获取值列表(或数组数组)的所有组合[笛卡尔积]

时间:2013-04-03 08:36:14

标签: list combinations

我有一系列参数列表,我希望将它们组合在一起。 在执行之前我不知道列表的数量和每个列表中指定的值。 此问题已在Cartesian_Product中定义和讨论。

问题输入可以存储在值数组(或列表列表)的数组中。一个例子可能是两副牌。有两个套牌[Red, Blue],每个牌组有4个牌套装[♠, ♥, ♦, ♣],每套牌有13张牌[Ace, King, Queen, Jack, 10, 9, 8, 7, 6, 5, 4, 3, 2]

这些阵列的笛卡尔积产品将返回一个由104个元素组成的组合,包括2副52张可能的扑克牌:

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

那么如何生成值列表列表的所有可能组合?

1 个答案:

答案 0 :(得分: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;
}