algorithm - Finding All Combinations of JavaScript array values -
how can produce of combinations of values in n number of javascript arrays of variable lengths?
let's have n number of javascript arrays, e.g.
var first = ['a', 'b', 'c', 'd']; var second = ['e']; var third = ['f', 'g', 'h', 'i', 'j'];
(three arrays in example, n number of arrays problem.)
and want output combinations of values, produce
aef aeg aeh aei aej bef beg .... dej
edit: here's version got working, using ffriend's accepted answer 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 rest of array (var c in allcasesofrest) { (var = 0; < 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"]
this not permutations, see permutations definitions wikipedia.
but can achieve 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 rest of array (var = 0; < allcasesofrest.length; i++) { (var j = 0; j < arr[0].length; j++) { result.push(arr[0][j] + allcasesofrest[i]); } } return result; } }
you can make loops, bit tricky , require implementing own analogue of stack.
Comments
Post a Comment