Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make column pairs of map?

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)
like image 770
harish Avatar asked Mar 02 '14 11:03

harish


2 Answers

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.

like image 134
elm Avatar answered Nov 05 '22 06:11

elm


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

like image 25
serejja Avatar answered Nov 05 '22 06:11

serejja