OR-Tools  7.1
Knapsack.java
Go to the documentation of this file.
1 // Copyright 2010-2018 Google LLC
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
14 // [START program]
15 // [START import]
17 import java.util.ArrayList;
18 // [END import]
19 
24 public class Knapsack {
25  static {
26  System.loadLibrary("jniortools");
27  }
28 
29  private static void solve() {
30  // [START solver]
31  KnapsackSolver solver = new KnapsackSolver(
33  // [END solver]
34 
35  // [START data]
36  final long[] values = {360, 83, 59, 130, 431, 67, 230, 52, 93, 125, 670, 892, 600, 38, 48, 147,
37  78, 256, 63, 17, 120, 164, 432, 35, 92, 110, 22, 42, 50, 323, 514, 28, 87, 73, 78, 15, 26,
38  78, 210, 36, 85, 189, 274, 43, 33, 10, 19, 389, 276, 312};
39 
40  final long[][] weights = {{7, 0, 30, 22, 80, 94, 11, 81, 70, 64, 59, 18, 0, 36, 3, 8, 15, 42, 9,
41  0, 42, 47, 52, 32, 26, 48, 55, 6, 29, 84, 2, 4, 18, 56, 7, 29, 93, 44, 71, 3, 86, 66, 31,
42  65, 0, 79, 20, 65, 52, 13}};
43 
44  final long[] capacities = {850};
45  // [END data]
46 
47  // [START solve]
48  solver.init(values, weights, capacities);
49  final long computedValue = solver.solve();
50  // [END solve]
51 
52  // [START print_solution]
53  ArrayList<Integer> packedItems = new ArrayList<Integer>();
54  ArrayList<Long> packedWeights = new ArrayList<Long>();
55  int totalWeight = 0;
56  System.out.println("Total value = " + computedValue);
57  for (int i = 0; i < values.length; i++) {
58  if (solver.bestSolutionContains(i)) {
59  packedItems.add(i);
60  packedWeights.add(weights[0][i]);
61  totalWeight = (int) (totalWeight + weights[0][i]);
62  }
63  }
64  System.out.println("Total weight: " + totalWeight);
65  System.out.println("Packed items: " + packedItems);
66  System.out.println("Packed weights: " + packedWeights);
67  // [END print_solution]
68  }
69 
70  public static void main(String[] args) throws Exception {
71  Knapsack.solve();
72  }
73 }
74 // [END program]
static void main(String[] args)
Definition: Knapsack.java:70
void init(long[] profits, long[][] weights, long[] capacities)
Sample showing how to model using the knapsack solver.
Definition: Knapsack.java:24