[英]Create All Possible Combinations - javascript
很抱歉,如果這是重復的,但是我沒有找到解決問題的方法。 我有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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.