2013-03-10 84 views
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]+"]"); 
     } 
    }   
} 

回答

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);