DotNet Reference

DotNet Reference

StopAfterNSolutionsSampleSat.cs
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 
15 using System;
16 using Google.OrTools.Sat;
17 
19 {
21  int solution_limit)
22  {
23  variables_ = variables;
24  solution_limit_ = solution_limit;
25  }
26 
27  public override void OnSolutionCallback()
28  {
29  Console.WriteLine(String.Format("Solution #{0}: time = {1:F2} s",
30  solution_count_, WallTime()));
31  foreach (IntVar v in variables_)
32  {
33  Console.WriteLine(
34  String.Format(" {0} = {1}", v.ShortString(), Value(v)));
35  }
36  solution_count_++;
37  if (solution_count_ >= solution_limit_)
38  {
39  Console.WriteLine(
40  String.Format("Stopping search after {0} solutions",
41  solution_limit_));
42  StopSearch();
43  }
44  }
45 
46  public int SolutionCount()
47  {
48  return solution_count_;
49  }
50 
51  private int solution_count_;
52  private IntVar[] variables_;
53  private int solution_limit_;
54 }
55 
57 {
58  static void Main()
59  {
60  // Creates the model.
61  CpModel model = new CpModel();
62  // Creates the variables.
63  int num_vals = 3;
64 
65  IntVar x = model.NewIntVar(0, num_vals - 1, "x");
66  IntVar y = model.NewIntVar(0, num_vals - 1, "y");
67  IntVar z = model.NewIntVar(0, num_vals - 1, "z");
68 
69  // Creates a solver and solves the model.
70  CpSolver solver = new CpSolver();
72  new VarArraySolutionPrinterWithLimit(new IntVar[] { x, y, z }, 5);
73  solver.SearchAllSolutions(model, cb);
74  Console.WriteLine(String.Format("Number of solutions found: {0}",
75  cb.SolutionCount()));
76  }
77 }
Wrapper class around the cp_model proto.
Definition: CpModel.cs:24
override string ShortString()
int SolutionCount()
double WallTime()
void StopSearch()
override void OnSolutionCallback()
IntVar NewIntVar(long lb, long ub, string name)
Definition: CpModel.cs:45
CpSolverStatus SearchAllSolutions(CpModel model, SolutionCallback cb)
Definition: CpSolver.cs:52
long Value(LinearExpr e)
Definition: CpSolver.cs:20
VarArraySolutionPrinterWithLimit(IntVar[] variables, int solution_limit)
Definition: CpModel.pb.cs:12