动态获取阵列所有元素的所有组合
问题描述:
重要提示: 您只能从每个阵列中选择一个元素。动态获取阵列所有元素的所有组合
我正在写代码,让我测试测验排列。下面是我返回所有可能的排列数组的当前硬编码方式。我需要适应这是动态的,因为稍后会添加更多的数组。
我正在考虑一种方法,它可以接受一个选项数组,并返回一个排列数组,但是我的大脑在第一个循环后中断。任何帮助将非常感激。
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)
我会很快接受,谢谢,知道有东西在那里。 – jahrichie 2014-09-20 22:04:42
我认为你的意思是'产品',你有'排列'。 (当你看到它时,我会删除这条评论。) – 2014-09-21 00:09:06
你也可以这样做:'arrays_to_permute.delete.product(* arrays_to_permute)'。最好不要在变量名中包含'permute',因为这不涉及置换。组合,是的;排列,没有。 – 2014-09-21 00:11:20