Skip to content

Instantly share code, notes, and snippets.

View mlabonne's full-sized avatar

Maxime Labonne mlabonne

View GitHub Profile
from ortools.sat.python import cp_model
# Instantiate model and solver
model = cp_model.CpModel()
solver = cp_model.CpSolver()
# 1. Variable
army = model.NewIntVar(1, 10000, 'army')
# 2. Constraints
# variable % mod = target → (target, variable, mod)
model.AddModuloEquality(0, army, 13)
model.AddModuloEquality(0, army, 19)
model.AddModuloEquality(0, army, 37)
# Find the variable that satisfies these constraints
status = solver.Solve(model)
# If a solution has been found, print results
if status == cp_model.OPTIMAL or status == cp_model.FEASIBLE:
print('================= Solution =================')
print(f'Solved in {solver.WallTime():.2f} milliseconds')
print()
print(f'🪖 Army = {solver.Value(army)}')
print()
model = cp_model.CpModel()
solver = cp_model.CpSolver()
# 1. Variable
army = model.NewIntVar(1, 100000, 'army')
# 2. Constraints
model.AddModuloEquality(0, army, 13)
model.AddModuloEquality(0, army, 19)
model.AddModuloEquality(0, army, 37)
# Instantiate model and solver
model = cp_model.CpModel()
solver = cp_model.CpSolver()
# 1. Variables
capacity = 19
bread = model.NewIntVar(0, capacity, 'bread')
meat = model.NewIntVar(0, capacity, 'meat')
beer = model.NewIntVar(0, capacity, 'beer')
# 2. Constraints
model.Add(1 * bread
+ 3 * meat
+ 7 * beer <= capacity)
# 3. Objective
model.Maximize(3 * bread
+ 10 * meat
+ 26 * beer)
# Solve problem
status = solver.Solve(model)
# If an optimal solution has been found, print results
if status == cp_model.OPTIMAL:
print('================= Solution =================')
print(f'Solved in {solver.WallTime():.2f} milliseconds')
print()
print(f'Optimal value = {3*solver.Value(bread)+10*solver.Value(meat)+26*solver.Value(beer)} popularity')
print('Food:')
class CountSolutions(cp_model.CpSolverSolutionCallback):
"""Count the number of solutions."""
def __init__(self):
cp_model.CpSolverSolutionCallback.__init__(self)
self.__solution_count = 0
def on_solution_callback(self):
self.__solution_count += 1