Skip to content

Instantly share code, notes, and snippets.

@dboyliao
Last active March 12, 2020 14:48
Show Gist options
  • Save dboyliao/3ccf4a52a89279aa75262743f350e3e5 to your computer and use it in GitHub Desktop.
Save dboyliao/3ccf4a52a89279aa75262743f350e3e5 to your computer and use it in GitHub Desktop.
Simple ortools example for solving constraint optimization with CP solver
from ortools.sat.python import cp_model
# setup a model which represents the constraint optimization problem
model = cp_model.CpModel()
# declare variables
# x and y are two integer with range of 0 to 2
x = model.NewIntVar(0, 2, 'x')
y = model.NewIntVar(0, 2, 'y')
# add constraint: x+y <= 1
model.Add(x + y <= 1)
# setup the objective function
obj = 2*x + y
model.Maximize(obj)
# solve the optimization problem
solver = cp_model.CpSolver()
status = solver.Solve(model)
if solver.StatusName(status) == 'OPTIMAL':
print('x:', solver.Value(x))
print('y:', solver.Value(y))
else:
print('no optimal solution')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment