如何在javascript中实现不同长度的n数组的笛卡尔积?

时间:2014-09-25 14:19:34

标签: javascript arrays

让我们说我有以下数组:

data[size] = Array('s', 'm');
data[color] = Array('blue', 'red');

我需要一个输出以下数组的函数

variations[] = Array('s', 'blue');
variations[] = Array('s', 'red');
variations[] = Array('m', 'blue');
variations[] = Array('m', 'red');

该函数也必须适用于以下数组:

data[size] = Array('s', 'm', 'l');
data[color] = Array('blue', 'red');
data[version] = Array('run', 'walk');

它应该给出一个类似

的数组
variations[] = Array('s', 'blue', 'run');
variations[] = Array('s', 'blue', 'walk');
variations[] = Array('s', 'red', 'run');
variations[] = Array('s', 'red', 'walk');

等等......

我该如何实施呢?

p.s。:如果此问题有特定名称,请告诉我,以便我编辑问题标题以备将来使用

3 个答案:

答案 0 :(得分:1)

以下工作有n个数组:

function cartesianProduct(data) {

    var current = [[]];
    for (var p in data) {
        var arr = data[p];
        var newCurrent = [];
        for (var c = 0; c < current.length; c++) {
            var baseArray = current[c];
            for (var a = 0; a < arr.length; a++) {
                var clone = baseArray.slice();
                clone.push(arr[a]);
                newCurrent.push(clone);
            }
        }
        current = newCurrent;
    }

    return current;
}

以下数据:

var data = {
    size: ['s', 'm'],
    color: ['blue', 'red'],
    version: ['run', 'walk', 'jump']
};

将返回所有组合:

var variations = [
    ["s","blue","run"],
    ["s","blue","walk"],
    ["s","blue","jump"],
    ["s","red","run"],
    ["s","red","walk"],
    ["s","red","jump"],
    ["m","blue","run"],
    ["m","blue","walk"],
    ["m","blue","jump"],
    ["m","red","run"],
    ["m","red","walk"],
    ["m","red","jump"]
];

答案 1 :(得分:0)

你的语法不是有效的JS,似乎是PHP。

我认为你有

var data = {
    size: ['s', 'm'],
    color: ['blue', 'red']
};

你想要

var variations = [
    ['s', 'blue'],
    ['s', 'red'],
    ['m', 'blue'],
    ['m', 'red']
];

为此,您可以使用

var variations = [];
for (var i=0; i<data.size.length; ++i)
    for (var j=0; j<data.color.length; ++j)
        variations.push([data.size[i], data.color[j]]);

答案 2 :(得分:0)

尝试了一些奇特的东西,在当地工作:

var variations = []
var str = "";
var ind = 0;
index = [];

for (var k in data)
{
    index[index.length] = k;
    str+="for(var i"+ind+" in data["+k+"])";
    ind++;
}
str += "{variations[variations.length] = [";
for (;ind >= 0; ind--)
{
    str+="data["+index[ind]+"][i"+ind+"]";
    if (ind > 0) str += ",";
    else str+="];";
}
str+= "}";

eval(str);

这允许在data =)

中包含任意数量的数组