DotNet Reference

DotNet Reference

SearchForAllSolutionsSampleSat.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 // [START program]
15 using System;
16 using Google.OrTools.Sat;
17 
18 // [START print_solution]
20 {
21  public VarArraySolutionPrinter(IntVar[] variables)
22  {
23  variables_ = variables;
24  }
25 
26  public override void OnSolutionCallback()
27  {
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  }
38  }
39 
40  public int SolutionCount()
41  {
42  return solution_count_;
43  }
44 
45  private int solution_count_;
46  private IntVar[] variables_;
47 }
48 // [END print_solution]
49 
51 {
52  static void Main()
53  {
54  // Creates the model.
55  // [START model]
56  CpModel model = new CpModel();
57  // [END model]
58 
59  // Creates the variables.
60  // [START variables]
61  int num_vals = 3;
62 
63  IntVar x = model.NewIntVar(0, num_vals - 1, "x");
64  IntVar y = model.NewIntVar(0, num_vals - 1, "y");
65  IntVar z = model.NewIntVar(0, num_vals - 1, "z");
66  // [END variables]
67 
68  // Adds a different constraint.
69  // [START constraints]
70  model.Add(x != y);
71  // [END constraints]
72 
73  // Creates a solver and solves the model.
74  // [START solve]
75  CpSolver solver = new CpSolver();
77  new VarArraySolutionPrinter(new IntVar[] { x, y, z });
78  solver.SearchAllSolutions(model, cb);
79  // [END solve]
80 
81  Console.WriteLine(String.Format("Number of solutions found: {0}",
82  cb.SolutionCount()));
83  }
84 }
85 // [END program]
Wrapper class around the cp_model proto.
Definition: CpModel.cs:24
override string ShortString()
override void OnSolutionCallback()
double WallTime()
IntVar NewIntVar(long lb, long ub, string name)
Definition: CpModel.cs:45
Constraint Add(BoundedLinearExpression lin)
Definition: CpModel.cs:104
CpSolverStatus SearchAllSolutions(CpModel model, SolutionCallback cb)
Definition: CpSolver.cs:52
long Value(LinearExpr e)
int SolutionCount()
Definition: CpSolver.cs:20
VarArraySolutionPrinter(IntVar[] variables)
Definition: CpModel.pb.cs:12