Get a list of partial lists

Viewed 114

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:

  • Allow for duplicates in the original collection
  • Have "sublists" of arbitrary size
  • Exclude "sublists" which are already present in a different order.
1 Answers

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