Skip to content

Instantly share code, notes, and snippets.

@vaclavcadek
Created July 30, 2018 16:05
Show Gist options
  • Save vaclavcadek/9b5d8ee95281bd0b46e108278841edaa to your computer and use it in GitHub Desktop.
Save vaclavcadek/9b5d8ee95281bd0b46e108278841edaa to your computer and use it in GitHub Desktop.
Simple Ortools solver for CP
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