0

给定多组值。我想在保留顺序的同时找到这些值的每个组合(抱歉,我使用这个术语松散但不确定正确的词是什么)。

即对于

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]+"]");
        }
    }           
}   
4

1 回答 1

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);
于 2013-03-10T20:13:06.087 回答