Ruby one-time permutation

I know how to create a permutation with ruby:

x = [*1..6] x.permutation.each { |y| py } 

that leads to:

 [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 6, 5] [1, 2, 3, 5, 4, 6] [1, 2, 3, 5, 6, 4] [1, 2, 3, 6, 4, 5] ... [6, 5, 4, 3, 1, 2] [6, 5, 4, 3, 2, 1] 

Is there any single ruler code to generate a repeated permutation, for example:

 x = [1,2,3] x.something.each { |y| py } 

which give the result:

 [1,1,1] [1,1,2] [1,1,3] [1,2,1] [1,2,2] ... [3,3,2] [3,3,3] 
+4
source share
2 answers

Try # repeat_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]] 
+10
source

I noticed that your question asked combinations, but your example used repeated permutations. If you are really interested in making real combinations, then a quick and dirty way to do this:

 >> x = [* ?a..?c] => ["a", "b", "c"] >> (0..x.length).each{|i| x.combination(i){|y| py}} [] ["a"] ["b"] ["c"] ["a", "b"] ["a", "c"] ["b", "c"] ["a", "b", "c"] 
+5
source

Source: https://habr.com/ru/post/1437106/


All Articles