StopAfterNSolutionsSampleSat.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 
17 import com.google.ortools.sat.IntVar;
18 
21  static {
22  System.loadLibrary("jniortools");
23  }
24 
25  static class VarArraySolutionPrinterWithLimit extends CpSolverSolutionCallback {
26  public VarArraySolutionPrinterWithLimit(IntVar[] variables, int limit) {
27  variableArray = variables;
28  solutionLimit = limit;
29  }
30 
31  @Override
32  public void onSolutionCallback() {
33  System.out.printf("Solution #%d: time = %.02f s%n", solutionCount, wallTime());
34  for (IntVar v : variableArray) {
35  System.out.printf(" %s = %d%n", v.getName(), value(v));
36  }
37  solutionCount++;
38  if (solutionCount >= solutionLimit) {
39  System.out.printf("Stop search after %d solutions%n", solutionLimit);
40  stopSearch();
41  }
42  }
43 
44  public int getSolutionCount() {
45  return solutionCount;
46  }
47 
48  private int solutionCount;
49  private final IntVar[] variableArray;
50  private final int solutionLimit;
51  }
52 
53  public static void main(String[] args) throws Exception {
54  // Create the model.
55  CpModel model = new CpModel();
56  // Create the variables.
57  int numVals = 3;
58 
59  IntVar x = model.newIntVar(0, numVals - 1, "x");
60  IntVar y = model.newIntVar(0, numVals - 1, "y");
61  IntVar z = model.newIntVar(0, numVals - 1, "z");
62 
63  // Create a solver and solve the model.
64  CpSolver solver = new CpSolver();
65  VarArraySolutionPrinterWithLimit cb =
66  new VarArraySolutionPrinterWithLimit(new IntVar[] {x, y, z}, 5);
67  solver.searchAllSolutions(model, cb);
68 
69  System.out.println(cb.getSolutionCount() + " solutions found.");
70  if (cb.getSolutionCount() != 5) {
71  throw new RuntimeException("Did not stop the search correctly.");
72  }
73  }
74 }
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 a small number of 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.