给出多组值。我希望在保留订单的同时找到这些值的每个组合(抱歉,我使用的这个术语很松散,但不确定正确的词是什么)。
即
var set1 = ["a","1"];
var set2 = ["b","2"];
var set3 = ["c","3"];
输出应为
[a][b][c]
[a][b][3]
[a][2][c]
[a][2][3]
[1][b][c]
[1][b][3]
[1][2][c]
[1][2][3]
这提供了正确的结果,但我不认为这是一个非常好的解决方案,但是我无法以递归的方式解决这个问题。这个例子是在Javascript中,但任何语言或见解都很好。
var set1 = ["a","1"];
var set2 = ["b","2"];
var set3 = ["c","3"];
var input = [set1, set2, set3];
var result = [];
for(var a=0;a<input[0].length;a++){
for(var i=0;i<input[1].length;i++){
for(var j=0;j<input[2].length;j++){
var output = [];
output.push(input[0][a]);
output.push(input[1][i]);
output.push(input[2][j]);
result.push(output);
console.log("["+input[0][a]+"]["+input[1][i]+"]["+input[2][j]+"]");
}
}
}
答案 0 :(得分:0)
当然,你可以递归地探索这样的空间:
function extend_set (base, sets) {
if(sets.length === 0) {
return console.log('found: '+base);
}
sets = sets.slice();
var choices = sets.shift();
for (var i = 0; i < choices.length; i += 1) {
var b2 = base.slice();
b2.push(choices[i]);
extend_set(b2, sets);
}
}
var set1 = ["a","1"];
var set2 = ["b","2"];
var set3 = ["c","3"];
var sets = [set1, set2, set3];
extend_set([], sets);