How to make pairs of map columns?

I have some columns like

age | company | country | gender | ---------------------------------- 1 | 1 | 1 | 1 | ----------------------------------- 

I want to create pairs like

  • (age, company)
  • (company, country)
  • (country, gender)
  • (company, gender)
  • (age, gender)
  • (age, country)
  • (age, company, country)
  • (company, country, gender)
  • (age, country, gender)
  • (age, company, gender)
  • (age, company, country, gender)
+6
source share
2 answers

An idiomatic approach to generating power sets using the Set collection 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 

provides

 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)) 

Please note that the set includes an empty set and a set for each element in the original set, here we filter them.

+3
source

I doubt that you can achieve this with tuples ( and this question confirms this ). 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])) } } 

Doing 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.

+2
source

All Articles