I need to generate all the possible combinations of N numbers including repetitions.
Problem input: I have N cells where I can put one number in the interval 0 to: 9, in each cell.
Wrong solution (with N = 4):
(0 to: 3) permutationsDo: [ : each | Transcript cr; show: each printString].
Does not includes #(0 0 0 0) , #(1 1 1 1) , #(2 2 2 2), etc.
Expected output (with N = 2, and range 1-4 for the sake of brevity):
#(1 1)
#(2 2)
#(3 3)
#(4 4)
#(2 1)
#(3 2)
#(4 3)
#(1 4)
#(3 1)
#(4 2)
#(1 3)
#(2 4)
#(4 1)
#(1 2)
#(2 3)
#(3 4)
Here are a couple of selectors with which you could extend
SequenceableCollection. That's the class wherepermutationsDo:is defined and is inherited, ultimately, by theIntervalclass.Category "enumerating":
Category "private":
So now you can do:
Which yields:
This selector operates "symmetrically" like the existing
permutationsDo:selector does, which is the number of elements in the resulting arrays (number of choices) is the same as the number of values in the collection.You can easily go from that to a more general solution:
Under "enumerating":
Under "private":
Here's an example:
Which yields: