在JavaScript中创建组合

时间:2012-01-11 16:33:05

标签: javascript algorithm combinations cartesian-product

假设我在Javascript中有几组选项

var color  =  ["red", "blue", "green","yellow"];
var size   =  ["small", "medium", "large"];
var weight =  ["heavy", "light"];

在一个看起来像这个

的数组中获取这些选项的所有组合的有效算法是什么
["red and small and heavy", "red and small and light", "red and medium and heavy" ...]

这是警告

此功能必须能够采用任意数量的选项

我有一种感觉,这样做的正确方法是通过某种树遍历,但现在还没有完全考虑到这一点,我还没有喝咖啡

4 个答案:

答案 0 :(得分:7)

function permutations(choices, callback, prefix) {
    if(!choices.length) {
        return callback(prefix);
    }
    for(var c = 0; c < choices[0].length; c++) {
        permutations(choices.slice(1), callback, (prefix || []).concat(choices[0][c]));
    }
}

var color  =  ["red", "blue", "green","yellow"];
var size   =  ["small", "medium", "large"];
var weight =  ["heavy", "light"];

permutations([color, size, weight], console.log.bind(console));

似乎工作......

[ 'red', 'small', 'heavy' ]
[ 'red', 'small', 'light' ]
[ 'red', 'medium', 'heavy' ]
[ 'red', 'medium', 'light' ]
[ 'red', 'large', 'heavy' ]
[ 'red', 'large', 'light' ]
[ 'blue', 'small', 'heavy' ]
[ 'blue', 'small', 'light' ]
[ 'blue', 'medium', 'heavy' ]
[ 'blue', 'medium', 'light' ]
[ 'blue', 'large', 'heavy' ]
[ 'blue', 'large', 'light' ]
[ 'green', 'small', 'heavy' ]
[ 'green', 'small', 'light' ]
[ 'green', 'medium', 'heavy' ]
[ 'green', 'medium', 'light' ]
[ 'green', 'large', 'heavy' ]
[ 'green', 'large', 'light' ]
[ 'yellow', 'small', 'heavy' ]
[ 'yellow', 'small', 'light' ]
[ 'yellow', 'medium', 'heavy' ]
[ 'yellow', 'medium', 'light' ]
[ 'yellow', 'large', 'heavy' ]
[ 'yellow', 'large', 'light' ]

答案 1 :(得分:3)

答案 2 :(得分:1)

树遍历是要走的路,准确的递归。

工作原理是,在每个深度,您将遍历该深度的所有选项,在您的情况下,列表的选项。当你选择元素形式的最后深度时,你有一整套。

答案 3 :(得分:0)

上面#1中提到的console.log函数应该是:

function log(message){
    if(typeof console == "object"){
        console.log(message);
    }
}

然后,将对函数的调用更改为:

combinations([color, size, weight], log);