/** * Implements the all interval problem. See http://www.hakank.org/google_or_tools/all_interval.py */ private static void solve(int n) { Solver solver = new Solver("AllInterval"); // // variables // IntVar[] x = solver.makeIntVarArray(n, 0, n - 1, "x"); IntVar[] diffs = solver.makeIntVarArray(n - 1, 1, n - 1, "diffs"); // // constraints // solver.addConstraint(solver.makeAllDifferent(x, true)); solver.addConstraint(solver.makeAllDifferent(diffs, true)); for (int k = 0; k < n - 1; k++) { solver.addConstraint( solver.makeEquality( diffs[k], solver.makeAbs(solver.makeDifference(x[k + 1], x[k])).Var())); } // symmetry breaking solver.addConstraint(solver.makeLess(x[0], x[n - 1])); solver.addConstraint(solver.makeLess(diffs[0], diffs[1])); // // search // DecisionBuilder db = solver.makePhase(x, solver.CHOOSE_FIRST_UNBOUND, solver.ASSIGN_MIN_VALUE); solver.newSearch(db); // // output // while (solver.nextSolution()) { System.out.print("x : "); for (int i = 0; i < n; i++) { System.out.print(x[i].value() + " "); } System.out.print("\ndiffs: "); for (int i = 0; i < n - 1; i++) { System.out.print(diffs[i].value() + " "); } System.out.println("\n"); } solver.endSearch(); // Statistics System.out.println(); System.out.println("Solutions: " + solver.solutions()); System.out.println("Failures: " + solver.failures()); System.out.println("Branches: " + solver.branches()); System.out.println("Wall time: " + solver.wall_time() + "ms"); }
/** Solves the N Queens problem. See http://www.hakank.org/google_or_tools/nqueens2.py */ private static void solve(int n, int num, int print) { Solver solver = new Solver("NQueens"); System.out.println("n: " + n); // // variables // IntVar[] q = solver.makeIntVarArray(n, 0, n - 1, "q"); // // constraints // solver.addConstraint(solver.makeAllDifferent(q, true)); IntVar b = solver.makeIntVar(1, 1, "b"); IntVar[] q1 = new IntVar[n]; IntVar[] q2 = new IntVar[n]; for (int i = 0; i < n; i++) { for (int j = 0; j < i; j++) { // // q[i]+i != q[j]+j solver.addConstraint( solver.makeNonEquality(solver.makeSum(q[i], i).Var(), solver.makeSum(q[j], j).Var())); // q[i]-i != q[j]-j solver.addConstraint( solver.makeNonEquality(solver.makeSum(q[i], -i).Var(), solver.makeSum(q[j], -j).Var())); } } // // Solve // DecisionBuilder db = solver.makePhase(q, solver.CHOOSE_MIN_SIZE_LOWEST_MAX, solver.ASSIGN_CENTER_VALUE); solver.newSearch(db); int c = 0; while (solver.nextSolution()) { if (print != 0) { for (int i = 0; i < n; i++) { System.out.print(q[i].value() + " "); } System.out.println(); } c++; if (num > 0 && c >= num) { break; } } solver.endSearch(); // Statistics System.out.println(); System.out.println("Solutions: " + solver.solutions()); System.out.println("Failures: " + solver.failures()); System.out.println("Branches: " + solver.branches()); System.out.println("Wall time: " + solver.wall_time() + "ms"); }