Created
October 4, 2023 19:37
-
-
Save codecontemplator/570b4d9dff3c6fb1e5e72fe05c2fd06d to your computer and use it in GitHub Desktop.
This file contains 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 | |
from typing import NamedTuple | |
class Box(NamedTuple): | |
weight: int | |
class Truck(NamedTuple): | |
capacity: int | |
trucks = [Truck(3000), Truck(5000), Truck(8000)] | |
boxes = [Box(3000), Box(3000), Box(4000), Box(2000)] | |
#trucks = [Truck(5), Truck(5), Truck(5)] | |
#boxes = [Box(2), Box(2), Box(3), Box(1), Box(1)] | |
model = cp_model.CpModel() | |
truckInUse = [ model.NewBoolVar(f"truck {ti} in use?") for ti in range(len(trucks)) ] | |
vars = {} | |
for ti in range(len(trucks)): | |
for bi in range(len(boxes)): | |
vars[(bi,ti)] = model.NewBoolVar(f"box {bi} in truck {ti}?") | |
for bi in range(len(boxes)): | |
model.AddExactlyOne([vars[(bi,ti)] for ti in range(len(trucks))]) | |
for ti in range(len(trucks)): | |
model.Add( | |
sum( | |
[vars[(bi,ti)] * boxes[bi].weight for bi in range(len(boxes))] | |
) <= trucks[ti].capacity * truckInUse[ti] | |
) | |
model.Minimize(sum(truckInUse)) | |
solver = cp_model.CpSolver() | |
solver.Solve(model) | |
for ti in range(len(trucks)): | |
print(f"boxes in truck {ti} ({trucks[ti].capacity}):") | |
for bi in range(len(boxes)): | |
v = solver.Value(vars[(bi,ti)]) | |
if v: | |
print(f" {bi} ({boxes[bi].weight})") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment