Algorithmadvanced
Stromquist moving knife
Also called Stromquist procedure.
An envy-free division among three agents into connected pieces with four moving knives, one held by a referee.
- Solves
- Cake cutting problem
- Time
- O(k log k) worst
- Space
- O(k) extra
- Where
- k = the number of segments of a piecewise-constant valuation
- Model
- Real RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
The Stromquist moving knife is a procedure that divides a cake among three agents into three intervals so that no agent envies another. A referee moves a sword over the cake, each agent moves a knife that halves the rest of the cake in its own eyes, and the cake is cut at the sword and at the middle knife when an agent shouts. It differs from the other envy-free protocols for three or more agents: the Selfridge-Conway procedure is finite but can give two intervals to an agent, while this procedure gives connected pieces but needs four knives that move continuously. By Stromquist's impossibility theorem, no finite protocol in the Robertson-Webb query model can do what this procedure does. The Brams-Taylor procedure and the Aziz-Mackenzie protocol handle any number of agents, with pieces that are not connected.
In plain words
A referee slowly moves a sword from the left end of a long cake to the right, splitting off a left part. Each of three friends holds a knife over the rest of the cake, at the place where the two sides of the knife look equal to that friend. The middle knife marks a second cut.
So there are always three pieces: left, middle and right. As soon as some friend thinks the left part is at least as good as each other part, that friend shouts "cut". The cake is cut at the sword and at the middle knife. The friend who shouted takes the left part. Each other friend takes the part that holds its own knife. To that friend, this part is the better of the two right parts and is at least as good as the left part, or it would have shouted first.
The problem
The cake is . Agents 1, 2 and 3 have nonnegative, additive and nonatomic valuations with . The procedure must output three intervals that cover the cake and meet only at end points, one for each agent, with for all and . Here we also assume that every interval of positive length has positive value to every agent, so that each knife position is unique and moves continuously. Without this assumption the halving point can jump, and the argument below fails.
The algorithm
For a sword position , agent holds its knife at , the point of with . The median knife is .
STROMQUIST-KNIFE(agents 1, 2, 3)- 1
the referee puts the sword at x = 0 - 2
move x continuously to the right, and at each moment: - 3
each agent i holds its knife at k_i(x) ▷ halves [x, 1] in its eyes - 4
y ← the median of k_1(x), k_2(x), k_3(x) - 5
agent i shouts if V_i([0, x]) ≥ V_i([x, y]) and V_i([0, x]) ≥ V_i([y, 1]) - 6
stop at the first shout; s ← the agent that shouts ▷ ties go to the smallest index - 7
cut at x and at y; give [0, x] to s - 8
of the two other agents, the one whose knife is further left gets [x, y] - 9
the other one gets [y, 1]
The procedure is a thought experiment with continuous motion. For valuations with positive piecewise-constant densities on equal segments, the implementation simulates it exactly: every knife position and the median are piecewise affine in , with break points, so the first shout is found by solving linear equations between break points.
Example
Take four equal segments. Agent 1 is uniform, agent 2 has densities proportional to , and agent 3 to . The first shout comes at . There the knives are at , and , so the median is , the knife of agent 1.
Agent 2 values at , at and at . So agent 2 shouts at the moment its left part ties with its best right part, and it gets . Agent 1's knife () is left of agent 3's knife (), so agent 1 gets and agent 3 gets . Row gives of each agent's piece:
| 5/14 | 2/7 | 5/14 | |
| 8/21 | 8/21 | 5/21 | |
| 5/21 | 4/21 | 4/7 |
Each row has its largest entry on the diagonal, so the division is envy-free. Agent 1 holds the median knife, so it values the two right parts equally at .
Correctness
The knife positions and the median knife move continuously, because each is continuous and strictly increasing on . Let be the value of the left part to agent minus the larger of the values of the two right parts. At , is at most ; at , it is . So there is a first moment when some reaches 0, and at that moment no is positive, because each was negative just before.
The shouter has , so it values the left part at least as much as each right part. The two other agents have , so each values its better right part at least as much as the left part. The agent whose knife is left of or at the median values at least half of , so is its better right part; the other agent is the mirror case. So every agent gets a piece it values most. The full proof, and the proof that the simulation is exact, are in proofs/correctness.md.
Proof: The Stromquist moving knife gives an envy-free division into three intervalsfull
Setting. The cake is . Agents 1, 2 and 3 have nonnegative, additive and nonatomic valuations with . We also assume that every interval of positive length has positive value to every agent; this is the assumption under which we prove the result, and the implementation meets it by positive densities. Let . Then is continuous, strictly increasing, and , so it has a continuous inverse on . We refer to the lines L1 to L9 of the page.
Lemma 1 (the knives move continuously). For , agent has exactly one knife position with , namely
The maps and the median knife are continuous, and .
Proof. The condition says , that is . Since is a strictly increasing bijection of , there is exactly one such , and gives . The formula is a composition of continuous maps. The median of three numbers is , which is continuous in . Each lies in , so the median does too.
Lemma 2 (the first shout). Let . Line L5 stops at . This minimum exists, , for the shouter , and for every agent .
Proof. Each is continuous by Lemma 1. At , and the two right pieces have total value 1, so the larger is at least and . At , and . So the set is nonempty, and it is closed because is continuous. Its least element exists, and . The knife stops at the first where some agent's condition holds, which is ; line L6 picks one such agent , so . For every and every , , so .
So : the shouter shouts at the moment of equality.
Lemma 3 (the knives of the others). Let and be the two agents other than , with as in line L8. Then , where .
Proof. The median is one of the three knives, and at most one knife is below it and at most one above it in the sorted order. If , then and are the other two, one on each side. If (as a value), then , and . If , then , and .
Lemma 4 (each other agent gets its better right piece). Agent values at least as much as , and agent values at least as much as .
Proof. Write . Since , monotonicity gives , so . The case of is the mirror image, with .
Theorem 1 (envy-free with connected pieces). The pieces , and of lines L7 to L9 form a partition of into three intervals, and no agent envies another.
Proof. by Lemmas 1 and 2, so the three intervals cover and meet only at end points. The shouter has , so is at least the value of each right piece. Agent gets , which by Lemma 4 is its better right piece, so , where the last step is from Lemma 2. The same argument holds for with .
Lemma 5 (exact simulation for the implementation). Let every have a positive density that is constant on each of the segments . Let be the set of points , together with each where some knife equals some , together with each where two knives cross between two such points. On each interval between consecutive points of , the knives, the median , and the two gaps and are affine in .
Proof. On , stays in one segment, so is affine. The knife stays in one segment too, because it does not cross a point inside ; on that segment is affine, so is affine. Two knives do not cross inside , so the order of the knives is the same on all of and is one fixed knife , hence affine. All agents use the same segments, so also stays in one segment and is affine. Then and are affine.
An affine function is determined by its values at and , and the set where it is nonnegative is an interval whose end points the code computes exactly in Fraction. The condition of line L5 is and , so the code finds the least such point in the first interval where it exists, and that point is . The crossing points of two knives between consecutive points of the first kind are found by the same linear interpolation, because both knives are affine there.
Complexity
The procedure uses two cuts, the fewest possible for three connected pieces. It is not a finite protocol: the agents watch values change continuously, and no finite number of Robertson-Webb queries replaces this in general, by Stromquist's 2008 theorem.
The simulation for piecewise-constant valuations with segments costs arithmetic operations on rationals, in the real-RAM sense. It builds the prefix sums of each valuation in , finds break points ( segment ends, at most points per knife where it crosses a segment end, and at most three knife crossings between two of these), sorts them, and does work per break point to invert a valuation. The rationals can grow in size, so the bit cost is larger.
Properties
- Envy-free and connected. Each agent gets one interval, and envy-freeness implies proportionality.
- Two cuts. The sword and the middle knife are the only cuts.
- Each agent can protect itself. An agent that keeps its knife at its own halving point and shouts at the right moment gets a piece it does not envy, as long as the other knives move continuously. The proof above uses, for one agent, only its own knife and the rule for the median.
- Not Pareto optimal in general. It finds one envy-free division, not a best one.
- Ties. If two agents would shout at the same moment, either one can take the left part; both pieces left are still fine for the other.
Variants and improvements
- A simpler procedure. Barbanel and Brams gave a moving-knife procedure for three agents that also uses two cuts and is simpler to run.
- More agents. There is no natural extension to four or more agents with connected pieces. For agents, envy-free divisions into intervals still exist (Stromquist 1980), and Su's algorithm uses Sperner's lemma to find approximate ones.
- Finite protocols. If pieces need not be connected, the Selfridge-Conway procedure is finite for three agents.
When to use it
Use the Stromquist moving knife when three agents must get one interval each with no envy, and the agents can watch a continuous process, or when the valuations are known well enough to simulate it, as for piecewise-constant densities. When only queries are available, use the Selfridge-Conway procedure and accept pieces of two intervals, or find an approximately envy-free division of intervals.
Pitfalls
- A knife that jumps. If an agent values some interval at 0, its halving point is not unique and can jump. Then the median can jump, and the first moment of a shout may not have the equality that the proof needs. Use positive densities, or fix a continuous choice of the halving point.
- The middle knife, not a fixed agent's knife. The second cut is at the median of the three knives, and which agent holds it can change as the sword moves.
- The wrong right piece. Each non-shouter gets the piece that contains its own knife. Giving the middle part to a fixed agent breaks envy-freeness.
- Treating it as finite. A discrete search for the shout point with finitely many queries in the Robertson-Webb model can only find an approximate answer in general.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the algorithmic game theory pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Piecewise-constant cake valuations and a Robertson-Webb query oracle.
The cake is the interval [0, 1]. A valuation is a list of k nonnegative
Fraction densities d[0], ..., d[k - 1]. Density d[j] holds on the segment
[j/k, (j + 1)/k], so that segment has value d[j] / k. A valuation is
normalized when the value of the whole cake is 1, that is, sum(d) = k.
All numbers are Fraction, so every value and every cut point is exact.
This module holds no cake cutting protocol.
"""
from fractions import Fraction
from random import Random
from typing import Optional, Sequence
Valuation = list[Fraction]
Interval = tuple[Fraction, Fraction]
ZERO = Fraction(0)
ONE = Fraction(1)
def normalize(dens: Sequence) -> Valuation:
"""Scale nonnegative densities so that the whole cake has value 1."""
d = [Fraction(x) for x in dens]
if not d:
raise ValueError("a valuation needs at least one segment")
if any(x < 0 for x in d):
raise ValueError("densities must be nonnegative")
total = sum(d)
if total == 0:
raise ValueError("densities must not all be zero")
k = len(d)
return [x * k / total for x in d]
def _check_point(x: Fraction) -> None:
if x < 0 or x > 1:
raise ValueError("a point of the cake must be in [0, 1]")
def value(v: Valuation, a, b) -> Fraction:
"""Return the value of the interval [a, b] under v. Needs 0 <= a <= b <= 1."""
a, b = Fraction(a), Fraction(b)
_check_point(a)
_check_point(b)
if a > b:
raise ValueError("value(v, a, b) needs a <= b")
k = len(v)
total = ZERO
j = min(int(a * k), k - 1)
while j < k:
lo = Fraction(j, k)
if lo >= b:
break
hi = Fraction(j + 1, k)
left = a if a > lo else lo
right = b if b < hi else hi
if right > left:
total += v[j] * (right - left)
j += 1
return total
def cut(v: Valuation, a, t) -> Optional[Fraction]:
"""Return the least x >= a with value(v, a, x) = t, or None if there is none."""
a, t = Fraction(a), Fraction(t)
_check_point(a)
if t < 0:
raise ValueError("cut(v, a, t) needs t >= 0")
if t == 0:
return a
k = len(v)
pos = a
rest = t
j = min(int(a * k), k - 1)
while j < k:
hi = Fraction(j + 1, k)
d = v[j]
if d > 0 and hi > pos:
here = d * (hi - pos)
if rest <= here:
return pos + rest / d
rest -= here
if hi > pos:
pos = hi
j += 1
return None
def piece_value(v: Valuation, piece: Sequence[Interval]) -> Fraction:
"""Return the value of a piece, given as a list of intervals (a, b)."""
return sum((value(v, a, b) for a, b in piece), ZERO)
def random_valuation(rng: Random, k: int, hi: int) -> Valuation:
"""Return a normalized valuation with k segments and integer densities in 0..hi."""
if k < 1 or hi < 1:
raise ValueError("random_valuation needs k >= 1 and hi >= 1")
while True:
dens = [rng.randint(0, hi) for _ in range(k)]
if any(dens):
return normalize(dens)
class Oracle:
"""Answer Robertson-Webb queries for a list of valuations and count them.
eval_query(i, a, b) returns V_i([a, b]). cut_query(i, a, t) returns the
least x with V_i([a, x]) = t, or None. The lists evals and cuts hold the
number of queries of each kind for each agent.
"""
def __init__(self, valuations: Sequence[Valuation]) -> None:
self.valuations = [list(v) for v in valuations]
n = len(self.valuations)
self.evals = [0] * n
self.cuts = [0] * n
@property
def n(self) -> int:
return len(self.valuations)
def eval_query(self, i: int, a, b) -> Fraction:
self.evals[i] += 1
return value(self.valuations[i], a, b)
def cut_query(self, i: int, a, t) -> Optional[Fraction]:
self.cuts[i] += 1
return cut(self.valuations[i], a, t)
def total_evals(self) -> int:
return sum(self.evals)
def total_cuts(self) -> int:
return sum(self.cuts)
def total(self) -> int:
return self.total_evals() + self.total_cuts()
stromquist_moving_knife.py 118 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stromquist-moving-knife/. The authors are listed in prov/PK1D3M.jsonl.
"""An exact simulation of the Stromquist moving knife for three agents.
The knives move continuously, so this is not a finite protocol. For
piecewise-constant valuations with positive densities on the same k equal
segments, each knife position k_i(x) and the median knife y(x) are
continuous and piecewise affine in the sword position x. The simulation
splits [0, 1] at every point where one of these functions can bend, and on
each part it solves the shout condition, which is then affine, exactly.
"""
from bisect import bisect_right
from fractions import Fraction
from agtcake import Valuation
Interval = tuple[Fraction, Fraction]
class _Cdf:
"""F(x) = V([0, x]) and its inverse, for positive piecewise-constant densities."""
def __init__(self, v: Valuation) -> None:
self.d = list(v)
self.k = len(v)
self.pre = [Fraction(0)]
for dj in self.d:
self.pre.append(self.pre[-1] + dj / self.k)
def f(self, x: Fraction) -> Fraction:
j = min(int(x * self.k), self.k - 1)
return self.pre[j] + self.d[j] * (x - Fraction(j, self.k))
def inv(self, t: Fraction) -> Fraction:
j = min(bisect_right(self.pre, t) - 1, self.k - 1)
return Fraction(j, self.k) + (t - self.pre[j]) / self.d[j]
def knife(self, x: Fraction) -> Fraction:
"""The point that splits [x, 1] into two halves of equal value."""
return self.inv((1 + self.f(x)) / 2)
def _breakpoints(cdfs: list[_Cdf]) -> list[Fraction]:
k = cdfs[0].k
pts = {Fraction(j, k) for j in range(k + 1)} # the density at x changes
for c in cdfs:
for j in range(1, k):
t = 2 * c.pre[j] - 1
if t > 0:
pts.add(c.inv(t)) # this knife crosses j/k
base = sorted(pts)
knives = [[c.knife(p) for c in cdfs] for p in base]
more = set(base)
for s in range(len(base) - 1):
p, q = base[s], base[s + 1]
kp, kq = knives[s], knives[s + 1]
for i in range(3):
for m in range(i + 1, 3):
dp, dq = kp[i] - kp[m], kq[i] - kq[m]
if dp * dq < 0:
more.add(p + (q - p) * dp / (dp - dq)) # two knives cross
return sorted(more)
def _nonneg_part(hp: Fraction, hq: Fraction, p: Fraction, q: Fraction):
"""The part of [p, q] where an affine h with h(p) = hp, h(q) = hq is >= 0."""
if hp >= 0 and hq >= 0:
return p, q
if hp < 0 and hq < 0:
return None
r = p + (q - p) * hp / (hp - hq)
return (p, r) if hp >= 0 else (r, q)
def _gaps(c: _Cdf, x: Fraction, y: Fraction) -> tuple[Fraction, Fraction]:
"""V([0, x]) - V([x, y]) and V([0, x]) - V([y, 1])."""
fx, fy = c.f(x), c.f(y)
return 2 * fx - fy, fx - 1 + fy
def stromquist(vals: list[Valuation]) -> tuple[dict[int, Interval], Fraction, Fraction, int]:
"""Run the knives. Return (pieces, x, y, shouter); agents are 0, 1 and 2."""
if len(vals) != 3 or len({len(v) for v in vals}) != 1:
raise ValueError("three valuations on the same segments are needed")
if any(d <= 0 for v in vals for d in v):
raise ValueError("the simulation needs positive densities")
cdfs = [_Cdf(v) for v in vals]
pts = _breakpoints(cdfs) # @line L1
found = None
yq = sorted(c.knife(pts[0]) for c in cdfs)[1]
for p, q in zip(pts, pts[1:]): # @line L2
yp = yq # @line L3
yq = sorted(c.knife(q) for c in cdfs)[1] # @line L4
best = None
for i, c in enumerate(cdfs): # @line L5
a1, a2 = _gaps(c, p, yp)
b1, b2 = _gaps(c, q, yq)
s1 = _nonneg_part(a1, b1, p, q)
s2 = _nonneg_part(a2, b2, p, q)
if s1 is None or s2 is None:
continue
lo, hi = max(s1[0], s2[0]), min(s1[1], s2[1])
if lo <= hi and (best is None or lo < best[0]):
best = (lo, i) # @line L6
if best is not None:
found = best
break
assert found is not None # someone shouts before x reaches 1
x, s = found
ks = [c.knife(x) for c in cdfs]
y = sorted(ks)[1]
pieces: dict[int, Interval] = {s: (Fraction(0), x)} # @line L7
a, b = sorted((i for i in range(3) if i != s), key=lambda i: (ks[i], i))
pieces[a] = (x, y) # @line L8
pieces[b] = (y, Fraction(1)) # @line L9
return pieces, x, y, s
test_stromquist_moving_knife.py 93 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stromquist-moving-knife/. The authors are listed in prov/PK1D3M.jsonl.
import random
from fractions import Fraction
import pytest
from agtcake import cut, normalize, value
from stromquist_moving_knife import stromquist
F = Fraction
def positive_valuation(rng: random.Random, k: int, hi: int):
return normalize([rng.randint(1, hi) for _ in range(k)])
def bisect(v, x):
"""The knife of v at sword position x, by the helper (independent of the slug file)."""
return cut(v, x, value(v, x, 1) / 2)
def shout_gap(v, x, y):
"""min(V[0, x] - V[x, y], V[0, x] - V[y, 1]); the agent shouts when it is >= 0."""
left = value(v, 0, x)
return min(left - value(v, x, y), left - value(v, y, 1))
def check_run(vals, grid: int = 0):
pieces, x, y, s = stromquist(vals)
# connected pieces that cover [0, 1] in order
assert pieces[s] == (0, x)
assert sorted(pieces.values()) == [(0, x), (x, y), (y, 1)]
assert 0 < x <= y <= 1
# y is the median knife at x
knives = [bisect(v, x) for v in vals]
assert y == sorted(knives)[1]
# envy-free, exactly
for i in range(3):
own = value(vals[i], *pieces[i])
for j in range(3):
assert own >= value(vals[i], *pieces[j])
# x is the first moment: the shouter's gap is 0, nobody else's is positive
assert shout_gap(vals[s], x, y) == 0
for i in range(3):
assert shout_gap(vals[i], x, y) <= 0 or i == s
if i < s:
assert shout_gap(vals[i], x, y) < 0
# a second method: on a grid of sword positions before x, nobody shouts
for t in range(1, grid):
z = F(t, grid)
if z >= x:
break
yz = sorted(bisect(v, z) for v in vals)[1]
assert all(shout_gap(v, z, yz) < 0 for v in vals)
return pieces, x, y, s
def test_page_example() -> None:
vals = [normalize([1, 1, 1, 1]), normalize([2, 2, 1, 1]), normalize([1, 1, 1, 3])]
pieces, x, y, s = check_run(vals, grid=60)
assert (x, y, s) == (F(2, 7), F(9, 14), 1)
assert [bisect(v, x) for v in vals] == [F(9, 14), F(15, 28), F(67, 84)]
assert pieces == {1: (0, F(2, 7)), 0: (F(2, 7), F(9, 14)), 2: (F(9, 14), 1)}
table = [[value(vals[i], *pieces[j]) for j in range(3)] for i in range(3)]
assert table == [
[F(5, 14), F(2, 7), F(5, 14)],
[F(8, 21), F(8, 21), F(5, 21)],
[F(5, 21), F(4, 21), F(4, 7)],
]
def test_identical_valuations_give_thirds() -> None:
rng = random.Random(5)
for _ in range(20):
v = positive_valuation(rng, rng.randint(1, 8), 6)
pieces, x, y, s = check_run([v, v, v])
assert s == 0
assert all(value(v, *pieces[i]) == F(1, 3) for i in range(3))
def test_random_valuations() -> None:
rng = random.Random(31)
for _ in range(60):
k = rng.randint(1, 8)
vals = [positive_valuation(rng, k, 6) for _ in range(3)]
check_run(vals, grid=24)
def test_needs_positive_densities() -> None:
with pytest.raises(ValueError):
stromquist([normalize([1, 0]), normalize([1, 1]), normalize([1, 1])])
History
Walter Stromquist published the procedure in 1980 in the American Mathematical Monthly, in the same paper that proves that envy-free divisions into intervals exist for any number of agents. In 2008 Stromquist proved that no finite protocol finds envy-free divisions into intervals for three or more agents.
References
- Walter Stromquist, How to cut a cake fairly, American Mathematical Monthly 87(8) (1980), pp. 640-644 (the moving-knife procedure for three players, and the existence of envy-free divisions into intervals)
- Steven J. Brams and Alan D. Taylor, Fair Division, From Cake-Cutting to Dispute Resolution, Cambridge University Press, 1996, the moving-knife procedures for three persons
- Walter Stromquist, Envy-free cake divisions cannot be found by finite protocols, Electronic Journal of Combinatorics 15 (2008), R11, Sections 1 and 3 (why the moving knife cannot be made finite)
- Julius B. Barbanel and Steven J. Brams, Cake division with minimal cuts: envy-free procedures for 3 persons, 4 persons, and beyond, Mathematical Social Sciences 48 (2004), 251-269, a simpler moving-knife procedure for three persons with two cuts
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag PK1D3M Edit this page History Report an error Markdown