【问题标题】:Getting all the combinations of a list of lists of values (or array of arrays) [Cartesian Product]获取值列表(或数组数组)列表的所有组合 [笛卡尔积]
【发布时间】:2013-04-03 08:36:14
【问题描述】:

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

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

【问题讨论】:

    标签: list combinations


    【解决方案1】:

    这里是用 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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-22
      • 2011-05-18
      • 2017-06-13
      • 2019-02-07
      • 2017-04-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-24
      相关资源
      最近更新 更多