Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Solutions · 2. Loop invariants, state machines and conservation laws as code contracts

School of Engineering, Nazarbayev University

Worked solutions to the three exercises of Lecture 2. 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.

Exercise 1

Problem. Implement Boyer–Moore’s O(N)\mathcal{O}(N) time, O(1)\mathcal{O}(1) space majority-vote algorithm with an explicit constructive pair-cancellation witness verifying at every prefix ii that (i−count)(i - \mathrm{count}) elements form disjoint heterogeneous pairs (u≠v)(u \neq v), and test across 40 randomized and adversarial sensor streams.


Exercise 1: Boyer-Moore O(N), O(1)-space majority vote and pair-cancellation proof
==================================================================================
Adversarial late-majority result: {'majority': 7, 'has_majority': True, 'cancelled_pairs_count': 25} | No-majority tie result: {'majority': None, 'has_majority': False, 'cancelled_pairs_count': 2}

Explanation. Every time count decrements, one copy of candidate and one distinct element x != candidate annihilate each other. Since any strict majority element owns >N/2> N/2 total votes, heterogeneous pairs can consume at most N−freq(m)<freq(m)N - \text{freq}(m) < \text{freq}(m) copies of mm, forcing at least one uncancelled copy of mm to survive at the end of Pass 1. Pass 2 confirms actual_freq > N // 2 when no majority exists.


Exercise 2

Problem. Demonstrate and quantify two classic loop-invariant bugs: (a) advancing mid += 1 inside the out[mid] > high_pivot swap of Dutch National Flag on [1.0, 9.0, 3.0, 8.0] ([lo_p, hi_p] = [2.0, 5.0]), and (b) pairing mid = (lo + hi) // 2 with lo = mid in binary search on [10, 20].


Exercise 2: Audit of uninspected-swap DNF corruption and zero-progress binary search infinite loop
==================================================================================================
(a) Input [1.0, 9.0, 3.0, 8.0] with pivots [2.0, 5.0]:
    Buggy DNF output : [1.0, 8.0, 3.0, 9.0]  <-- 8.0 (>5.0) illegally stranded before 3.0
    Clean DNF output : [1.0, 3.0, 8.0, 9.0]

(b) Floor-mid + `lo = mid` binary search: {'stalled': True, 'stall_step': 4, 'stuck_bounds': (6, 7)} (Variant V = hi - lo stops decreasing at hi - lo == 1)

Explanation. In Dutch National Flag, out[lo] is already proved to lie in [lo_p, hi_p] (so swapping lo and mid lets both advance), whereas out[hi] comes from the unclassified zone, so mid must stay put to inspect the newly arrived value. In binary search, lo + (hi - lo) // 2 == lo whenever hi == lo + 1; setting lo = mid gives ΔV=0\Delta V = 0, violating Lyapunov’s strict decrease rule.


Exercise 3

Problem. Implement verify_chemical_valve_fsm(events, omit_low_level_trip=False) controlling batch reactor states (EMPTY, FILLING, FULL_READY, HEATING, DRAINING, LOCKOUT) with actuator tuple (level_low, inlet_open, drain_open, heater_on), plus bfs_find_hazard_trace(omit_low_level_trip) that proves zero reachable hazards for the safe FSM and finds the shortest dry-boil trace when the low-level trip is omitted.


Exercise 3: Implement it yourself — chemical batch-reactor FSM and counterexample model checker
===============================================================================================
Safe Interlocked FSM Audit  : {'safe': True, 'reachable_count': 6, 'counterexample': None, 'hazard_state': None}
Omitted-Trip Buggy FSM Audit: {'safe': False, 'reachable_count': 7, 'counterexample': ['CMD_FILL', 'LVL_HIGH', 'CMD_HEAT', 'FAULT_LEAK'], 'hazard_state': 'UNSAFE_BOIL'}
Replaying shortest counterexample on Safe FSM -> final state: LOCKOUT | violations: 0

Summary. Breadth-First Search over an explicit FSM is a small example of model checking: it proves that no command sequence reaches dry boiling (heater_on and level_low) or pass-through (inlet_open and drain_open), and when an interlock is missing it returns the shortest failing trace, here four events.