Bin包装强力方法

时间:2013-04-18 13:13:31

标签: java brute-force bin packing

我需要制作解决bin打包问题的程序,但我已经制作了第一个适合和贪婪的算法,但我的讲师说在某些情况下它找不到问题的最小解决方案。所以我决定尝试使用暴力,但我不知道它应该如何检查所有可能的解决方案。所以是..有人可以向我解释或给出伪代码或其他东西。我会很感激。

3 个答案:

答案 0 :(得分:2)

蛮力只是尝试每一个组合。

enter image description here

要编写暴力破解的代码,请考虑这个技巧:假设我们想要访问8个皇后的所有组合,而不需要硬编码8个嵌套循环。 想想下面八个零的八进制数。

00000000

然后编写一个单循环,在八进制数字系统中增加它:

00000001
00000002
00000003
...
00000007 // 7 + 1 = 10
00000010
00000011
00000012
...
77777776
77777777

尝试所有组合,而不必硬编码8个内部循环。将n替换为n,相同的代码仍然有效。

答案 1 :(得分:2)

请注意bin-packing是一个NP难问题,基本上意味着对它施加蛮力会花费太长时间,即使对于相对较小的输入,所以对于NP难问题的蛮力几乎是永远不是一个好主意。上面的链接显示了一些替代方案(或近似值)。但我会继续......

Recursion使蛮力变得容易。理解a basic recursive algorithm后,继续阅读...

基本思路:(对于3个项目,2个箱子,假设一切都适合,如果它不只是跳过那个分支)

Put the first item in the first bin.
  Put the second item in the first bin.
    Put the third item in the first bin.
      Woo-hoo! We have a solution!
    Remove the third item from the first bin and put it into the second bin.
      Woo-hoo! We have a solution!
    Remove the third item from the second bin.
  Remove the second item from the first bin and put it into the second bin.
    Put the third item in the first bin.
      Woo-hoo! We have a solution!
    Remove the third item from the first bin and put it into the second bin.
      Woo-hoo! We have a solution!
    Remove the third item from the second bin.
  Remove the second item from the second bin.
Remove the first item from the first bin and put it into the second bin.
  Put the second item in the first bin.
    Put the third item in the first bin.
      Woo-hoo! We have a solution!
    Remove the third item from the first bin and put it into the second bin.
      Woo-hoo! We have a solution!
    Remove the third item from the second bin.
  Remove the second item from the first bin and put it into the second bin.
    Put the third item in the first bin.
      Woo-hoo! We have a solution!
    Remove the third item from the first bin and put it into the second bin.
      Woo-hoo! We have a solution!
    Remove the third item from the second bin.
  Remove the second item from the second bin.
Remove the first item from the second bin.

(看看已经有多少步骤了?这只适用于3个项目和2个垃圾箱)

的伪代码:

recurse(int itemID)
  if pastLastItem(itemID)
    if betterThanBestSolution
      bestSolution = currentAssignment
    return
  for each bin i:
    putIntoBin(itemID, i)
    recurse(itemID+1)
    removeFromBin(itemID, i)

答案 2 :(得分:1)

你显然可以做得比蛮力更好。首先,您计算最小的箱数。如果您有100个尺寸的垃圾箱,以及总尺寸为1,234的物品,那么它们将不适合12个垃圾箱,但可能适合13个。

有13个箱子,你将有66个未使用的空间(1,300 - 1,234)。由于5 x 13 = 65,因此必须至少有一个大小为6的箱子未使用。因此,如果您有任何大小为6或更小的物品,您可以将其排除在计算之外,因为您最终可以将其装入(当然您需要检查实际的数字,但无论如何,小物品可以是从搜索中删除)。

如果两个项目完全填满了垃圾箱,那么您不需要考虑任何不适合的解决方案。

从那时起,你使用动态编程,除了你总是使用最大的未使用的项目作为新鲜垃圾箱中的第一项,你总是按降序填充垃圾箱,你总是添加更多的项目,直到什么都不适合,你永远不会考虑所有项目都比其他组合更小或相同的组合。最后,当您发现一个与所需的最小数量的垃圾箱一样好的组合时,您找到了最佳解决方案。

相关问题