Algorithm Search⌘K

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.

Time
O(k log k) worst
Space
O(k) extra
Where
k = the number of segments of a piecewise-constant valuation
Properties
deterministicofflineiterative

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 [0,1][0, 1]. Agents 1, 2 and 3 have nonnegative, additive and nonatomic valuations ViV_i with Vi([0,1])=1V_i([0, 1]) = 1. The procedure must output three intervals that cover the cake and meet only at end points, one for each agent, with Vi(Xi)≥Vi(Xj)V_i(X_i) \ge V_i(X_j) for all ii and jj. 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 xx, agent ii holds its knife at ki(x)k_i(x), the point of [x,1][x, 1] with Vi([x,ki])=Vi([ki,1])V_i([x, k_i]) = V_i([k_i, 1]). The median knife is y(x)=med(k1(x),k2(x),k3(x))y(x) = \mathrm{med}(k_1(x), k_2(x), k_3(x)).

  1. STROMQUIST-KNIFE(agents 1, 2, 3)
  2. 1the referee puts the sword at x = 0
  3. 2move x continuously to the right, and at each moment:
  4. 3each agent i holds its knife at k_i(x) ▷ halves [x, 1] in its eyes
  5. 4y ← the median of k_1(x), k_2(x), k_3(x)
  6. 5agent i shouts if V_i([0, x]) ≥ V_i([x, y]) and V_i([0, x]) ≥ V_i([y, 1])
  7. 6stop at the first shout; s ← the agent that shouts ▷ ties go to the smallest index
  8. 7cut at x and at y; give [0, x] to s
  9. 8of the two other agents, the one whose knife is further left gets [x, y]
  10. 9the other one gets [y, 1]

The procedure is a thought experiment with continuous motion. For valuations with positive piecewise-constant densities on kk equal segments, the implementation simulates it exactly: every knife position and the median are piecewise affine in xx, with O(k)O(k) 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 (2,2,1,1)(2, 2, 1, 1), and agent 3 to (1,1,1,3)(1, 1, 1, 3). The first shout comes at x=2/7x = 2/7. There the knives are at k1=9/14k_1 = 9/14, k2=15/28k_2 = 15/28 and k3=67/84k_3 = 67/84, so the median is y=9/14y = 9/14, the knife of agent 1.

Agent 2 values [0,2/7][0, 2/7] at 8/218/21, [2/7,9/14][2/7, 9/14] at 8/218/21 and [9/14,1][9/14, 1] at 5/215/21. So agent 2 shouts at the moment its left part ties with its best right part, and it gets [0,2/7][0, 2/7]. Agent 1's knife (9/149/14) is left of agent 3's knife (67/8467/84), so agent 1 gets [2/7,9/14][2/7, 9/14] and agent 3 gets [9/14,1][9/14, 1]. Row ii gives ViV_i of each agent's piece:

X1=[2/7,9/14]X_1 = [2/7, 9/14] X2=[0,2/7]X_2 = [0, 2/7] X3=[9/14,1]X_3 = [9/14, 1]
V1V_1 5/14 2/7 5/14
V2V_2 8/21 8/21 5/21
V3V_3 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 5/145/14.

Correctness

The knife positions and the median knife move continuously, because each ViV_i is continuous and strictly increasing on [0,1][0, 1]. Let hi(x)h_i(x) be the value of the left part to agent ii minus the larger of the values of the two right parts. At x=0x = 0, hih_i is at most −1/2-1/2; at x=1x = 1, it is 11. So there is a first moment x∗>0x^* > 0 when some hih_i reaches 0, and at that moment no hih_i is positive, because each hih_i was negative just before.

The shouter has hs(x∗)≥0h_s(x^*) \ge 0, so it values the left part at least as much as each right part. The two other agents have hi(x∗)≤0h_i(x^*) \le 0, 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 [x∗,y][x^*, y] at least half of [x∗,1][x^*, 1], so [x∗,y][x^*, y] 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 [0,1][0, 1]. Agents 1, 2 and 3 have nonnegative, additive and nonatomic valuations ViV_i with Vi([0,1])=1V_i([0, 1]) = 1. 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 Gi(x)=Vi([0,x])G_i(x) = V_i([0, x]). Then GiG_i is continuous, strictly increasing, Gi(0)=0G_i(0) = 0 and Gi(1)=1G_i(1) = 1, so it has a continuous inverse Gi−1G_i^{-1} on [0,1][0, 1]. We refer to the lines L1 to L9 of the page.

Lemma 1 (the knives move continuously). For x∈[0,1]x \in [0, 1], agent ii has exactly one knife position ki(x)∈[x,1]k_i(x) \in [x, 1] with Vi([x,ki(x)])=Vi([ki(x),1])V_i([x, k_i(x)]) = V_i([k_i(x), 1]), namely

ki(x)=Gi−1(1+Gi(x)2).k_i(x) = G_i^{-1}\left(\frac{1 + G_i(x)}{2}\right).

The maps kik_i and the median knife y(x)=med(k1(x),k2(x),k3(x))y(x) = \mathrm{med}(k_1(x), k_2(x), k_3(x)) are continuous, and x≤y(x)≤1x \le y(x) \le 1.

Proof. The condition says Gi(k)−Gi(x)=1−Gi(k)G_i(k) - G_i(x) = 1 - G_i(k), that is Gi(k)=(1+Gi(x))/2G_i(k) = (1 + G_i(x))/2. Since GiG_i is a strictly increasing bijection of [0,1][0, 1], there is exactly one such kk, and Gi(x)≤(1+Gi(x))/2≤1G_i(x) \le (1 + G_i(x))/2 \le 1 gives x≤k≤1x \le k \le 1. The formula is a composition of continuous maps. The median of three numbers is max⁡(min⁡(a,b),min⁡(a,c),min⁡(b,c))\max(\min(a, b), \min(a, c), \min(b, c)), which is continuous in (a,b,c)(a, b, c). Each ki(x)k_i(x) lies in [x,1][x, 1], so the median does too. □\square

Lemma 2 (the first shout). Let hi(x)=Vi([0,x])−max⁡(Vi([x,y(x)]),Vi([y(x),1]))h_i(x) = V_i([0, x]) - \max(V_i([x, y(x)]), V_i([y(x), 1])). Line L5 stops at x∗=min⁡{x∈[0,1]:hi(x)≥0 for some i}x^* = \min\{x \in [0, 1] : h_i(x) \ge 0 \text{ for some } i\}. This minimum exists, x∗>0x^* > 0, hs(x∗)≥0h_s(x^*) \ge 0 for the shouter ss, and hi(x∗)≤0h_i(x^*) \le 0 for every agent ii.

Proof. Each hih_i is continuous by Lemma 1. At x=0x = 0, Vi([0,0])=0V_i([0, 0]) = 0 and the two right pieces have total value 1, so the larger is at least 1/21/2 and hi(0)≤−1/2<0h_i(0) \le -1/2 < 0. At x=1x = 1, y(1)=1y(1) = 1 and hi(1)=1>0h_i(1) = 1 > 0. So the set S={x:max⁡ihi(x)≥0}S = \{x : \max_i h_i(x) \ge 0\} is nonempty, and it is closed because max⁡ihi\max_i h_i is continuous. Its least element x∗x^* exists, and x∗>0x^* > 0. The knife stops at the first xx where some agent's condition holds, which is x∗x^*; line L6 picks one such agent ss, so hs(x∗)≥0h_s(x^*) \ge 0. For every ii and every x<x∗x < x^*, hi(x)<0h_i(x) < 0, so hi(x∗)=lim⁡x→x∗, x<x∗hi(x)≤0h_i(x^*) = \lim_{x \to x^*,\, x < x^*} h_i(x) \le 0. □\square

So hs(x∗)=0h_s(x^*) = 0: the shouter shouts at the moment of equality.

Lemma 3 (the knives of the others). Let aa and bb be the two agents other than ss, with ka(x∗)≤kb(x∗)k_a(x^*) \le k_b(x^*) as in line L8. Then ka(x∗)≤y≤kb(x∗)k_a(x^*) \le y \le k_b(x^*), where y=y(x∗)y = y(x^*).

Proof. The median yy 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 y=ksy = k_s, then kak_a and kbk_b are the other two, one on each side. If y=kay = k_a (as a value), then ka≤yk_a \le y, and kb≥ka=yk_b \ge k_a = y. If y=kby = k_b, then kb≥yk_b \ge y, and ka≤kb=yk_a \le k_b = y. □\square

Lemma 4 (each other agent gets its better right piece). Agent aa values [x∗,y][x^*, y] at least as much as [y,1][y, 1], and agent bb values [y,1][y, 1] at least as much as [x∗,y][x^*, y].

Proof. Write x=x∗x = x^*. Since ka≤yk_a \le y, monotonicity gives Va([x,y])≥Va([x,ka])=Va([x,1])/2V_a([x, y]) \ge V_a([x, k_a]) = V_a([x, 1])/2, so Va([y,1])=Va([x,1])−Va([x,y])≤Va([x,1])/2≤Va([x,y])V_a([y, 1]) = V_a([x, 1]) - V_a([x, y]) \le V_a([x, 1])/2 \le V_a([x, y]). The case of bb is the mirror image, with kb≥yk_b \ge y. □\square

Theorem 1 (envy-free with connected pieces). The pieces [0,x∗][0, x^*], [x∗,y][x^*, y] and [y,1][y, 1] of lines L7 to L9 form a partition of [0,1][0, 1] into three intervals, and no agent envies another.

Proof. 0<x∗≤y≤10 < x^* \le y \le 1 by Lemmas 1 and 2, so the three intervals cover [0,1][0, 1] and meet only at end points. The shouter ss has hs(x∗)≥0h_s(x^*) \ge 0, so Vs([0,x∗])V_s([0, x^*]) is at least the value of each right piece. Agent aa gets [x∗,y][x^*, y], which by Lemma 4 is its better right piece, so Va([x∗,y])=max⁡(Va([x∗,y]),Va([y,1]))≥Va([0,x∗])V_a([x^*, y]) = \max(V_a([x^*, y]), V_a([y, 1])) \ge V_a([0, x^*]), where the last step is ha(x∗)≤0h_a(x^*) \le 0 from Lemma 2. The same argument holds for bb with [y,1][y, 1]. □\square

Lemma 5 (exact simulation for the implementation). Let every ViV_i have a positive density that is constant on each of the kk segments [j/k,(j+1)/k][j/k, (j+1)/k]. Let BB be the set of points j/kj/k, together with each xx where some knife ki(x)k_i(x) equals some j/kj/k, together with each xx where two knives cross between two such points. On each interval [p,q][p, q] between consecutive points of BB, the knives, the median yy, and the two gaps g1=Vi([0,x])−Vi([x,y])g_1 = V_i([0, x]) - V_i([x, y]) and g2=Vi([0,x])−Vi([y,1])g_2 = V_i([0, x]) - V_i([y, 1]) are affine in xx.

Proof. On [p,q][p, q], xx stays in one segment, so Gi(x)G_i(x) is affine. The knife ki(x)k_i(x) stays in one segment too, because it does not cross a point j/kj/k inside (p,q)(p, q); on that segment Gi−1G_i^{-1} is affine, so kik_i is affine. Two knives do not cross inside (p,q)(p, q), so the order of the knives is the same on all of (p,q)(p, q) and yy is one fixed knife klk_l, hence affine. All agents use the same segments, so y=kly = k_l also stays in one segment and Gi(y)G_i(y) is affine. Then g1=2Gi(x)−Gi(y)g_1 = 2 G_i(x) - G_i(y) and g2=Gi(x)+Gi(y)−1g_2 = G_i(x) + G_i(y) - 1 are affine. □\square

An affine function is determined by its values at pp and qq, 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 g1≥0g_1 \ge 0 and g2≥0g_2 \ge 0, so the code finds the least such point in the first interval [p,q][p, q] where it exists, and that point is x∗x^*. 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 kk segments costs O(klog⁡k)O(k \log k) arithmetic operations on rationals, in the real-RAM sense. It builds the prefix sums of each valuation in O(k)O(k), finds O(k)O(k) break points (k+1k + 1 segment ends, at most k−1k - 1 points per knife where it crosses a segment end, and at most three knife crossings between two of these), sorts them, and does O(log⁡k)O(\log k) 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 nn 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.

agtcake.pyI0RawGitHub
# 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

  1. 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)
  2. 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
  3. 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)
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • a scene preset for the example