-1
重要提示: 您只能從每個陣列中選擇一個元素。動態獲取陣列所有元素的所有組合
我正在寫代碼,讓我測試測驗排列。下面是我返回所有可能的排列數組的當前硬編碼方式。我需要適應這是動態的,因爲稍後會添加更多的數組。
我正在考慮一種方法,它可以接受一個選項數組,並返回一個排列數組,但是我的大腦在第一個循環後中斷。任何幫助將非常感激。
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"]]
我會很快接受,謝謝,知道有東西在那裏。 – 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