JavaScript - 从具有m个元素的n个数组生成组合 [英] JavaScript - Generating combinations from n arrays with m elements

查看:182
本文介绍了JavaScript - 从具有m个元素的n个数组生成组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在编写代码时遇到麻烦,需要在JavaScript中生成包含m个元素的n个数组的组合。我已经在其他语言中看到了类似的问题,但答案包含语法或库魔法,我不确定如何翻译。

I'm having trouble coming up with code to generate combinations from n number of arrays with m number of elements in them, in JavaScript. I've seen similar questions about this for other languages, but the answers incorporate syntactic or library magic that I'm unsure how to translate.

考虑这些数据:

[[0,1], [0,1,2,3], [0,1,2]]

3个数组,其中包含不同数量的元素。我想要做的是通过组合每个数组中的项来获得所有组合。

3 arrays, with a different number of elements in them. What I want to do is get all combinations by combining an item from each array.

例如:

0,0,0 // item 0 from array 0, item 0 from array 1, item 0 from array 2
0,0,1
0,0,2
0,1,0
0,1,1
0,1,2
0,2,0
0,2,1
0,2,2

等等。

如果数组的数量是固定的,那么很容易进行硬编码实现。但阵列的数量可能会有所不同:

If the number of arrays were fixed, it would be easy to make a hard coded implementation. But the number of arrays may vary:

[[0,1], [0,1]]
[[0,1,3,4], [0,1], [0], [0,1]]

我们非常感谢任何帮助。

Any help would be much appreciated.

推荐答案

这是一个非常简单和简单的使用递归辅助函数:

Here is a quite simple and short one using a recursive helper function:

function cartesian() {
    var r = [], arg = arguments, max = arg.length-1;
    function helper(arr, i) {
        for (var j=0, l=arg[i].length; j<l; j++) {
            var a = arr.slice(0); // clone arr
            a.push(arg[i][j]);
            if (i==max)
                r.push(a);
            else
                helper(a, i+1);
        }
    }
    helper([], 0);
    return r;
}

用法:

cartesian([0,1], [0,1,2,3], [0,1,2]);

要使函数采用数组数组,只需将签名更改为 function cartesian(arg)这样 arg 是一个参数,而不是所有参数

To make the function take an array of arrays, just change the signature to function cartesian(arg) so that arg is a parameter instead of all arguments.

这篇关于JavaScript - 从具有m个元素的n个数组生成组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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