Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeated Permutation

Tags:

ruby

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?

like image 982
Kokizzu Avatar asked Oct 01 '12 05:10

Kokizzu


1 Answers

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]]
like image 175
Chris Heald Avatar answered Oct 14 '22 09:10

Chris Heald