ruby - Generate different combinations of arrays using positive integers as elements -
given integer n
, different integer k
(both positive) want generate possible different arrays of size k
containing integers in interval [0..n]
. example n = 2
, k = 2
want generate array of arrays contains [0,0]
, [0,1]
, [1,0]
, [0,2]
, [1,1]
, [2,0]
, [1,2]
, [2,1]
, [2,2]
. result should be
result = [[0,0], [0,1], [1,0], [0,2], [1,1], [2,0], [1,2], [2,1], [2,2]]
the order of elements doesn't matter.
use array#repeated_permutation
:
(0..2).to_a.repeated_permutation(2).to_a # => [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]
Comments
Post a Comment