I know how to create permutations of an array of values. For example:
[*1..3].permutation(2)
which results in the following six permutations:
[1, 2]
[1, 3]
[2, 1]
[2, 3]
[3, 1]
[3, 2]
But this result is missing the three permutations, which are combinations of the same value, i.e.:
[1, 1]
[2, 2]
[3, 3]
How can I get all the permutations, including repeated ones above?
Try #repeated_permutation:
[*1..3].repeated_permutation(3).to_a
> pp [*1..3].repeated_permutation(3).to_a
[[1, 1, 1],
[1, 1, 2],
[1, 1, 3],
[1, 2, 1],
[1, 2, 2],
[1, 2, 3],
[1, 3, 1],
[1, 3, 2],
[1, 3, 3],
[2, 1, 1],
[2, 1, 2],
[2, 1, 3],
[2, 2, 1],
[2, 2, 2],
[2, 2, 3],
[2, 3, 1],
[2, 3, 2],
[2, 3, 3],
[3, 1, 1],
[3, 1, 2],
[3, 1, 3],
[3, 2, 1],
[3, 2, 2],
[3, 2, 3],
[3, 3, 1],
[3, 3, 2],
[3, 3, 3]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With