algorithm - 返回多个变量的所有可能组合集的伪代码或 C# 算法

标签 algorithm set combinations

我有 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/

相关文章:

java - 递归代码到非递归循环

performance - 在二维空间中查找矩形

algorithm - 可以检查位集子集的类似 Map<bitset,object> 的数据结构?

python - 列表中多个集合的交集

c++ - GCC 树 STL 数据容器

python - 我为快乐号码检查器编写的代码无法正常工作,有人可以检查一下吗?

algorithm - 收敛于元素的最佳组合

algorithm - 多重图和最便宜的路径

algorithm - 如何测试完美优化的算法?

python - 来自单独数组中纬度/经度坐标的(纬度,经度)的所有可能点