6

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)
harish
  • 295
  • 1
  • 12
  • I want to create these pairs because i have some other tables of two, three and four columns. I want to make these pairs and the value of these pairs is inserted in the tables according to columns pairs. – harish Mar 02 '14 at 11:45
  • In controller in the form of map. – harish Mar 02 '14 at 11:51

2 Answers2

3

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.

elm
  • 20,117
  • 14
  • 67
  • 113
2

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

Community
  • 1
  • 1
serejja
  • 22,901
  • 6
  • 64
  • 72
  • 2
    There is already a `subsets` method for `Set`, which returns an `Iterator` over all subsets: `List(1,2,3,4).toSet.subsets.filter(_.size > 1).toSet` – Kigyo Mar 02 '14 at 17:37