0

我有一个参数列表列表,我想将它们组合成所有可能的组合。在执行之前我不知道列表的数量和每个列表中指定的值。这个问题在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)]

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

4

1 回答 1

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;
}
于 2013-04-03T08:36:14.230 回答