【发布时间】:2017-05-02 21:16:07
【问题描述】:
我想做的是处理 n 个集合,而我在下面提供的代码正好可以处理 4 个集合。
def show_combinations
@combos = []
['A', 'no A'].each do |a|
['B', 'no B'].each do |b|
['C', 'no C'].each do |c|
['D', 'no D'].each do |d|
@combos << [a, b, c, d]
end
end
end
end
end
如何重构以下代码来处理以下场景: 假设我有一个大小为 y 的数组,其中包含大小为 n 的数组,我想返回所有组合。 请务必注意,每个子数组中只能有一个项目出现在结果中。 (如“已完成配置文件”也不能出现在带有“未完成配置文件”的结果中)
背景:
用户可能有一些任务:例如,“完成个人资料”或“设置电子邮件”等。这些任务可以这样表示:
@task_states = [["Completed Profile, NOT Completed Profile"], ["Set up Email", "NOT set up Email"]]
然后,将@task_states 传递给方法,结果应该是这样的:
[
["Completed Profile", "Set up Email"],
["Completed Profile", "NOT set up Email"],
["NOT Completed Profile", "Set up Email"],
["NOT Completed Profile", "NOT Set up Email"]
]
所以一个代表所有组合的数组数组。显然“Completed Profile”也不能和“NOT Completed Profile”等在同一个数组中。
谢谢!
【问题讨论】:
-
你的意思是数组的笛卡尔积吗?