Advertisement
lashrone1

0/1 Knapsack Problem

Oct 15th, 2019
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. /*
  2. The 0/1 Knapsack Problem solved with dynamic programming.
  3. */
  4.  
  5.  
  6.  
  7.  
  8. class Knapsack01 {
  9. public static void main(String args[]) {
  10. int[] values = new int[]{ 40,20,60,100 };
  11. int[] weights = new int[]{ 1, 2, 3, 4 };
  12.  
  13. int maxWeight = 5;
  14.  
  15. int[][] dpCache = new int[values.length + 1][maxWeight + 1]; // rows => consider items 0...(total items), cols => weights 0...(max weight)
  16. System.out.println(knapsackBottomUp(values, weights, maxWeight, dpCache)); // 390
  17. printCache(dpCache);
  18. newline();
  19.  
  20. }
  21.  
  22. private static int knapsackBottomUp(int[] values, int[] weights, int maxWeightConstraint, int[][] cache) {
  23.  
  24. for (int totalItems = 0; totalItems <= values.length; totalItems++) {
  25. for (int maxWeight = 0; maxWeight <= maxWeightConstraint; maxWeight++) {
  26. /*
  27. 1.) Without Item -> Going up 1 row
  28. 2.) With Item -> Go up 1 row & left 'weights[currentItem]' columns
  29. */
  30. int currentItem = totalItems - 1;
  31.  
  32. if (totalItems == 0 || maxWeight == 0) {
  33. cache[totalItems][maxWeight] = 0;
  34. } else if (weights[currentItem] > maxWeight) {
  35. cache[totalItems][maxWeight] = cache[totalItems - 1][maxWeight];
  36. } else {
  37. int withItem = values[currentItem] + cache[totalItems - 1][maxWeight - weights[currentItem]];
  38. int withoutItem = cache[totalItems - 1][maxWeight];
  39.  
  40. cache[totalItems][maxWeight] = Math.max(withItem, withoutItem);
  41. }
  42. }
  43. }
  44.  
  45. return cache[values.length][maxWeightConstraint];
  46. }
  47.  
  48.  
  49. private static void printCache(int[][] cache) {
  50. for (int[] row: cache) {
  51. for (int col: row) {
  52. System.out.print(col + " ");
  53. }
  54. System.out.println();
  55. }
  56. }
  57.  
  58. private static void newline() {
  59. System.out.println();
  60. }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement