Chris
Chris

Reputation: 535

Get a list of partial lists

So I have a list of elements and I want to get a list of all lists which can be generated by selecting an arbitrary number of elements from the original list.

For this input: val input = List('a','b','a')

I expect this output: val input = List(List(), List('a'), List('b'), List('a','a'), List('a', 'b'), List('a','b','a'))

Note that I don't want to include List('b','b') since 'b' is only present once in the original collection and I dont't want List('b','a') since it is already included in a different order.

I have found several solutions of similar problems based on subsets method of the Set class or combinations method but none that fulfills all of my requirements:

Upvotes: 2

Views: 184

Answers (1)

jwvh
jwvh

Reputation: 51271

I think combinations() will do what you want. All sub-lists are presented in increasing order.

val input = List('a','b','a')

(0 to input.length).flatMap(input.combinations)
//res0: IndexedSeq[List[Char]] =
//      Vector(List(), List(a), List(b), List(a, a), List(a, b), List(a, a, b))

Upvotes: 3

Related Questions