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

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

问题描述

您将如何在 JavaScript 中实现多个数组的笛卡尔积?

举个例子

笛卡尔([1, 2], [10, 20], [100, 200, 300])

应该返回

<预><代码>[[1, 10, 100],[1, 10, 200],[1, 10, 300],[2, 10, 100],[2, 10, 200]...]

解决方案

这里是使用 reduceflatten,由 underscore.js 提供:

function cartesianProductOf() {返回 _.reduce(参数,函数(a,b){返回 _.flatten(_.map(a, function(x) {返回 _.map(b, function(y) {返回 x.concat([y]);});}), 真的);}, [ [] ]);}//[[1,3,"a"],[1,3,"b"],[1,4,"a"],[1,4,"b"],[2,3,"a"],[2,3,"b"],[2,4,"a"],[2,4,"b"]]console.log(cartesianProductOf([1, 2], [3, 4], ['a']));

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js"></script>

备注:此解决方案的灵感来自 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 return

[
  [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);
    }, [ [] ]);
}

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

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js"></script>

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

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

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