我试图写一个算法,将'填补'车辆的能力,它的基础上不同的输入组合。这个问题已经解决了,但是它太慢了,不能用于更多的组合。
例如:
我有一辆容量为10的车辆,我有不同的座椅类型(属性)组合,可以不同地填充车辆(可移动,或正常的座椅容量为1是默认值)。此外,不等于10的每个组合(大于10的被移除)将被填充为可移动的容量,或只是一个正常的座位。就像这样:

const a = [ {
 name: 'wheelchair',
 capacity: 0,
 total: 3
}, {
  name: 'walker',
  capacity: 2,
  total: 5
  }, {
  name: 'service animal',
  capacity: 2,
  total: 5
}];

在上面的例子中还值得注意的是,轮椅每次组合只能添加3次,因为它总共有3次(最大值)。轮椅的0容量是此特定属性的指定位置的一个示例,该属性不占用任何其他活动座椅。
为此,我尝试了几种不同的方法,我的算法对于这种特定的组合很好,甚至可以再添加一些。但是,如果我添加一个总共10个、容量为1的属性,这将使总的可能性增加一个数量级,并大大降低算法的速度。在我的方法中,我找到了不同的排列,然后过滤掉重复项来找到组合,如果有一种方法只找到组合,也许会减少计算负载,但我想不出一种方法。我有一个输出需要查看的特定方式,这是底部的输出,但是,我可以控制输入,并且可以在必要时进行更改。任何想法或帮助都是非常感谢的。
此代码是根据此答案修改的https://stackoverflow.com/a/21640840/6025994

  // the power set of [] is [[]]
  if(arr.length === 0) {
      return [[]];
  }

  // remove and remember the last element of the array
  var lastElement = arr.pop();

  // take the powerset of the rest of the array
  var restPowerset = powerSet(arr);


  // for each set in the power set of arr minus its last element,
  // include that set in the powerset of arr both with and without
  // the last element of arr
  var powerset = [];
  for(var i = 0, len = restPowerset.length; i < len; i++) {

      var set = restPowerset[i];

      // without last element
      powerset.push(set);

      // with last element
      set = set.slice(); // create a new array that's a copy of set
      set.push(lastElement);
      powerset.push(set);
  }

  return powerset;
};

var subsetsLessThan = function (arr, number) {
  // all subsets of arr
  var powerset = powerSet(arr);

  // subsets summing less than or equal to number
  var subsets = new Set();
  for(var i = 0, len = powerset.length; i < len; i++) {

      var subset = powerset[i];

      var sum = 0;
      const newObject = {};
      for(var j = 0, len2 = subset.length; j < len2; j++) {
          if (newObject[subset[j].name]) {
            newObject[subset[j].name]++;
          } else {
            newObject[subset[j].name] = 1;
          }
          sum += subset[j].seat;
      }
      const difference = number - sum;

      newObject.ambulatory = difference;

      if(sum <= number) {
          subsets.add(JSON.stringify(newObject));
      }
  }

  return [...subsets].map(subset => JSON.parse(subset));
};

const a = [{
  name: 'grocery',
  capacity: 2,
  total: 5
}, {
  name: 'wheelchair',
  capacity: 0,
  total: 3
}];
const hrStart = process.hrtime();
const array = [];

for (let i = 0, len = a.length; i < len; i++) {
  for (let tot = 0, len2 = a[i].total; tot < len2; tot++) {
    array.push({
      name: a[i].name,
      seat: a[i].capacity
    });
  }
}
const combinations = subsetsLessThan(array, 10);
const hrEnd = process.hrtime(hrStart);
// for (const combination of combinations) {
//   console.log(combination);
// }

console.info('Execution time (hr): %ds %dms', hrEnd[0], hrEnd[1] / 1000000)

期望结果是所有传递结果的组合小于车辆通行能力,因此本质上是一个小于和的组合算法。例如,我发布的代码的预期结果将是-->
[{"ambulatory":10},{"wheelchair":1,"ambulatory":10},{"wheelchair":2,"ambulatory":10},{"wheelchair":3,"ambulatory":10},{"grocery":1,"ambulatory":8},{"grocery":1,"wheelchair":1,"ambulatory":8},{"grocery":1,"wheelchair":2,"ambulatory":8},{"grocery":1,"wheelchair":3,"ambulatory":8},{"grocery":2,"ambulatory":6},{"grocery":2,"wheelchair":1,"ambulatory":6},{"grocery":2,"wheelchair":2,"ambulatory":6},{"grocery":2,"wheelchair":3,"ambulatory":6},{"grocery":3,"ambulatory":4},{"grocery":3,"wheelchair":1,"ambulatory":4},{"grocery":3,"wheelchair":2,"ambulatory":4},{"grocery":3,"wheelchair":3,"ambulatory":4},{"grocery":4,"ambulatory":2},{"grocery":4,"wheelchair":1,"ambulatory":2},{"grocery":4,"wheelchair":2,"ambulatory":2},{"grocery":4,"wheelchair":3,"ambulatory":2},{"grocery":5,"ambulatory":0},{"grocery":5,"wheelchair":1,"ambulatory":0},{"grocery":5,"wheelchair":2,"ambulatory":0},{"grocery":5,"wheelchair":3,"ambulatory":0}]

最佳答案

有一个技巧可以用来改进你的算法,叫做backtracking:如果你到达一个不可能的路径,例如5->6,那么你不必继续在那里搜索,因为5+6已经大于10。通过它你可以消除很多组合。

   function* combineMax([current, ...rest], max, previous = {}) {
     // Base Case:  if there are no items left to place, end the recursion here
     if(!current) {
       // If the maximum is reached exactly, then this a valid solution, yield it up
       if(!max) yield previous;
       return;
     }

     // if the "max" left is e.g. 8, then the grocery with "seat" being 2 can only fit in 4 times at max, therefore loop from 0 to 4
     for(let amount = 0; (!current.seat || amount <= max / current.seat) && amount <= current.total; amount++) {
       // The recursive call
       yield* combineMax(
        rest, // exclude the current item as that was  used already
        max - amount * current.seat, // e.g. max was 10, we take "seat: 2" 3 times, then the max left is "10 - 2 * 3"
        { ...previous, [current.name]: amount } // add the current amount
       );
     }
   }

   const result = [...combineMax([
    { name: 'grocery', seat: 2, total: Infinity },
    { name: 'wheelchair', seat: 0, total: 3 },
    { name: 'ambulatory equipment', seat: 1, total: Infinity },
     //...
   ], 10)];

09-11 13:45