需要帮助获得尽可能多的独特啤酒

时间:2017-05-18 20:23:32

标签: javascript recursion language-agnostic combinations permutation

让我们说我有一个酒吧和汽车在前往海滩前停下来捡啤酒。每辆车的行李箱大小(remainingSum),每种啤酒的大小(beer.size

我想为顾客提供他们的汽车后备箱可以容纳的啤酒组合选择(AllCombinations),但是它们是独特的组合。

例如,输入:

let Beers = [ 
    {id: 1, size: 4},
    {id: 5, size: 1},
    {id: 10, size: 0.5},
    {id: 11, size: 1},
    {id: 12, size: 2},
    {id: 13, size: 1},
];

let TrunkSize = 2;

预期产出

AllCombinations = [ // no duplicates
    [{id: 5, size: 1}, {id: 10, size: 0.5}],
    [{id: 5, size: 1}, {id: 11, size: 1}],
    [{id: 5, size: 1}, {id: 13, size: 1}],
    [{id: 10, size: 0.5}, {id: 11, size: 1}],
    [{id: 10, size: 0.5}, {id: 13, size: 1}],
    [{id: 11, size: 1}, {id: 13, size: 1}],
    [{id: 5, size: 1}],
    [{id: 11, size: 1}],
    [{id: 12, size: 2}],
    [{id: 13, size: 1}],
    [{id: 10, size: 0.5}],
] 

当前输出

AllCombinations = [ 
    [{id: 5, size: 1}, {id: 10, size: 0.5}],  // dup a
    [{id: 5, size: 1}, {id: 11, size: 1}],    // dup c
    [{id: 5, size: 1}, {id: 13, size: 1}],    // dup d
    [{id: 10, size: 0.5}, {id: 5, size: 1}],  // dup a
    [{id: 10, size: 0.5}, {id: 11, size: 1}], // dup b
    [{id: 10, size: 0.5}, {id: 13, size: 1}], // dup e
    [{id: 11, size: 1}, {id: 13, size: 1}],   // dup f
    [{id: 11, size: 1}, {id: 10, size: 0.5}], // dup b
    [{id: 11, size: 1}, {id: 5, size: 1}],    // dup c
    [{id: 13, size: 1}, {id: 5, size: 1}],    // dup d
    [{id: 13, size: 1}, {id: 10, size: 0.5}], // dup e
    [{id: 13, size: 1}, {id: 11, size: 1}],   // dup f
    [{id: 5, size: 1}],
    [{id: 11, size: 1}],
    [{id: 12, size: 2}],
    [{id: 13, size: 1}],
    [{id: 10, size: 0.5}]
]

当前功能:

AllCombinations = [];
GetCombinations(currentCombination, beers, remainingSum) 
{ 

    if (remainingSum < 0) 
        return;// Sum is too large; terminate recursion

    else {
        if (currentCombination.length > 0) 
        {
            currentCombination.sort();  
            var uniquePermutation = true;

            for (var i = 0; i < this.AllCombinations.length; i++) 
            {
                if (currentCombination.length == this.AllCombinations[i].length) 
                {
                    for (var j = 0; currentCombination[j] == this.AllCombinations[i][j] && j < this.AllCombinations[i].length; j++);  // Pass

                    if (j == currentCombination.length) {
                        uniquePermutation = false; 
                        break;
                    }
                }
            }

            if (uniquePermutation)
                this.AllCombinations.push(currentCombination);
        }
    }

    for (var i = 0; i < beers.length; i++) {
        var newChoices = beers.slice();       
        var newCombination = currentCombination.concat(newChoices.splice(i, 1)); 
        var newRemainingSum = remainingSum - beers[i].size;
        this.GetCombinations(newCombination, newChoices, newRemainingSum);
    }
}

4 个答案:

答案 0 :(得分:1)

这是另一种方法:

let Beers = [ 
            {id: 1, size: 4},
            {id: 5, size: 1},
            {id: 10, size: 0.5},
            {id: 11, size: 1},
            {id: 12, size: 2},
            {id: 13, size: 1},
];

let TrunkSize = 2;

// get all combinations (stolen from http://stackoverflow.com/questions/5752002/find-all-possible-subset-combos-in-an-array )
function combinations(array) {
    return new Array(1 << array.length).fill().map(
        (e1,i) => array.filter((e2, j) => i & 1 << j));
}

// filter them out if the summed sizes are > trunksize
var valids = combinations(Beers).filter(function(el) {
  return el.reduce(function(a,b){return a+b.size;}, 0) <= TrunkSize;
});

console.log(valids);

答案 1 :(得分:1)

要获得所有可能的组合而不重复,您可以使用一组N位表示组合,其中N =#of。

所以你应该得到一个看起来像这样的表:

000000
000001
000010
000011
000100
000101
000110
000111

...

111111

1告诉您哪些啤酒是可能组合的一部分。然后你只是总结他们的尺寸。如果得到的总和大于trunkCapacity,则中止该循环。

循环后,检查该组合的总大小是否在限制范围内,并将其添加到组合列表中。

&#13;
&#13;
function getCombination(beers, trunkSize) {
  const beersCount = beers.length;
  const combinationsCount = Math.pow(2, beersCount);
  
  const combinations = [];
  
  let i = 0; // Change this to 1 to remove the empty combination that will always be there.
  
  while(i < combinationsCount) {
    const binary = i.toString(2);
    const bits = Array.prototype.concat.apply(Array(beersCount - binary.length).fill(0), binary.split('').map(parseInt));
    
    const combination = [];
    
    let bit = 0;
    let total = 0;
    
    while(bit < beersCount && total <= trunkSize) {
      if (bits[bit]) {
        const beer = beers[bit];

        total += beer.size;
      
        combination.push(beer);
      }
      
      ++bit;
    }
    
    if (total <= trunkSize) {
      combinations.push(combination)
    }
  
    ++i;
  }
  
  return combinations;
}

const combinations = getCombination([ 
  {id: 1, size: 4},
  {id: 5, size: 1},
  {id: 10, size: 0.5},
  {id: 11, size: 1},
  {id: 12, size: 2},
  {id: 13, size: 1},
], 2);

console.log(JSON.stringify(combinations, null, 2));
&#13;
&#13;
&#13;

答案 2 :(得分:1)

我已经编辑了你的代码,修复了sort&amp;检查附加阵列&amp; stringify:

vItem.StylesData['descript'] := 'Description';
vItem.StylesData['details'] := 'Details text';
vItem.ImageIndex := 3;

答案 3 :(得分:1)

您可以获得所有组合并确定哪些组符合条件。

function getCombinations(array, sum, length) {

    function fork(i, t) {
        var s = t.reduce((a, b) => a + b.size, 0);
        if (i === array.length) {
            return s <= sum && t.length <= length && result.push(t);
        }
        fork(i + 1, t.concat([array[i]]));
        fork(i + 1, t);
    }

    var result = [];
    fork(0, []);
    return result;
}

var beers = [{ id: 1, size: 4 }, { id: 5, size: 1 }, { id: 10, size: 0.5 }, { id: 11, size: 1 }, { id: 12, size: 2 }, { id: 13, size: 1 }],
    result = getCombinations(beers, 2, 2);

document.getElementById('out').appendChild(document.createTextNode(JSON.stringify(result, 0, 4)));
<pre id="out"></pre>