查找JavaScript数组值的所有组合(笛卡尔积) [英] Finding All Combinations (Cartesian product) of JavaScript array values
问题描述
如何在N个可变长度的JavaScript数组中生成值的所有组合?
How can I produce all of the combinations of the values in N number of JavaScript arrays of variable lengths?
假设我有N个JavaScript数组,例如
Let's say I have N number of JavaScript arrays, e.g.
var first = ['a', 'b', 'c', 'd'];
var second = ['e'];
var third = ['f', 'g', 'h', 'i', 'j'];
(在此示例中为三个数组,但对于问题,使用N个数组)。
(Three arrays in this example, but its N number of arrays for the problem.)
我想输出其值的所有组合,以产生
And I want to output all the combinations of their values, to produce
aef
aeg
aeh
aei
aej
bef
beg
....
dej
编辑:这是我使用的版本,使用ffriend接受的答案作为基础
Here's the version I got working, using ffriend's accepted answer as the basis.
var allArrays = [['a', 'b'], ['c', 'z'], ['d', 'e', 'f']];
function allPossibleCases(arr) {
if (arr.length === 0) {
return [];
}
else if (arr.length ===1){
return arr[0];
}
else {
var result = [];
var allCasesOfRest = allPossibleCases(arr.slice(1)); // recur with the rest of array
for (var c in allCasesOfRest) {
for (var i = 0; i < arr[0].length; i++) {
result.push(arr[0][i] + allCasesOfRest[c]);
}
}
return result;
}
}
var r=allPossibleCases(allArrays);
//outputs ["acd", "bcd", "azd", "bzd", "ace", "bce", "aze", "bze", "acf", "bcf", "azf", "bzf"]
推荐答案
这不是排列,请参阅Wikipedia中的排列定义。
This is not permutations, see permutations definitions from Wikipedia.
但是您可以通过递归来实现:
But you can achieve this with recursion:
var allArrays = [['a', 'b'], ['c'], ['d', 'e', 'f']]
function allPossibleCases(arr) {
if (arr.length == 1) {
return arr[0];
} else {
var result = [];
var allCasesOfRest = allPossibleCases(arr.slice(1)); // recur with the rest of array
for (var i = 0; i < allCasesOfRest.length; i++) {
for (var j = 0; j < arr[0].length; j++) {
result.push(arr[0][j] + allCasesOfRest[i]);
}
}
return result;
}
}
您也可以使用循环,但这会有些棘手,并且需要实现自己的堆栈模拟。
You can also make it with loops, but it will be a bit tricky and will require implementing your own analogue of stack.
这篇关于查找JavaScript数组值的所有组合(笛卡尔积)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!