Optimisation and games

Integer programs

When the answer must be whole numbers (items packed, machines bought, people assigned), rounding the linear optimum is not enough. Branch and bound splits the problem until every piece is either whole, impossible, or provably no better than what has been found.

A knapsack

import { integerProgram } from "@ratmath/discrete";

const pack = integerProgram({
  maximize: { a: 8, b: 11, c: 6, d: 4 },                    // values
  constraints: [
    [{ a: 5, b: 7, c: 4, d: 3 }, "<=", 14],                   // weights, capacity 14
    [{ a: 1 }, "<=", 1], [{ b: 1 }, "<=", 1], [{ c: 1 }, "<=", 1], [{ d: 1 }, "<=", 1],
  ],
});
String(pack);   // "optimal: 21 at a = 0, b = 1, c = 1, d = 1 (13 subproblems; relaxation 22)"

// the same 0–1 knapsack in one call: binary adds x ≤ 1 and wholeness for each variable
integerProgram({ maximize: { a: 8, b: 11, c: 6, d: 4 }, constraints: [[{ a: 5, b: 7, c: 4, d: 3 }, "<=", 14]] }, { binary: true });

The linear relaxation drops the requirement that the variables be whole and is solved exactly. Its optimum bounds the integer optimum: here no packing is worth more than 22. If its solution is already whole, it is the answer. Otherwise some variable has a fractional value vv, and every integer solution has either x≤⌊v⌋x \le \lfloor v\rfloor or x≥⌊v⌋+1x \ge \lfloor v\rfloor + 1. Each case is a new linear program. A branch is closed when its relaxation is infeasible, whole, or no better than the best whole solution found so far.

Rounding is not enough

const r = integerProgram({ maximize: [5, 4], constraints: [[[6, 4], "<=", 24], [[1, 2], "<=", 6]] });
r.relaxation.solution;   // { x1: 3, x2: 3/2 }: the linear optimum, worth 21
String(r);               // "optimal: 20 at x1 = 4, x2 = 0 (5 subproblems; relaxation 21)"

Rounding the relaxation's (3,3/2)(3, 3/2) gives (3,1)(3, 1), worth 19, or the infeasible (3,2)(3, 2). The best integer point, (4,0)(4, 0), is not near it. Integer programming is NP-hard in general, so the search can grow exponentially. This solver is for small problems and for teaching; it refuses with "too-hard" beyond maxNodes subproblems (20,000 by default). Pass integer: ["x"] to require only some variables to be whole, and binary: true (or a list of names) to make variables 0 or 1.

The check() of an integer result confirms feasibility and wholeness. Unlike a linear optimum it carries no short proof of optimality: that rests on the search, and the test suite compares the search with every integer point of hundreds of small random problems.

Try itEdit the code and run it with @ratmath/discrete and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.
Ctrl/⌘ + Enter runs