Advertisement
Guest User

Untitled

a guest
May 20th, 2019
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. package ads.set1.knapsack;
  2.  
  3. public class MaxItemsKnapsackSolver {
  4.  
  5. /**
  6. * Solves the limited-items knapsack problem using a dynamic programming
  7. * algorithm based on the one introduced in the lecture.
  8. *
  9. * @param items
  10. * (possibly empty) list of items. All items have a profit
  11. * {@code > 0.}
  12. * @param capacity
  13. * the maximum weight allowed for the knapsack ({@code >= 0}).
  14. * @param maxItems
  15. * the maximum number of items that may be packed ({@code >= 0}).
  16. * @return the maximum profit achievable by packing at most {@code maxItems}
  17. * with at most {@code capacity} weight.
  18. */
  19. public static int pack(Item[] items, int capacity, int maxItems) {
  20.  
  21. int n = items.length;
  22. int maxprofit = 0;
  23. for (int i = 0; i < items.length; i++) {
  24. maxprofit += items[i].getProfit();
  25. }
  26.  
  27. int a[][][] = new int[n][maxprofit + 1][maxItems + 1];
  28.  
  29. // ganzes Array mit unendlich füllen bzw. capacity + 1
  30. for (int i = 0; i < n; i++) {
  31.  
  32. for (int t = 0; t <= maxprofit; t++) {
  33.  
  34. for (int c = 0; c <= maxItems; c++) {
  35. a[i][t][c] = capacity + 1;
  36. }
  37.  
  38. }
  39.  
  40. }
  41.  
  42. for (int t = 1; t <= maxprofit; t++) {
  43.  
  44. for (int i = 0; i < n; i++) {
  45.  
  46. if (items[i].getProfit() == t) {
  47. a[i][t][1] = items[i].getWeight();
  48. }else if(i > 0){
  49. a[i][t][1] = a[i-1][t][1];
  50. }
  51.  
  52. }
  53.  
  54. }
  55.  
  56. for(int i = 0; i < n; i++) {
  57. for(int t = 0; t <= maxprofit; t++) {
  58. a[i][t][0] = 0;
  59. }
  60. }
  61.  
  62. for (int i = 1; i < n; i++) {
  63.  
  64. for (int t = 0; t <= maxprofit; t++) {
  65.  
  66. for (int c = 2; c <= maxItems; c++) {
  67.  
  68. if (t < items[i].getProfit()) {
  69. a[i][t][c] = a[i - 1][t][c];
  70. } else {
  71. a[i][t][c] = Math.min(a[i - 1][t][c], a[i - 1][t - items[i].getProfit()][c - 1] + items[i].getWeight());
  72. }
  73.  
  74. }
  75.  
  76. }
  77.  
  78. }
  79.  
  80. int j = 0;
  81.  
  82. for (int t = 1; t <= maxprofit; t++) {
  83. for (int c = 1; c <= maxItems; c++) {
  84. if (a[n-1][t][c] <= capacity ) {
  85. j = t;
  86. }
  87. }
  88. }
  89.  
  90. return j;
  91. }
  92.  
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement