Shakti
Shakti

Reputation: 2033

How to create all possible combinations from the elements of a list?

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 

Upvotes: 44

Views: 45320

Answers (4)

pagoda_5b
pagoda_5b

Reputation: 7373

def combine(in: List[Char]): Seq[String] = 
    for {
        len <- 1 to in.length
        combinations <- in combinations len
    } yield combinations.mkString 

Upvotes: 35

Kim Stebel
Kim Stebel

Reputation: 42047

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

Upvotes: 96

Santosh Gokak
Santosh Gokak

Reputation: 3411

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.

Upvotes: 10

Science_Fiction
Science_Fiction

Reputation: 3433

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.

Upvotes: 10

Related Questions