|
| 1 | +import java.util.Arrays; |
| 2 | + |
| 3 | +/** |
| 4 | + * The knapsack problem or rucksack problem. Given a set of items, each with a weight and a value, |
| 5 | + * determine the number of each item to include in a collection so that the total weight is less than |
| 6 | + * or equal to a given limit and the total value is as large as possible. |
| 7 | + * |
| 8 | + * @author Atom |
| 9 | + * @see <a href="https://en.wikipedia.org/wiki/Knapsack_problem">Knapsack problem</a> |
| 10 | + */ |
| 11 | +public class Knapsack { |
| 12 | + |
| 13 | + public static void maxValue(int maxCapacity, int[] weights, int[] values, int[][] v) { |
| 14 | + for (int i = 1; i < maxCapacity + 1; i++) { |
| 15 | + for (int j = 1; j < weights.length + 1; j++) { |
| 16 | + if (weights[j - 1] > i) { |
| 17 | + v[j][i] = v[j -1][i]; |
| 18 | + } else { |
| 19 | + v[j][i] = Math.max(v[j - 1][i], v[j - 1][i - weights[j - 1]] + values[j - 1]); |
| 20 | + } |
| 21 | + } |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + public static boolean[] includedItems(int[] weights, int[][] v) { |
| 26 | + boolean[] items = new boolean[weights.length]; |
| 27 | + int w = v[0].length - 1; |
| 28 | + for (int i = weights.length; i > 0; i--) { |
| 29 | + if (v[i][w] == v[i - 1][w]) { items[i - 1] = false; } |
| 30 | + else { |
| 31 | + items[i - 1] = true; |
| 32 | + w -= weights[i - 1]; |
| 33 | + } |
| 34 | + } |
| 35 | + return items; |
| 36 | + } |
| 37 | + |
| 38 | + public static void main(String[] args) { |
| 39 | + final int capacity = 8; |
| 40 | + final int[] values = {2, 5, 10, 14, 15}; |
| 41 | + final int[] weights = {1, 3, 4, 5, 7}; |
| 42 | + final int[][] v = new int[weights.length + 1][capacity + 1]; |
| 43 | + System.out.println("Knapsack max weight = " + capacity); |
| 44 | + System.out.println("Number of distinct items = " + values.length); |
| 45 | + System.out.println("Values = " + Arrays.toString(values)); |
| 46 | + System.out.println("Weights = " + Arrays.toString(weights)); |
| 47 | + System.out.println(); |
| 48 | + |
| 49 | + maxValue(capacity, weights, values, v); |
| 50 | + final int b = v[weights.length][capacity]; |
| 51 | + System.out.println("v:"); |
| 52 | + for (int i = 0; i < weights.length + 1; i++) { System.out.println(Arrays.toString(v[i])); } |
| 53 | + System.out.println(); |
| 54 | + System.out.println("Maximum value = " + b); |
| 55 | + System.out.println("Items included: " + Arrays.toString(includedItems(weights, v))); |
| 56 | + } |
| 57 | + |
| 58 | +} |
0 commit comments