3

假设我在 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

4 回答 4

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' ]
于 2012-01-11T16:40:45.223 回答
3

那将是这些集合的笛卡尔积:http ://en.wikipedia.org/wiki/Cartesian_product

另请参阅:https ://stackoverflow.com/questions/4796678/javascript-golf-cartesian-product

于 2012-01-11T16:35:50.440 回答
1

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

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

于 2012-01-11T16:37:12.030 回答
0

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

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

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

combinations([color, size, weight], log);
于 2012-10-07T03:07:00.200 回答