动态获取阵列所有元素的所有组合

重要提示: 您只能从每个阵列中选择一个元素。动态获取阵列所有元素的所有组合

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

我正在考虑一种方法,它可以接受一个选项数组,并返回一个排列数组,但是我的大脑在第一个循环后中断。任何帮助将非常感激。

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"]] 

回答:

使用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)

以上是 动态获取阵列所有元素的所有组合 的全部内容, 来源链接: utcz.com/qa/265061.html

回到顶部