Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 views
in Technique[技术] by (71.8m points)

javascript - 查找JavaScript数组值的所有组合(笛卡尔积)(Finding All Combinations (Cartesian product) of JavaScript array values)

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, eg(假设我有N个JavaScript数组,例如) var first = ['a', 'b', 'c', 'd']; var second = ['e']; var third = ['f', 'g', 'h', 'i', 'j']; (Three arrays in this example, but its N number of arrays for the problem.)((此示例中为三个数组,但是有N个数组用于解决此问题。)) And I want to output all the combinations of their values, to produce(我想输出其值的所有组合,以产生) aef aeg aeh aei aej bef beg .... dej EDIT: Here's the version I got working, using ffriend's accepted answer as the basis.(编辑:这是我使用ffriend接受的答案作为基础的版本。) 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"]   ask by Yahel translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is not permutations, see permutations definitions from Wikipedia.(这不是排列,请参阅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.(您也可以使用循环来实现它,但是这会有些棘手,并且需要实现自己的堆栈模拟。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...