Five items in five lines.
Chapter: VI — Knapsack · lesson id knapsack-indexed · practice lesson
The scalar form doesn't scale past a handful of items. Real models declare a set I, parameters v_i and w_i, and a single sum constraint. Same problem, same optimum — far less typing.
Notice how the entire model fits in five lines.
model knap
set I = {1, 2, 3, 4, 5}
const v = {6, 4, 5, 3, 2}, forall i in I
const w = {2, 3, 4, 2, 1}, forall i in I
const W = 6
bin x, forall i in I
constr sum_{i in I}{w_{i} * x_{i}} <= W
max sum_{i in I}{v_{i} * x_{i}}
end
import elytica
def main():
elytica.init_model("knap")
elytica.run_model("knap")
for i in [1,2,3,4,5]:
print("x"+str(i), "=", elytica.get_variable_value("knap", "x"+str(i)))
print("obj =", elytica.get_best_primal_bound("knap"))
return 0
Compare to the previous lesson. Same problem, same answer.
no-error — Model solvesnumeric-match — Same optimum as the scalar version (12)code-contains — Reads the objective from the solver (no hardcoding)Five items, fresh numbers. Indexed form, same five-line template.
model knap_v
set I = {1, 2, 3, 4, 5}
const v = {5, 7, 3, 4, 2}, forall i in I
const w = {2, 3, 4, 1, 1}, forall i in I
const W = 5
bin x, forall i in I
constr sum_{i in I}{w_{i} * x_{i}} <= W
max sum_{i in I}{v_{i} * x_{i}}
end
import elytica
def main():
elytica.init_model("knap_v")
elytica.run_model("knap_v")
for i in [1,2,3,4,5]:
print("x"+str(i), "=", elytica.get_variable_value("knap_v", "x"+str(i)))
print("obj =", elytica.get_best_primal_bound("knap_v"))
return 0
Read this through MCP: read with path: "lessons/knapsack-indexed", or resource hlpl://lessons/knapsack-indexed.