javascript - 数组中所有属性的组合

标签 javascript combinatorics

好吧,在过去的几天里,我一直在为这件事伤脑筋。生成所有可能组合的数组的最简洁(任何没有巨大开销的方法)是什么

var input = [
    {a: 1}, {a: 2, b: 3},
    {b: 4}, {b: 5}, {a: 6}
];

所以我希望生成的是以下内容:

var output = [
    {a: 1}, {b: 4}, {b: 5}, {a: 6},
    {a: 1, b: 4}, {a: 1, b: 5},
    {a: 6, b: 4}, {a: 6, b: 5},
    {a: 2, b: 3}
];

虽然在我的具体情况下我谈论的是 4 个属性(实际上我需要为每组不同的属性集生成一个单独的数组,但是这些都是我以后应该能够自己实现的东西) .然而,我正在寻找的只是一些关于如何解决这个问题的通用伪代码,而不是有人为我编写它或类似的东西。

我觉得这应该是我应该能够弄清楚的事情,但我就是没有做到。首先,我为所有属性组合生成单独的数组(所有 a、所有 b、所有 c、所有 ab,所有 bc,等等)。然而,问题是,有了 3 个属性,您接下来必须为每个 a 添加所有 bc bc 的。现在,为单个属性写出它已经很简单了,但是为 n 个属性编写一个通用解决方案却完全让我望而却步。

最佳答案

我不确定我是否真的理解这些要求,但您可以按照这些思路尝试递归解决方案(使用伪代码而不是 javascript):

def generate(i,C):
    # C is a dictionary representing the currently defined properties
    # We are allowed to add to our set of properties from the choices input[i],input[i+1],...

    # First choose a non-conflicting set of additional properties to add
    while i<len(input):
        if all of properties in input[i] are not in C:
             Add properties in input[i] to C
             solutions.append(C)
             generate(i+1,C)
             Remove properties in input[i] from C
        i++

generate(0,{})

关于javascript - 数组中所有属性的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26066921/

相关文章:

javascript没有获得值(value)

javascript - JS - 如何正确使用setTimeout()

algorithm - 矩阵中的路径数

java - 如果您只能投资 10 美元增量,则输出投资 10 只股票的方式总数

python - 创建独特的单败淘汰赛的方法

javascript - 如何订购运行 ajax 的 jQuery 然后必须返回 true

javascript - 有人可以解释以下 javascript 代码片段吗? (小白)

javascript - jQuery 和 Prototype 方法相互干扰

algorithm - 旅行商 (TSP) : what is the Relation with number of vertices and length of the found route?

algorithm - n 个对象的排列(重复排列)