JavaScript中多个数组的笛卡尔积 [英] Cartesian product of multiple arrays in JavaScript

查看:896
本文介绍了JavaScript中多个数组的笛卡尔积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



举例来说,

  cartesian([1,2],[10,20],[100,200,300])//应该是
// [[1,10,100],[1,10,200], [1,10,300],[2,10,100],[2,10,200] ...]


解决方案

使用 reduce 和<$>解决问题的功能性解决方案(不含可变变量!) c $ c> flatten ,由 underscore.js 提供:

  function cartesianProductOf(){
return _.reduce(arguments,function(a,b){
return _.flatten(_。map(a,function(x){
return _.map(b,function(y){
return x.concat([y]);
});
}),true);
},[[]]);
};

cartesianProductOf([1,2],[3,4],['a','b']); // [[1,3,a],[1,3,b],[1,4,a],[1,4,b],[2,3,a ],[2,3,b],[2,4,a],[2,4,b]]

备注:此解决方案的灵感来源于 http://cwestblog.com/2011/05/02/cartesian-product-of-multiple-arrays/


How would you implement the Cartesian product of multiple arrays in JavaScript?

As an example,

cartesian([1,2],[10,20],[100,200,300]) //should be
// [[1,10,100],[1,10,200],[1,10,300],[2,10,100],[2,10,200]...]

解决方案

Here is a functional solution to the problem (without any mutable variable!) using reduce and flatten, provided by underscore.js:

function cartesianProductOf() {
    return _.reduce(arguments, function(a, b) {
        return _.flatten(_.map(a, function(x) {
            return _.map(b, function(y) {
                return x.concat([y]);
            });
        }), true);
    }, [ [] ]);
};

cartesianProductOf([1, 2], [3, 4], ['a', 'b']); // [[1,3,"a"],[1,3,"b"],[1,4,"a"],[1,4,"b"],[2,3,"a"],[2,3,"b"],[2,4,"a"],[2,4,"b"]] 

Remark: This solution was inspired by http://cwestblog.com/2011/05/02/cartesian-product-of-multiple-arrays/

这篇关于JavaScript中多个数组的笛卡尔积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆