Versions Compared

Key

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

...

Open Eclipse and expand the sandbox project we created previously. Create a new class called KnapsackSolver. Next we are going to connect to Cplex. Right click on sandbox in the package explorer and select new->folder. Give it the name lib and click "Finish." Find the file cplex.jar in your Cplex installation. On my Windows installation, it was located at

  • Windows: C:\Program Files\IBM\ILOG\CPLEX_Studio125\cplex\lib\cplex.jar
  • Linux: /opt/IBM/ILOG/CPLEX_Studio125/cplex/lib/cplex.jar TODO check
  • Mac: Unknown.
    Copy the file cplex.jar and paste it in the newly created lib folder in our project. Right click on sandbox in the package explorer, then select Build Path → Configure Build Path... Select the Libraries tab, then hit the Add JARs button (see here for an explanation of what all these buttons do). Select the file sandbox/lib/cplex.jar, then hit OK until we have exited all the menus.

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

Code Block
collapsibleCollapsibletrue
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));
	}
}

...