I'm trying to get all the possible combinations of a 3d array. I found a lot of answers for one- or two-dimensional arrays with recursive functions but no solution works for a deeper nested array.
The array structure is always the same (three levels), but the length of each level can change.
example code:
function getCombinations(arr){
...
}
var arr = [[[100, 200]], [[10, 20], [30, 40]]];
var arr2 = [[[100, 200]], [[10, 20], [50]], [[400, 500, 600]]];
res = getCombinations(arr);
res2 = getCombinations(arr2);
expected outputs:
// arr: [[[100, 200]], [[10, 20], [30, 40]]]
[
[[100], [10, 30]],
[[100], [10, 40]],
[[100], [20, 30]],
[[100], [20, 40]],
[[200], [10, 30]],
[[200], [10, 40]],
[[200], [20, 30]],
[[200], [20, 40]],
];
// arr2: [[[100, 200]], [[10, 20], [50]], [[400, 500, 600]]]
[
[[100], [10, 50], [400]],
[[100], [10, 50], [500]],
[[100], [10, 50], [600]],
[[100], [20, 50], [400]],
[[100], [20, 50], [500]],
[[100], [20, 50], [600]],
[[200], [10, 50], [400]],
[[200], [10, 50], [500]],
[[200], [10, 50], [600]],
[[200], [20, 50], [400]],
[[200], [20, 50], [500]],
[[200], [20, 50], [600]],
];
CodePudding user response:
By researching Cartesian product function, I get more knowledge to implement a solution
Certesion product function (answered by viebel at this question: Cartesian product of multiple arrays in JavaScript):
function cartesianProduct(arr) {
return arr.reduce(function (a, b) {
return a.map(function (x) {
return b.map(function (y) {
return x.concat([y]);
});
}).reduce(function (a, b) {
return a.concat(b);
}, []);
}, [[]]);
}
Nested call for deeper nested arrays:
let arr = [[[100, 200]], [[10, 20], [30, 40]]];
let res = cartesianProduct(arr.map(a => cartesianProduct(a)));
Thanks a lot to Scott Sauyet for the hint in the comments!
CodePudding user response:
My own version was similar, although I think my cartesian
function is a bit simpler.
const cartesian = ([xs, ...xss]) =>
xs == undefined ? [[]] : xs .flatMap (x => cartesian (xss) .map (ys => [x, ...ys]))
const getCombinations = (xss) =>
cartesian (xss .map (cartesian))
const arr = [[[100, 200]], [[10, 20], [30, 40]]];
const arr2 = [[[100, 200]], [[10, 20], [50]], [[400, 500, 600]]];
console .log (JSON .stringify (getCombinations (arr), null, 4))
console .log (JSON .stringify (getCombinations (arr2), null, 4))
.as-console-wrapper {max-height: 100% !important; top: 0}