2013-04-03 76 views
0

我有參數列表的列表,我希望將它們組合在一起進行所有可能的組合。 執行前我不知道列表的數量和每個列表中指定的值。 此問題在Cartesian_Product中進行了定義和討論。獲取值列表(或陣列數組)列表的所有組合[笛卡爾乘積]

問題輸入可以存儲在數組值列表(或列表列表)中。一個例子可能是兩副牌。有兩個牌組[Red, Blue],每個牌組有4張牌套裝[♠, ♥, ♦, ♣],每套牌有13張牌[Ace, King, Queen, Jack, 10, 9, 8, 7, 6, 5, 4, 3, 2]

這些陣列的笛卡爾乘積返回由2層甲板52張可能撲克牌104元素集合:

[[Red, ♠, Ace], [Red, ♠, King], ..., (Red, ♠, 2), (Red, ♥, Ace), ..., (Red, ♣, 2), 
[Blue, ♠, Ace],[Blue, ♠, King], ..., (Blue, ♠, 2), (Blue, ♥, Ace), ..., (Blue, ♣, 2)] 

那麼如何產生值的列表的列表的所有可能組合?

回答

0

在這裏,用Javascript編寫的解決方案。

問題的一個可能的輸入:

var parameterList = [ [ 'Red', 'Blue' ], 
       [ '\u2660', '\u2665', '\u2666', '\u2663' ], 
       [ 'Ace', 'King', 'Queen', 'Jack', 10, 9, 8, 7, 6, 5, 4, 3, 2 ] ]; 

計算組合的數量

var num_comb = 1; 
for (var i = 0; i < parameterList.length; i++) 
    num_comb *= parameterList[i].length; 

代所有可能的組合的:

// index used to store the positions of the combination just generated 
var index = new Array(parameterList.length); 
for (var i = 0; i < parameterList.length; i++) 
    index[i] = 0; 

//array of arrays that will store the final result (i.e., all possible combinations) 
var combinationsList = []; 

do { 
    var temp = []; 
    for (var i = 0; i < index.length; i++) 
    temp[i] = parameterList[i][index[i]]; 
    combinationsList.push(temp); 
} while (nextIndex()); 


function nextIndex() { 
    var carryover = true; 
    for (var i = parameterList.length - 1; i >= 0 && carryover; i--) { 
    index[i] = (index[i] + 1) % parameterList[i].length; 
    if (index[i] != 0) 
     carryover = false; 
    } 
//if 'carryover' is true and 'i' is equal to zero means that all possible combinations 
//have been generated. In this case 'nextIndex' is equal to the first combination. 
    return !carryover; 
} 

var allCombString = printCombinationsList(); 

用於打印的所有組合:

function printCombinationsList() { 
    var ret = ""; 
    for (var i = 0; i < combinationsList.length; i++) { 
    for (var j = 0; j < combinationsList[i].length; j++) 
     ret += ((j == 0) ? "[" : "") + combinationsList[i][j] + ((j == combinationsList[i].length - 1) ? "]": ", "); 
    ret += "<br/>"; 
    } 
return ret; 
}