寻找数字选择的可能性

时间:2010-07-29 08:25:31

标签: javascript algorithm

我在javascript中有以下示例数据:

var variations = [
  {group: 1, id: 1},
  {group: 1, id: 2},
  {group: 1, id: 3},
  {group: 1, id: 4},
  {group: 2, id: 5},
  {group: 2, id: 6},
  {group: 2, id: 7},
  {group: 3, id: 8},
  {group: 3, id: 9}
];

让我们说我已经使用以下变量定义了选择:

var selected_variation_groups = [1,2,3];
var selected_variation_group_ids = [1,2,3,4,5,6,7,8,9];

当我尝试从上面的数据中找到选择号码的可能性时,我会有24个可能性:

=> 1, 5, 8
=> 1, 5, 9
=> 1, 6, 8
=> 1, 6, 9
=> 1, 7, 8
=> 1, 7, 9

=> 2, 5, 8
=> 2, 5, 9
=> 2, 6, 8
=> 2, 6, 9
=> 2, 7, 8
=> 2, 7, 9

=> 3, 5, 8
=> 3, 5, 9
=> 3, 6, 8
=> 3, 6, 9
=> 3, 7, 8
=> 3, 7, 9

=> 4, 5, 8
=> 4, 5, 9
=> 4, 6, 8
=> 4, 6, 9
=> 4, 7, 8
=> 4, 7, 9

是否有人可以帮助我为此提供算法,或者是否有人可以帮助我提供javascript代码来创建这些可能性?

groupid可以无限制。

3 个答案:

答案 0 :(得分:1)

您正在计算从每个组中选择一个项目的所有排列。

如果将所有组排列为数组,则更容易编码,因此所有组1的数据都在一个数组中,组2在另一个数组中,依此类推。

此函数会将组的所有排列添加到数组中,其值以逗号分隔。

var groups = [
      [1,2,3,4], [5,6,7], [8,9]
];

var result = new Array();
appendPermutation(groups, 0, groups.length, "", result);

alert(result.length);
alert(result);


function appendPermutation(groups, start, end, currentResult, result)
{
   if (start==end)
   {

       result.push(currentResult);
        return;
   }

   var group = groups[start];
   for (var i=0; i<group.length; i++) {
      var value = group[i].toString();
      var nextResult;
      if (currentResult.length==0)
          nextResult = currentResult + value;
      else
          nextResult = currentResult + "," + value;      
      appendPermutation(groups, start+1, end, nextResult, result);
   }
}

答案 1 :(得分:0)

mdma已经展示了如何获得排列。此代码将按照建议将数据分组到哈希集合中:

var groups = {};
for(var i = 0; i < variations.length; i++){
    var key = variations[i].group;
    var value = variations[i].id;

    if(!groups[key])
        groups[key] = [];
     groups[key].push(value);
}

如果您需要将数组更改groups = {};更改为groups = [];,但确保密钥是小数字,或者它可能生成大数组(对于大数字),或添加属性(对于其他字符串) )。

答案 2 :(得分:0)

除了@ mdma的解决方案,您可能会发现这也很有用:

function permutation(options) {
    if(options.length == 1) {
        var permutations = [];
        for(var i = 0; i < options[0].length; i++) {
            permutations.push([options[0][i]]);
        }
        return permutations;
    }
    return addOptionWithPermutation(options[0], permutation(options.slice(1)));
}

function addOptionWithPermutation(option, permutations) {
    var newPermutations = [];
    for(var i = 0; i < option.length; i++) {
        for(var j = 0; j < permutations.length; j++) {
            var newPerm = permutations[j].slice(0); //just to take copy
            newPerm.splice(0, 0, option[i]); //insert in the beginning
            newPermutations.push(newPerm);
        }
    }
    return newPermutations;
}

var permutations = permutation([[1,2,3,4], [5,6,7], [8,9]]);

for(var i = 0; i < permutations.length; i++) {
  alert(permutations[i]);
}