可以说我在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" ...]
这是警告
此功能必须能够采用任何数量的选项
我觉得这样做的正确方法是通过某种树的遍历,但是为时过早,无法完全考虑到这一点,而且我还没有喝咖啡
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' ]