Reputation: 2766
In a scheduling problem. I want to assign vacations proportionally to the days worked. Right now I have a working solution using multiple boolean flags but it doesn't scale very well.
from ortools.sat.python import cp_model
from math import ceil
model = cp_model.CpModel()
solver = cp_model.CpSolver()
days = model.NewIntVar(0, 365, 'days')
vacations = model.NewIntVar(0, 30, 'vacations')
for i in range(365 + 1):
flag_bool = model.NewBoolVar(f'days == {i}')
model.Add(days == i).OnlyEnforceIf(flag_bool)
model.Add(days != i).OnlyEnforceIf(flag_bool.Not())
model.Add(vacations == ceil(i * 30 / 365)).OnlyEnforceIf(flag_bool)
# test
model.Add(days == 300)
status = solver.Solve(model)
print(solver.Value(days), solver.Value(vacations))
Any suggestions?
Edit: A more general question would be if there is a better way to implement a precalculated arbitrary mapping of one variable to another.
Upvotes: 3
Views: 568
Reputation: 2766
Solution following Laurent's suggestion:
ceil(days * 30 / 365) == (days * 30 + 364) // 365
Therefore
from ortools.sat.python import cp_model
model = cp_model.CpModel()
solver = cp_model.CpSolver()
days = model.NewIntVar(0, 365, 'days')
vacations = model.NewIntVar(0, 30, 'vacations')
tmp = model.NewIntVar(364, 365 * 30 + 364, 'days*30+364')
model.Add(tmp == days * 30 + 364)
model.AddDivisionEquality(vacations, tmp, 365)
# test
model.Add(days == 300)
status = solver.Solve(model)
print(solver.Value(days), solver.Value(vacations))
Upvotes: 3