[英]All combinations of properties in an array
好吧,过去几天我一直在为此烦恼。 什么是最好的(没有巨大开销的任何东西)生成所有可能组合的数组的方法
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
所有b
的, c
的和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,{})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.