安装

jar包
ortools-7.4-SNAPSHOT.jar
测试

  1. import com.google.ortools.linearsolver.MPConstraint;
  2. import com.google.ortools.linearsolver.MPObjective;
  3. import com.google.ortools.linearsolver.MPSolver;
  4. import com.google.ortools.linearsolver.MPVariable;
  5. import com.google.ortools.util.OrToolsHelper;
  6. public class LinearProgrammingExample {
  7. //注意这个地方,一定要加这一句
  8. static {
  9. OrToolsHelper.loadLibrary();
  10. }
  11. public static void main(String[] args) throws Exception {
  12. MPSolver solver = new MPSolver("LinearProgrammingExample", MPSolver.OptimizationProblemType.GLOP_LINEAR_PROGRAMMING);
  13. double infinity = java.lang.Double.POSITIVE_INFINITY;
  14. // x and y are continuous non-negative variables.
  15. MPVariable x = solver.makeNumVar(0.0, infinity, "x");
  16. MPVariable y = solver.makeNumVar(0.0, infinity, "y");
  17. System.out.println("Number of variables = " + solver.numVariables());
  18. // x + 2*y <= 14.
  19. MPConstraint c0 = solver.makeConstraint(-infinity, 14.0, "c0");
  20. c0.setCoefficient(x, 1);
  21. c0.setCoefficient(y, 2);
  22. // 3*x - y >= 0.
  23. MPConstraint c1 = solver.makeConstraint(0.0, infinity, "c1");
  24. c1.setCoefficient(x, 3);
  25. c1.setCoefficient(y, -1);
  26. // x - y <= 2.
  27. MPConstraint c2 = solver.makeConstraint(-infinity, 2.0, "c2");
  28. c2.setCoefficient(x, 1);
  29. c2.setCoefficient(y, -1);
  30. System.out.println("Number of constraints = " + solver.numConstraints());
  31. // Maximize 3 * x + 4 * y.
  32. MPObjective objective = solver.objective();
  33. objective.setCoefficient(x, 3);
  34. objective.setCoefficient(y, 4);
  35. objective.setMaximization();
  36. final MPSolver.ResultStatus resultStatus = solver.solve();
  37. // Check that the problem has an optimal solution.
  38. if (resultStatus != MPSolver.ResultStatus.OPTIMAL) {
  39. System.err.println("The problem does not have an optimal solution!");
  40. return;
  41. }
  42. // The value of each variable in the solution.
  43. System.out.println("Solution");
  44. System.out.println("x = " + x.solutionValue());
  45. System.out.println("y = " + y.solutionValue());
  46. // The objective value of the solution.
  47. System.out.println("Optimal objective value = " + solver.objective().value());
  48. }
  49. }