OR-Tools  7.1
SearchForAllSolutionsSampleSat.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]
18 import com.google.ortools.sat.IntVar;
19 
22  static {
23  System.loadLibrary("jniortools");
24  }
25 
26  // [START print_solution]
27  static class VarArraySolutionPrinter extends CpSolverSolutionCallback {
28  public VarArraySolutionPrinter(IntVar[] variables) {
29  variableArray = variables;
30  }
31 
32  @Override
33  public void onSolutionCallback() {
34  System.out.printf("Solution #%d: time = %.02f s%n", solutionCount, wallTime());
35  for (IntVar v : variableArray) {
36  System.out.printf(" %s = %d%n", v.getName(), value(v));
37  }
38  solutionCount++;
39  }
40 
41  public int getSolutionCount() {
42  return solutionCount;
43  }
44 
45  private int solutionCount;
46  private final IntVar[] variableArray;
47  }
48  // [END print_solution]
49 
50  public static void main(String[] args) throws Exception {
51  // Create the model.
52  // [START model]
53  CpModel model = new CpModel();
54  // [END model]
55 
56  // Create the variables.
57  // [START variables]
58  int numVals = 3;
59 
60  IntVar x = model.newIntVar(0, numVals - 1, "x");
61  IntVar y = model.newIntVar(0, numVals - 1, "y");
62  IntVar z = model.newIntVar(0, numVals - 1, "z");
63  // [END variables]
64 
65  // Create the constraints.
66  // [START constraints]
67  model.addDifferent(x, y);
68  // [END constraints]
69 
70  // Create a solver and solve the model.
71  // [START solve]
72  CpSolver solver = new CpSolver();
73  VarArraySolutionPrinter cb = new VarArraySolutionPrinter(new IntVar[] {x, y, z});
74  solver.searchAllSolutions(model, cb);
75  // [END solve]
76 
77  System.out.println(cb.getSolutionCount() + " solutions found.");
78  }
79 }
80 // [END program]
Wrapper around the SAT solver.
Definition: CpSolver.java:26
IntVar newIntVar(long lb, long ub, String name)
Creates an integer variable with domain [lb, ub].
Definition: CpModel.java:69
Code sample that solves a model and displays all solutions.
Main modeling class.
Definition: CpModel.java:40
CpSolverStatus searchAllSolutions(CpModel model, CpSolverSolutionCallback cb)
Searches for all solutions of a satisfiability problem.
Definition: CpSolver.java:57
Parent class to create a callback called at each solution.
Constraint addDifferent(LinearExpr expr, long value)
Adds.
Definition: CpModel.java:220