动态获取所有数组元素的所有组合

时间:2014-09-20 21:57:46

标签: ruby-on-rails ruby permutation

重要: 您只能从每个数组中选择一个元素。

我正在编写代码,让我测试测验排列。下面是当前硬编码的方式,我返回所有可能排列的数组。我需要将其调整为动态,因为稍后会添加更多数组。

我在想一个接受一系列选项的方法,并返回一个排列数组,但是我的大脑在第一个循环之后断了。任何帮助将非常感激。

options =
[
  [["Geek", "Chef", "Supporter", "Fashionista"]],
  [["0-1000", "1001-10000", "No limit"]],
  [["Many", "For One"]]
]


def test_gifts(options)
  options.each_with_index do |a,index|
   ....
  end
end

坚持使用方式:

character_types = ["Geek","Chef", "Supporter", "Fashionista"]
price_ranges    = ["0-1,000","1,001-10000","No limit"]
party_size      = ["Many", "For One"]


permutations = []
character_types.each do |type|
  price_ranges.each do |price|
    party_size.each do |party|
      permutations << [type, price, party]
    end    
  end
end

返回

[["Geek", "0-1,000", "Many"], ["Geek", "0-1,000", "For One"], ["Geek", "1,001-10000", "Many"], ["Geek", "1,001-10000", "For One"], ["Geek", "No limit", "Many"], ["Geek", "No limit", "For One"], ["Chef", "0-1,000", "Many"], ["Chef", "0-1,000", "For One"], ["Chef", "1,001-10000", "Many"], ["Chef", "1,001-10000", "For One"], ["Chef", "No limit", "Many"], ["Chef", "No limit", "For One"], ["Supporter", "0-1,000", "Many"], ["Supporter", "0-1,000", "For One"], ["Supporter", "1,001-10000", "Many"], ["Supporter", "1,001-10000", "For One"], ["Supporter", "No limit", "Many"], ["Supporter", "No limit", "For One"], ["Fashionista", "0-1,000", "Many"], ["Fashionista", "0-1,000", "For One"], ["Fashionista", "1,001-10000", "Many"], ["Fashionista", "1,001-10000", "For One"], ["Fashionista", "No limit", "Many"], ["Fashionista", "No limit", "For One"]] 

1 个答案:

答案 0 :(得分:3)

使用Array#product方法:

character_types.product(price_ranges, party_size)

处理未知数量的其他数组:

arrays_to_permute = [character_types, price_ranges, party_size]
first_array, *rest_of_arrays = arrays_to_permute
first_array.product(*rest_of_arrays)