Worked solutions to the three exercises of Lecture 8. Each solution is computed here and checked with assert statements against an exact identity or an independent calculation. The first code cell sets up the notebook and runs Demonstration 1 of the lecture without showing its output, because some of the solutions use its variables.
try: # use the installed package, or the copy in this repository
import engthink
except ImportError:
import pathlib, subprocess, sys
for _root in [pathlib.Path.cwd(), *pathlib.Path.cwd().parents]:
if (_root / "engthink" / "__init__.py").exists():
sys.path.insert(0, str(_root))
break
else: # on Google Colab: install from GitHub
subprocess.run([sys.executable, "-m", "pip", "install", "-q",
"git+https://github.com/ktwyw/engthink.git"], check=True)
import engthink
import inspect
import math
import numpy as np
import matplotlib.pyplot as plt
from engthink import (constants_benchmarks, divide_spatial, dynamic_optimality, emergence_verification,
greedy_heuristic_search, information_streams, invariants_complexity, reductions_constraints,
representation_scaling)
from engthink.plotting import label_panels, log_ticks, panel_label, use_style
use_style()
def show_source(obj):
"""Return the source code of a library function or class."""
return inspect.getsource(obj)
def heading(text):
print(f"\n{text}\n" + "=" * len(text))
# Demonstration 1 of the lecture, run without output: the solutions use its variables.
import contextlib, io
_show, plt.show = plt.show, lambda *args, **kwargs: None
_stdout = contextlib.redirect_stdout(io.StringIO()); _stdout.__enter__()
heading("Demonstration 1: Earliest finish time against three other greedy rules")
mm17 = [m for m in constants_benchmarks.MENTAL_MOVES_DB if m["id"] == 17][0]
print(f"Mental Move #{mm17['id']} ({mm17['name']}): {mm17['invariant']}")
def greedy_by_key(intervals: list[tuple[float, float]], mode: str) -> list[tuple[float, float]]:
rem = list(intervals)
chosen = []
while rem:
if mode == "earliest_start":
best = min(rem, key=lambda iv: (iv[0], iv[1]))
elif mode == "shortest_duration":
best = min(rem, key=lambda iv: (iv[1] - iv[0], iv[0]))
elif mode == "fewest_conflicts":
def deg(cand):
return sum(1 for other in rem if not (other[1] <= cand[0] + 1e-12 or other[0] >= cand[1] - 1e-12))
best = min(rem, key=lambda iv: (deg(iv), iv[0]))
else:
raise ValueError(mode)
chosen.append(best)
rem = [iv for iv in rem if iv[1] <= best[0] + 1e-12 or iv[0] >= best[1] - 1e-12]
return sorted(chosen)
# Counterexample 1 (Earliest Start): [0, 10] blocks [1, 3], [3, 5], [5, 7], [7, 9]
ivs_est = [(0.0, 10.0), (1.0, 3.0), (3.0, 5.0), (5.0, 7.0), (7.0, 9.0)]
# Counterexample 2 (Shortest Duration): [4, 6] blocks [0, 5] and [5, 10]
ivs_short = [(0.0, 5.0), (4.0, 6.0), (5.0, 10.0)]
# Counterexample 3 (Fewest Conflicts — Classic 11-interval graph):
# Top optimal row of 4 disjoint jobs: (0,2), (3,5), (6,8), (9,11)
# Middle trap (4.5, 6.5) has unique minimum conflict degree = 2, whereas 3 left & 3 right blockers give all others degree >= 3
ivs_fc11 = [
(0.0, 2.0), (3.0, 5.0), (6.0, 8.0), (9.0, 11.0),
(4.5, 6.5),
(1.5, 3.5), (1.6, 3.6), (1.7, 3.7),
(7.5, 9.5), (7.6, 9.6), (7.7, 9.7),
]
for label, ivs, bad_mode, expected_opt, expected_bad in [
("Earliest start (5 jobs)", ivs_est, "earliest_start", 4, 1),
("Shortest duration (3 jobs)", ivs_short, "shortest_duration", 2, 1),
("Fewest conflicts (11 jobs)", ivs_fc11, "fewest_conflicts", 4, 3),
]:
opt_eft = greedy_heuristic_search.interval_scheduling_greedy(ivs)
bad_sel = greedy_by_key(ivs, bad_mode)
assert opt_eft["count"] == expected_opt
assert len(bad_sel) == expected_bad
print(f"{label:33s}: EFT Optimal = {opt_eft['count']} jobs vs. {bad_mode:18s} = {len(bad_sel)} jobs")
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9.4, 3.8), sharex=True)
eft_11 = set(greedy_heuristic_search.interval_scheduling_greedy(ivs_fc11)["selected_intervals"])
fc_11 = set(greedy_by_key(ivs_fc11, "fewest_conflicts"))
for y_i, (s, f) in enumerate(ivs_fc11):
c1 = "#2E8B57" if (s, f) in eft_11 else "#C5CCD3"
c2 = "#C0392B" if (s, f) in fc_11 else "#C5CCD3"
ax1.plot([s, f], [y_i, y_i], lw=5.0, solid_capstyle="butt", color=c1)
ax2.plot([s, f], [y_i, y_i], lw=5.0, solid_capstyle="butt", color=c2)
ax1.set_title("Earliest finish time: 4 disjoint jobs (optimal)")
ax1.set_xlabel("Time $t$")
ax1.set_ylabel("Request index")
ax2.set_title("Fewest conflicts: takes (4.5, 6.5), 3 jobs")
ax2.set_xlabel("Time $t$")
label_panels(fig)
plt.show()
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Across 200 random 14-interval schedules, verify that (a) interval_scheduling_greedy matches an exact DP oracle on 100% of trials, and (b) against every compatible schedule sorted by finish time, greedy’s sorted selections obey for all .
heading("Exercise 1: 200-trial greedy stay-ahead invariant and exact DP verification")
def exact_unweighted_interval_dp(intervals: list[tuple[float, float]]) -> int:
s_ivs = sorted(intervals, key=lambda x: (x[1], x[0]))
n = len(s_ivs)
dp = [0] * (n + 1)
for j in range(1, n + 1):
sj, _ = s_ivs[j - 1]
pred = 0
for i in range(j - 1, 0, -1):
if s_ivs[i - 1][1] <= sj + 1e-12:
pred = i
break
dp[j] = max(dp[j - 1], 1 + dp[pred])
return dp[n]
rng_ex1 = np.random.default_rng(108)
n_trials = 200
stay_ahead_checks = 0
for _ in range(n_trials):
starts = rng_ex1.uniform(0.0, 20.0, size=14)
durs = rng_ex1.uniform(0.5, 6.0, size=14)
ivs = [(float(s), float(s + d)) for s, d in zip(starts, durs)]
grd_res = greedy_heuristic_search.interval_scheduling_greedy(ivs)
dp_cnt = exact_unweighted_interval_dp(ivs)
assert grd_res["count"] == dp_cnt
g_finishes = [f for _, f in sorted(grd_res["selected_intervals"], key=lambda x: x[1])]
# Sample 10 random compatible competitor schedules and check f(g_r) <= f(o_r) for every rank r:
for _ in range(10):
perm = rng_ex1.permutation(len(ivs))
comp: list[tuple[float, float]] = []
for idx in perm:
cand = ivs[int(idx)]
if all(cand[1] <= o[0] + 1e-12 or cand[0] >= o[1] - 1e-12 for o in comp):
comp.append(cand)
comp.sort(key=lambda x: x[1])
assert len(comp) <= len(g_finishes)
for r, (_, fo) in enumerate(comp):
assert g_finishes[r] <= fo + 1e-12
stay_ahead_checks += 1
print(f"Exact EFT == DP cardinality verified on {n_trials}/{n_trials} random 14-interval instances")
print(f"Stay-Ahead inequality f(g_r) <= f(o_r) verified across {stay_ahead_checks:,d} individual rank comparisons")
Exercise 1: 200-trial greedy stay-ahead invariant and exact DP verification
===========================================================================
Exact EFT == DP cardinality verified on 200/200 random 14-interval instances
Stay-Ahead inequality f(g_r) <= f(o_r) verified across 9,032 individual rank comparisons
Explanation. Because holds inductively at every rank , greedy always frees up the shared resource at least as early as any competing valid schedule—leaving a superset of remaining future intervals available after step .
Exercise 2¶
Problem. Verify ValueError guards on interval_scheduling_greedy and belady_optimal_cache, audit greedy coin-change suboptimality on [1, 3, 4] () and [1, 7, 10] (), and prove numerically why cyclic scan [0, 1, 2, 3] * 15 in a cache_size = 3 buffer causes 100% misses (60/60) under LRU/FIFO vs. 22 misses under Bélády.
heading("Exercise 2: Failure-mode audit — guards, coin-change traps and cyclic scan thrashing")
# 0. Input guard checks:
caught = 0
try:
greedy_heuristic_search.interval_scheduling_greedy([(5.0, 2.0)])
except ValueError:
caught += 1
try:
greedy_heuristic_search.belady_optimal_cache([1, 2, 3], cache_size=0)
except ValueError:
caught += 1
assert caught == 2
assert greedy_heuristic_search.belady_optimal_cache([], cache_size=3)["belady_hit_rate"] == 1.0
# 1. Non-canonical coin traps:
def greedy_vs_dp_single(coins: list[int], target: int) -> tuple[int, int]:
dp = [10**9] * (target + 1)
dp[0] = 0
for a in range(1, target + 1):
dp[a] = min(dp[a - c] + 1 for c in coins if c <= a)
rem = target
g_cnt = 0
for c in sorted(coins, reverse=True):
q, rem = divmod(rem, c)
g_cnt += q
return g_cnt, dp[target]
g_6, opt_6 = greedy_vs_dp_single([1, 3, 4], 6)
g_14, opt_14 = greedy_vs_dp_single([1, 7, 10], 14)
assert g_6 == 3 and opt_6 == 2 # 4+1+1 vs. 3+3
assert g_14 == 5 and opt_14 == 2 # 10+1+1+1+1 vs. 7+7
# 2. Cyclic scan thrashing: working set size M = 4 looping inside cache size k = 3
cyclic_trace = [0, 1, 2, 3] * 15 # 60 total accesses
cyc_k3 = greedy_heuristic_search.belady_optimal_cache(cyclic_trace, cache_size=3)
cyc_k4 = greedy_heuristic_search.belady_optimal_cache(cyclic_trace, cache_size=4)
assert cyc_k3["lru_misses"] == 60 and cyc_k3["fifo_misses"] == 60 # 100% miss rate (0 hits)
assert cyc_k3["belady_misses"] == 22 # 3 warmup + 19*(1 miss per 3 steps) = 22
assert np.isclose(cyc_k3["belady_hit_rate"], 38.0 / 60.0, atol=1e-12)
assert cyc_k4["lru_misses"] == 4 and cyc_k4["belady_misses"] == 4 # Once k >= M=4, only 4 cold-start misses
print(f"Coin trap [1, 3, 4] at A=6 : Greedy = {g_6} coins vs. Optimal DP = {opt_6} coins")
print(f"Coin trap [1, 7, 10] at A=14 : Greedy = {g_14} coins vs. Optimal DP = {opt_14} coins")
print(f"Cyclic scan (M=4 in k=3) : LRU = {cyc_k3['lru_misses']}/60 misses (100% thrashing) vs. Belady = {cyc_k3['belady_misses']}/60 misses ({100.0 * cyc_k3['belady_hit_rate']:.1f}% hits)")
Exercise 2: Failure-mode audit — guards, coin-change traps and cyclic scan thrashing
====================================================================================
Coin trap [1, 3, 4] at A=6 : Greedy = 3 coins vs. Optimal DP = 2 coins
Coin trap [1, 7, 10] at A=14 : Greedy = 5 coins vs. Optimal DP = 2 coins
Cyclic scan (M=4 in k=3) : LRU = 60/60 misses (100% thrashing) vs. Belady = 22/60 misses (63.3% hits)
Explanation. On a cyclic table scan 0, 1, 2, 3, 0, 1, 2, 3, ... with cache size , when 3 arrives at {0, 1, 2}, the least recently used item is 0—which is the exact item needed on the very next step. Thus LRU evicts the worst possible page on 100% of accesses (k-competitive worst case), whereas Bélády evicts 2 (needed 3 steps away), keeping two slots pinned and hitting of steady-state requests.
Exercise 3¶
Problem. Implement weighted_interval_scheduling_dp(intervals_with_weights) in time using finish-time sorting, binary search (bisect_right) for predecessor , and Bellman DP with backpointer subset reconstruction. Verify exact optimality against brute-force enumeration across 40 random weighted instances (N = 12) and verify that greedy EFT fails when weights vary.
heading("Exercise 3: Implement it yourself — O(N log N) weighted interval scheduling DP")
import bisect
def weighted_interval_scheduling_dp(intervals_with_weights: list[tuple[float, float, float]]) -> dict:
"""Solve exact maximum-weight compatible interval subset in O(N log N) via binary search + Bellman DP."""
indexed = []
for orig_i, (s, f, w) in enumerate(intervals_with_weights):
if f < s or w < 0.0:
raise ValueError("Require finish >= start and non-negative weight.")
indexed.append((float(f), float(s), float(w), orig_i))
indexed.sort(key=lambda t: (t[0], t[1]))
n = len(indexed)
finishes = [t[0] for t in indexed]
# p[j] in 0..j-1 (1-based count of compatible prefix items with finish <= start_j):
p = np.zeros(n + 1, dtype=int)
for j in range(1, n + 1):
sj = indexed[j - 1][1]
p[j] = bisect.bisect_right(finishes, sj + 1e-12, 0, j - 1)
dp = np.zeros(n + 1, dtype=float)
take = np.zeros(n + 1, dtype=bool)
for j in range(1, n + 1):
cand_take = indexed[j - 1][2] + dp[p[j]]
if cand_take >= dp[j - 1]:
dp[j] = cand_take
take[j] = True
else:
dp[j] = dp[j - 1]
chosen_orig: list[int] = []
j_cur = n
while j_cur > 0:
if take[j_cur]:
chosen_orig.append(indexed[j_cur - 1][3])
j_cur = int(p[j_cur])
else:
j_cur -= 1
chosen_orig.reverse()
return {"max_weight": float(dp[n]), "selected_indices": chosen_orig}
def bruteforce_weighted_intervals(ivw: list[tuple[float, float, float]]) -> float:
n = len(ivw)
best = 0.0
for mask in range(1 << n):
sub = [ivw[k] for k in range(n) if (mask >> k) & 1]
sub.sort(key=lambda t: t[0])
if all(sub[i][1] <= sub[i + 1][0] + 1e-12 for i in range(len(sub) - 1)):
best = max(best, sum(t[2] for t in sub))
return best
# 1. Explicit example where EFT greedy picks 2 low-value jobs (weight 10+10=20) blocking 1 high-value job (weight 95):
demo_w = [(0.0, 4.0, 10.0), (2.0, 8.0, 95.0), (5.0, 9.0, 10.0)]
eft_idx = greedy_heuristic_search.interval_scheduling_greedy([(s, f) for s, f, _ in demo_w])["selected_indices"]
eft_val = sum(demo_w[i][2] for i in eft_idx)
dp_demo = weighted_interval_scheduling_dp(demo_w)
assert np.isclose(eft_val, 20.0) and np.isclose(dp_demo["max_weight"], 95.0)
# 2. 40 random 12-interval tests against 2^12 = 4,096 brute-force subset oracle + unit-weight EFT parity:
rng_w = np.random.default_rng(808)
for _ in range(40):
st = rng_w.uniform(0.0, 15.0, size=12)
du = rng_w.uniform(0.5, 5.0, size=12)
wt = rng_w.uniform(1.0, 50.0, size=12)
inst = [(float(s), float(s + d), float(w)) for s, d, w in zip(st, du, wt)]
res_dp = weighted_interval_scheduling_dp(inst)
res_bf = bruteforce_weighted_intervals(inst)
assert np.isclose(res_dp["max_weight"], res_bf, atol=1e-11)
unit_inst = [(float(s), float(s + d), 1.0) for s, d in zip(st, du)]
assert int(round(weighted_interval_scheduling_dp(unit_inst)["max_weight"])) == greedy_heuristic_search.interval_scheduling_greedy([(s, f) for s, f, _ in unit_inst])["count"]
print(f"Weighted trap : EFT Greedy = {eft_val:.1f} vs. Weighted Bellman DP = {dp_demo['max_weight']:.1f} (selected {dp_demo['selected_indices']})")
print("Verified O(N log N) Weighted Interval DP against 2^N brute-force oracle across 40/40 random instances")
Exercise 3: Implement it yourself — O(N log N) weighted interval scheduling DP
==============================================================================
Weighted trap : EFT Greedy = 20.0 vs. Weighted Bellman DP = 95.0 (selected [1])
Verified O(N log N) Weighted Interval DP against 2^N brute-force oracle across 40/40 random instances
Summary. Adding arbitrary weights breaks the greedy Stay-Ahead exchange argument (here the greedy choice of two jobs of weight 10 blocks one job of weight 95), yet sorting by finish time still provides the topological DAG order needed for binary-search Bellman DP to solve the weighted problem exactly in time.