在JavaScript中创建组合
假设我有几个Javascript选项集在JavaScript中创建组合,javascript,algorithm,combinations,cartesian-product,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
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" ...]
不过这里有个警告
此功能必须能够接受任意数量的选项集
我有一种感觉,正确的方法是通过某种形式的树遍历,但现在想清楚这一点还为时过早,而且我还没有喝过咖啡,那将是这些集合的笛卡尔积:
另请参见:树遍历是一种方法,确切地说是递归
工作原理是,在每个深度,您将迭代该深度的所有选项,在您的示例中是列表的选项。当您选择element form last depth时,您有一个完整的集合。上面#1中提到的console.log函数应该是:
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));
function log(message){
if(typeof console == "object"){
console.log(message);
}
}
然后,将对函数的调用更改为:
combinations([color, size, weight], log);
太棒了,太棒了。我知道这必须是已经做过的事情。“JavaScript高尔夫…”页面被删除:(在chrome调试器中不起作用,除非你将console.log包装到匿名函数中。不管怎样,这都是很棒的工作!对不起,是的。我在node.js 0.6.x中测试了这个,而不是在浏览器中。我忘了在帖子中提到这一点。上面#1中提到的console.log函数应该是:函数日志(消息){if(typeof console==“object”){console.log(message);}}然后,将对函数的调用更改为:combines([color,size,weight],log);“bind”是您的朋友:combines([color,size,weight],console.log.bind(console));
combinations([color, size, weight], log);