43

I have the following list:

List(a, b, c, d, e)

How to create all possible combinations from the above list?

I expect something like:

a
ab
abc 
kiritsuku
  • 52,967
  • 18
  • 114
  • 136
Shakti
  • 2,013
  • 8
  • 27
  • 40

4 Answers4

95

Or you could use the subsets method. You'll have to convert your list to a set first though.

scala> List(1,2,3).toSet[Int].subsets.map(_.toList).toList
res9: List[List[Int]] = List(List(), List(1), List(2), List(3), List(1, 2), List(1, 3), List(2, 3), List(1, 2, 3))
Kim Stebel
  • 41,826
  • 12
  • 125
  • 142
35
def combine(in: List[Char]): Seq[String] = 
    for {
        len <- 1 to in.length
        combinations <- in combinations len
    } yield combinations.mkString 
pagoda_5b
  • 7,333
  • 1
  • 27
  • 40
  • True. But the way I used to do this was waaaay hairier =P – Tiago Farias May 12 '13 at 05:42
  • The method `combinations(length)` defined on `List`, gives you back a further iterator of sublists of limited length generated by combining the elements of the original list in any possible way. The for comprehension gives you all possible combinations for all lengths between 1 and the whole original list's length. The `combinations` assigned on the left of `<-` is one such possible shuffle. The `yield` gives you back a List of all those possible combinations. Check [the docs](http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.List@combinations(n:Int):Iterator[Repr]) – pagoda_5b Jul 25 '16 at 19:22
10
val xs = List( 'a', 'b' , 'c' , 'd' , 'e' )
(1 to xs.length flatMap (x => xs.combinations(x))) map ( x => x.mkString(""))

This should give you all the combination concatenated by empty String.

Santosh Gokak
  • 3,393
  • 3
  • 22
  • 24
9
def powerset[A](s: Set[A]) = s.foldLeft(Set(Set.empty[A])) { case (ss, el) => ss ++ ss.map(_ + el) }

Sounds like you need the Power set.

Science_Fiction
  • 3,403
  • 23
  • 27