-1

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.

tmesis
  • 347
  • 1
  • 3
  • 8
  • 2
    So, when you were _trying_ to do it, what were the problems you ran into? – Dima Jul 16 '16 at 02:04
  • Simply said, I couldn't manipulate the permutation function to generate the lists as shown. – tmesis Jul 16 '16 at 02:07
  • I tried what jwvh suggested, and the following: val test = List(1,2,3).toSet[Int].subsets.map(_.toList).toList val test = List.range(0, 2).toList.transpose val test = for { v <- List.range(0, 3) s <- List.range(1, 6) } yield (v, s) – tmesis Jul 16 '16 at 23:30

1 Answers1

1

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.

jwvh
  • 50,871
  • 7
  • 38
  • 64
  • It does not create all possible combinations--sequence matters. For instance, nothing like (3, 0, 1, 0) is created. Thoughts? – tmesis Jul 16 '16 at 23:29
  • @tmesis, oops. Updated. The result won't be in an obvious order, but it should be complete. – jwvh Jul 17 '16 at 00:22
  • That is an elegant solution. I tried adding `permutations` to your initial response but it yielded a wild result. Would you please explain why your fix worked but my attempt produced excessive output? – tmesis Jul 17 '16 at 00:27