ruby on rails - All variants of an array -
i have array structured one:
array = ["one","two","three","four"];
how can possible variants of array, in possible lengths 1-4:
ar = [["one"]["two"]["three"]["four"]["one","two"] ["one","three"] ["one","three","four"]]
i think in end there should 4*4*4*4 elements in array.
how can possible variants of array[...]
use array#combination
:
array.combination(3).to_a
result:
[["one", "two", "three"], ["one", "two", "four"], ["one", "three", "four"], ["two", "three", "four"]]
[...]in possible lengths 1-4
use range, iterate on enumerable#flat_map
:
(1..array.length).flat_map {|len| array.combination(len).to_a }
result:
[["one"], ["two"], ["three"], ["four"], ["one", "two"], ["one", "three"], ["one", "four"], ["two", "three"], ["two", "four"], ["three", "four"], ["one", "two", "three"], ["one", "two", "four"], ["one", "three", "four"], ["two", "three", "four"], ["one", "two", "three", "four"]]
ruby-on-rails ruby arrays ruby-on-rails-3 combinatorics
No comments:
Post a Comment