Advertisement
Guest User

Untitled

a guest
Apr 20th, 2015
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. class Knapsack {
  2. public static void main(String[] args) throws Exception {
  3. //
  4. // 3 8.00
  5. // 700 7.00 299 3.00 499 5.00
  6. int cal[] = {700, 299, 499 };// val=cal
  7. double price[] = {7.00, 3.00, 5.00 };
  8. int max = 8;
  9. System.out.println(knapsack(cal, price, max));
  10. }
  11.  
  12. public static int knapsack(int cal[], double price[], int maxPrice) {
  13. int N = price.length; // Get the total number of items. Could be price.length
  14. // or cal.length. Doesn't matter
  15. int[][] V = new int[N + 1][maxPrice + 1]; // Create a matrix. Items are in rows
  16. // and price at in columns +1 on
  17. // each side
  18. // What if the knapsack's capacity is 0 - Set all columns at row 0 to be
  19. // 0
  20. for (int col = 0; col <= maxPrice; col++) {
  21. V[0][col] = 0;
  22. }
  23. // What if there are no items at home. Fill the first row with 0
  24. for (int row = 0; row <= N; row++) {
  25. V[row][0] = 0;
  26. }
  27. for (int item = 1; item <= N; item++) {
  28. // Let's fill the values row by row
  29. for (int calories = 1; calories <= maxPrice; calories++) {
  30. // Is the current items cal less than or equal to running
  31. // cal
  32. if (price[item - 1] <= calories) {
  33. // Given a cal, check if the value of the current item +
  34. // value of the item that we could afford with the remaining
  35. // weight
  36. // is greater than the value without the current item itself
  37. V[item][calories] = Math.max(cal[item - 1]
  38. + V[item - 1][(int) (calories - price[item - 1])],
  39. V[item - 1][calories]);
  40. } else {
  41. // If the current item's cal is more than the running
  42. //cal, just carry forward the value without the current
  43. // item
  44. V[item][calories] = V[item - 1][calories];
  45. }
  46. }
  47. }
  48. // Printing the matrix
  49. for (int[] rows : V) {
  50. for (int col : rows) {
  51. System.out.format("%5d", col);
  52. }
  53. System.out.println();
  54. }
  55. return V[N][maxPrice];
  56. }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement