Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Open up KnapsackSolver and replace the text of the file with the following:

Code Block
collapsiblecollapsible
import java.util.Arrays;
import ilog.concert.IloException;
import ilog.concert.IloIntVar;
import ilog.cplex.IloCplex;

public class KnapsackSolver {
	
	public static double[] solveKnapsack(double[] values, double[] weights, double capacity){		
		if(weights.length != values.length){
			throw new RuntimeException("values.length was " + values.length 
					+ " and weights.length was" +  weights.length 
					+ " but they must be the same");
		}
		try {
			IloCplex cplex = new IloCplex();
			IloIntVar[] x = cplex.boolVarArray(values.length);
			cplex.addLe(cplex.scalProd(x, weights), capacity);
			cplex.addMaximize(cplex.scalProd(x, values));
			cplex.solve();
			return cplex.getValues(x);			
		} catch (IloException e) {
			throw new RuntimeException();
		}
	}
		
	public static void main(String[] args){
		double[] values = new double[]{2,4,5,6};
		double[] weights= new double[]{2,3,4,7};
		double capacity = 8;
		double[] solution = solveKnapsack(values,weights,capacity);
		System.out.println(Arrays.toString(solution));
	}
}

Wiki Markup
Run the code.  The final line of output should of course be {{\[0.0, 1.0, 1.0, 0.0\]}}, up to some precision.  If you get the error

Cannot find cplex...

then your PATH was not set properly. The easiest way to deal with this is to add a virtual machine argument to the Run Configuration. Starting from the menu bar at the top, select Run → Run Configurations... and then on the left, make sure Java Application → KnapsackSolver is selected. In the center panel, pick the (error)=Arguments tab. In the second box, titled VM Arguments, add the line:

this is a VM argument

Finally, hit Run on the bottom.