Created
July 30, 2018 16:05
-
-
Save vaclavcadek/9b5d8ee95281bd0b46e108278841edaa to your computer and use it in GitHub Desktop.
Simple Ortools solver for CP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from ortools.sat.python import cp_model | |
class SolutionPrinter(cp_model.CpSolverSolutionCallback): | |
def __init__(self, variables): | |
super().__init__() | |
self.variables = variables | |
self.solutions = [] | |
def NewSolution(self): | |
super().NewSolution() | |
solution = {v: self.Value(v) for v in self.variables} | |
self.solutions.append(solution) | |
print(solution) | |
@property | |
def solution_count(self): | |
return len(self.solutions) | |
if __name__ == '__main__': | |
model = cp_model.CpModel() | |
solver = cp_model.CpSolver() | |
x = model.NewIntVar(0, 2, 'x') | |
y = model.NewIntVar(0, 2, 'y') | |
z = model.NewIntVar(0, 2, 'z') | |
model.Add(x != y) | |
printer = SolutionPrinter([x, y, z]) | |
status = solver.SearchForAllSolutions(model, printer) | |
print(status) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment