[英]Create All Possible Combinations - javascript
I'm sorry if this is a duplicate, but I haven't found a solution to my problem. 很抱歉,如果这是重复的,但是我没有找到解决问题的方法。 I have 4 groups of words, I need to create all possible combinations of 4, yet keeping group restrictions (ie. there must be a word from each group and no doubling from a group).
我有4组单词,我需要创建4组的所有可能组合,但要保持组限制(即,每个组中必须有一个单词,并且组中不能有重复)。
Psuedo-code example: 伪代码示例:
Group1 = [A1, A2]
Group2 = [B1, B2]
Group3 = [C1, C2]
Group4 = [D1, D2]
Result:
A1 B1 C1 D1,
A2 B1 C1 D1,
A1 B2 C1 D1 ...
Unacceptable:
A1 A2 B1 C1,
A1 B1 B2 C1
I really don't even know where to start something like this. 我什至不知道从哪里开始这样的事情。 Initial groups are arrays.
初始组是数组。
Thanks in advance. 提前致谢。
This should do the trick: 这应该可以解决问题:
function cartesian() {
var r = [], arg = arguments, max = arg.length-1; //r=results, arg=the arrays you sent, max=number of arrays you sent
function helper(arr, i) {// this is a recursive function
for (var j=0, l=arg[i].length; j<l; j++) { //for 0 to the current array's length
var a = arr.slice(0); // clone array sent
a.push(arg[i][j]) // add string
if (i==max) { // reached 4 elements, add that as possibility
r.push(a);
} else // if its not 4, call recursive function sending the current possibility array and the following index of the array to choose from
helper(a, i+1);
}
}
helper([], 0); // this starts the recursive function, sending an empty array and index 0 (start with nothing from 0)
return r; // after recursive function ends, return possibilities
};
Group1 = ["A1", "A2"]
Group2 = ["B1", "B2"]
Group3 = ["C1", "C2"]
Group4 = ["D1", "D2"]
console.log(cartesian(Group1,Group2,Group3,Group4));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.