gpt4 book ai didi

javascript - 创建所有可能的组合 - javascript

转载 作者:行者123 更新时间:2023-11-30 17:28:48 25 4
gpt4 key购买 nike

如果这是重复的,我很抱歉,但我还没有找到解决我的问题的方法。我有 4 组单词,我需要创建所有可能的 4 组组合,但要保持组限制(即每组必须有一个单词,并且组中不能加倍)。

伪代码示例:

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

我真的不知道从哪里开始这样的事情。初始组是数组。

提前致谢。

最佳答案

这应该可以解决问题:

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));

关于javascript - 创建所有可能的组合 - javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23644465/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com