我有 3 个具有一些可能值的变量。 例如:
Var1 - possible values: 1,2,3
Var2 - possible values: a, b, c
var3 - possible values: false, true
您能否提供一种返回所有可能组合的方法?
结果是这样的:
1,a,false
1,a,true,
1,b,false
1,b,true,
1,c,false
1,c,true
2,a,false
2,a,true
2,b,false
Etc..
我希望该算法可以应用于任何级别的组合,例如,该算法适用于具有其他可能值的 4 或 5 个变量。
最佳答案
看起来您正在尝试枚举 Cartesian products .假设您的项目在 list_of_lists
中,这个伪代码中的递归函数将执行此操作:
enumerate_cartesian_prducts(list_of_lists):
if list_of_lists is empty:
return [[]]
this_list = list_of_lists[0]
other_lists = list_of_lists[1: ]
other_cartesian_products = []
return [(e + other_cartesian_product) \
for e in this_list and other_cartesian_product in other_cartesian_products]
注意最后一行在大多数语言中可能是一个双循环:它遍历第一个列表中的所有元素,其余列表的笛卡尔积中的所有列表,并创建所有附加结果的列表。
关于algorithm - 返回多个变量的所有可能组合集的伪代码或 C# 算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30530425/