I have some columns like
age | company | country | gender |
----------------------------------
1 | 1 | 1 | 1 |
-----------------------------------
I want to create pairs like
An idiomatic approach to generating a powerset using Set
collection method subsets
,
implicit class groupCols[A](val cols: List[A]) extends AnyVal {
def grouping() = cols.toSet.subsets.filter { _.size > 1 }.toList
}
Then
List("age","company","country","gender").grouping
delivers
List( Set(age, company),
Set(age, country),
Set(age, gender),
Set(company, country),
Set(company, gender),
Set(country, gender),
Set(age, company, country),
Set(age, company, gender),
Set(age, country, gender),
Set(company, country, gender),
Set(age, company, country, gender))
Note that the powerset includes the empty set and a set for each element in the original set, here we filter them out.
I doubt you can achieve this with tuples (and this topic confirms it).
But what you are looking for is called Power Set
.
Consider this piece of code:
object PowerSetTest extends Application {
val ls = List(1, 2, 3, 4)
println(power(ls.toSet).filter(_.size > 1))
def power[A](t: Set[A]): Set[Set[A]] = {
@annotation.tailrec
def pwr(t: Set[A], ps: Set[Set[A]]): Set[Set[A]] =
if (t.isEmpty) ps
else pwr(t.tail, ps ++ (ps map (_ + t.head)))
pwr(t, Set(Set.empty[A]))
}
}
Running this gives you:
Set(Set(1, 3), Set(1, 2), Set(2, 3), Set(1, 2, 3, 4), Set(3, 4), Set(2, 4), Set(1, 2, 4), Set(1, 4), Set(1, 2, 3), Set(2, 3, 4), Set(1, 3, 4))
You can read here for more information
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With