Below is a compact “cook-book” of how people in practice model and solve exactly the kind of “grid construction” (aka student–course timetabling) problem you describe.
- Data you usually start with
• S = set of students (|S| = n)
• P = set of subjects a school offers (|P| = m)
• L = {1, …, k } fixed number of “lines” (= future periods in the day)
• Cₚ = parallel classes in each subject p ∈ P (can be 1, 2, 3 …)
• cap(c) = desk capacity of class c (upper bound)
Students tell you a subset take(s) ⊆ P of subjects they want.
- The natural decision variables
(1) line[c] ∈ L … which line each class runs on
(2) assign[s,p] ∈ Cₚ … which concrete class a student attends
(undefined if student s does not take subject p)
- Hard constraints to post
A. Capacity
∑_{s : assign[s,p] = c} 1 ≤ cap(c) ∀ c
B. One class per subject
assign[s,p] is defined exactly once for every (s,p) with p ∈ take(s)
C. Clash-free lines for every student
allDifferent( line[ assign[s,p] ] : p ∈ take(s) ) ∀ s
Constraint C is the key: the set of lines chosen by one student must be pairwise
different, so a single allDifferent() (or “pairwise-inequality”) does the job.
- Two standard optimisation goals (optional)
• Minimise the number of students left un-scheduled.
• Balance class sizes (e.g. minimise ∑ |size(c) – target|² ).
Feel free to add whatever objective your school cares about; the model above
already guarantees feasibility.
- Two mainstream ways to solve it
A. Constraint Programming (CP) / CP-SAT
– Each line[c] is a small-domain integer (1..k).
– each allDifferent() is natively supported and prunes heavily.
– Google OR-Tools, Choco, OptaPlanner, MiniZinc + OR-Tools back-end, …
– Typical instance (1000 students, k=6–8 lines, capacities 20–30) solves
in seconds to minutes.
B. Mixed-Integer Linear Programming (MILP)
Choose binary variables:
y_{c,l} = 1 if class c is on line l
x_{s,c} = 1 if student s sits in class c
Linking constraint:
∑l y{c,l} = 1 (each class on 1 line)
∑{c∈Cₚ} x{s,c} = 1 ∀(s,p) (one class per subject)
∑{c} x{s,c}·y_{c,l} ≤ 1 ∀(s,l) (no clash)
Linearise the product with standard “big-M” or helper variables z_{s,c,l}.
Feed to Gurobi/CP-SAT/CBC. Works, but the CP model is shorter and easier.
- A graph-theoretic view (why k lines are enough)
Build a bipartite graph G = (S ∪ P, E) with an edge (s,p) iff student s
takes subject p.
By König’s theorem, a bipartite graph of maximum degree Δ (here Δ = max
subjects per student) has an edge-colouring with Δ colours.
Each colour ⇔ one “line”, each coloured edge ⇔ (student,subject) pair.
Hence: if every student takes ≤ k subjects, k lines are provably enough.
To construct it you can repeatedly extract Δ disjoint matchings; this runs in
O(Δ·|E|·√|V|) time. The extra capacity constraints are what turn the problem
from “easy” to NP-hard and make the CP/MILP approach above more attractive.
- Heuristics that work well if instances get big
• Greedy sequential assignment + conflict repair
• Iterated Local Search / Tabu on the line[c] variables
• Very Large Neighbourhood Search (Google’s CP-SAT provides this for free)
• Decomposition: first line-colour subjects ignoring capacity, then
balance capacities by swapping students between parallel classes.
- Tiny OR-Tools CP-SAT sketch (Python)
from ortools.sat.python import cp_model
model = cp_model.CpModel()
# ---- 1. Vars ---------------------------------------------------------
line = {}
for c in classes:
line[c] = model.NewIntVar(1, k, f'line_{c}')
assign = {}
for s in students:
for p in take[s]:
for c in classes_of[p]:
assign[s,p,c] = model.NewBoolVar(f'x_{s}_{p}_{c}')
# ---- 2. Constraints --------------------------------------------------
# One class per (s,p)
for s in students:
for p in take[s]:
model.AddExactlyOne(assign[s,p,c] for c in classes_of[p])
# Capacity
for c in classes:
model.Add(sum(assign[s,p,c]
for s in students
for p in take[s] if c in classes_of[p]) <= capacity[c])
# Link chosen class to its line
for s in students:
used_lines = []
for p in take[s]:
tmp = model.NewIntVar(1, k, f'line_of_{s}_{p}')
# tmp = Σ line[c]*assign[s,p,c] (only one will be 1)
model.Add(sum( line[c] * assign[s,p,c] for c in classes_of[p]) == tmp)
used_lines.append(tmp)
model.AddAllDifferent(used_lines) # <-- clash-free magic
# ---- 3. (Optional) Objective ----------------------------------------
# minimise the largest class size
max_size = model.NewIntVar(0, max_cap, 'max_size')
for c in classes:
model.Add(sum(assign[s,p,c] for s in students for p in take[s]
if c in classes_of[p]) <= max_size)
model.Minimize(max_size)
solver = cp_model.CpSolver()
solver.parameters.max_time_in_seconds = 60
solver.Solve(model)
Ten-dozen lines and you’re done.
Take-away
• Model each class’ line as an integer and use an allDifferent per student.
• Solve with a CP/CP-SAT engine for convenience and speed.
• Theoretical underpinning: bipartite edge-colouring shows k lines always
suffice if every student has ≤ k subjects; the extra capacity constraints
are what need optimisation.
That is the standard, scalable way schools, universities, and commercial
timetabling systems tackle your exact “grid construction” task. Good luck!