Search code examples
listscalapermutationseq

creating all permutations of a list with a limited range in Scala


I am trying to create a sequence of n-element lists comprising all permutations for a given range. Would like to parameterize both the number of elements and range. Example:

Length: 4, Range: [0, 3]

Seq(List(0, 0, 0, 0), List(0, 0, 0, 1), ..., List(3, 3, 3, 3), ..., List(1, 0, 0, 0))

Thank you in advance.


Solution

  • This will get you there.

    List.fill(4)(0 to 3).flatten.combinations(4).flatMap(_.permutations)
    

    It returns an Iterator that can be cast to Seq, List, Vector, whatever.

    You need n copies of the range so that combinations() will allow n repetitions of each number within the range.


    Explanation

    combinations is all about ignoring the order of the elements, so (0,1) is considered the same as (1,0) and only one of them will be presented. You also have to tell it the size of the sub-groups.

    permutations is all about reordering the given elements, so (2,2) has only one permutation, itself, while (0,0,1) has 3: (0,0,1) (0,1,0) (1,0,0)

    After combinations has created the initial groupings of the elements, each one is fed to permutations to get all possible re-orderings.