繁体   English   中英

js中获取3d数组的所有组合

[英]Get all the combinations of 3d array in js

我正在尝试获取 3d 数组的所有可能组合。 我用递归函数找到了很多一维或二维 arrays 的答案,但没有解决方案适用于更深的嵌套数组。

数组结构始终相同(三层),但每一层的长度可以改变。

示例代码:

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);

预期产出:

// 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]],
];

我自己的版本是相似的,虽然我认为我的cartesian function 有点简单。

 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}

通过研究笛卡尔积 function ,我获得了更多知识来实施解决方案

Certesion 产品 function( viebel在这个问题上回答: 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);
        }, []);
    }, [[]]);
}

嵌套调用更深的嵌套 arrays:

let arr = [[[100, 200]], [[10, 20], [30, 40]]];
let res = cartesianProduct(arr.map(a => cartesianProduct(a)));

非常感谢Scott Sauyet在评论中提供的提示!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM