Algorithm Search⌘K

Algorithmadvanced

Su's algorithm for rental harmony

Also called Sperner rent division.

Finds an approximately envy-free rent division by following doors through a triangulated simplex of price vectors, as in the path-following proof of Sperner's lemma.

Time
O(n^2 N^(n-1) + 4^n n! n^2) worst
Space
O(n N^(n-1) + n 4^n) extra
Where
N = the grid size; n = the number of rooms and tenants
Properties
deterministicofflineiterative

Su's algorithm for rental harmony finds rooms and prices for nn tenants that share a fixed rent, so that each tenant almost prefers its own room at its price to every other room. It covers the simplex of all ways to split the rent with a grid of small cells, gives each grid point an owner among the tenants, asks the owner which room it would choose at those prices, and walks from cell to cell through "doors" until it finds a cell where the nn owners choose nn different rooms. The rental harmony page states the problem and its existence theorem; this page is the procedure that finds an approximate solution with a finite number of questions. It differs from Sperner's lemma itself in its labels: the room labels are not a Sperner labeling, because a tenant takes a free room, so the walk starts at a door on the boundary next to the corner where one room costs all the rent.

In plain words

Housemates must split the rent of a house and pick rooms. A helper writes down many price lists, each a small step from its neighbours. Each list gets one housemate as its owner, arranged so that every small group of neighbouring lists has every housemate as an owner once.

The helper starts at a group of lists near the edge, where some rooms are free. For each list it asks the owner: "Which room would you take at these prices?" Then it moves to a neighbouring group, one new list at a time, by a fixed rule that never goes back. It stops at a group where every owner picks a different room. Each housemate gets the room it picked, and the final prices are the average of the lists in that group. They are so close to each list that nobody cares about the difference.

The problem

There are nn rooms and nn tenants, numbered 00 to n−1n - 1, and a total rent RR. A price vector is p≥0p \ge 0 with ∑jpj=R\sum_j p_j = R. At each price vector, each tenant chooses one room. The tenants are miserly: at a price vector with a free room (pj=0p_j = 0), a tenant chooses a free room. The goal is a permutation rr of the rooms and a price vector qq such that, for each tenant ii, room rir_i is the choice of tenant ii at a price vector within R/NR/N of qq in every room. For tenants whose choices change only a little when prices change a little, this is an approximately envy-free rent division.

The algorithm

Fix a grid size N≥nN \ge n. A grid point is an integer vector ss with 0≤s0≤⋯≤sn−2≤N0 \le s_0 \le \dots \le s_{n-2} \le N, and its prices are pj=Rxj/Np_j = R x_j / N with x0=s0x_0 = s_0, xj=sj−sj−1x_j = s_j - s_{j-1} and xn−1=N−sn−2x_{n-1} = N - s_{n-2}. A cell is a set of nn grid points y0,y1,…,yn−1y^0, y^1, \dots, y^{n-1} with yt=yt−1+eπty^t = y^{t-1} + e_{\pi_t} for a permutation π\pi; these cells triangulate the region. The owner of ss is the tenant (s0+⋯+sn−2) mod n(s_0 + \dots + s_{n-2}) \bmod n, and the label of ss is the room its owner chooses at the prices of ss. A door is a face of n−1n - 1 points of a cell whose labels are exactly the rooms 0,…,n−20, \dots, n - 2.

  1. SU-RENTAL-HARMONY(n, R, N, tenants)
  2. 1label(s) ← the room that the owner of s chooses at the prices of s ▷ ask each point at most once
  3. 2for each door D on the boundary, in its cell C:
  4. 3loop
  5. 4v_0, …, v_{n-1} ← the vertices of C, with their labels
  6. 5if the labels are all n rooms then
  7. 6give each owner the label of its vertex
  8. 7return the rooms and the average of the vertex prices
  9. 8u ← the vertex of the entry door with the same label as the new vertex
  10. 9C' ← the other cell that holds the face without u; if C' is outside the region, go to the next door
  11. 10C ← C', and its new vertex is the one not in that face

Lines L9 and L10 use the pivot rules of the Freudenthal (Kuhn) triangulation: removing an inner vertex swaps two neighbours in π\pi, and removing the first or the last vertex shifts the base point and rotates π\pi. With miserly tenants, every boundary door lies in a cell whose base point has all coordinates at most n−2n - 2, so line L2 searches a part of the region whose size does not depend on NN.

Example

Take n=3n = 3, R=900R = 900 and N=6N = 6, so prices move in steps of 150150. In its own eyes, tenant 0 pays half the price for room 0, tenant 1 pays half the price for room 1, and tenant 2 pays the real prices; each picks the room that costs it least, with ties going to the smaller room. A free room costs nothing, so the tenants are miserly. The walk starts at the only boundary door, the face with prices (0,0,900)(0, 0, 900) and (150,0,750)(150, 0, 750). Each row gives the three vertices of a cell as prices (owner, label):

Step Vertex 1 Vertex 2 Vertex 3
1 (0, 0, 900) (0, 0) (0, 150, 750) (1, 0) (150, 0, 750) (2, 1)
2 (0, 150, 750) (1, 0) (150, 0, 750) (2, 1) (150, 150, 600) (0, 0)
3 (150, 0, 750) (2, 1) (150, 150, 600) (0, 0) (300, 0, 600) (1, 1)
4 (150, 150, 600) (0, 0) (300, 0, 600) (1, 1) (300, 150, 450) (2, 1)
5 (150, 150, 600) (0, 0) (150, 300, 450) (1, 0) (300, 150, 450) (2, 1)
6 (150, 300, 450) (1, 0) (300, 150, 450) (2, 1) (300, 300, 300) (0, 0)
7 (300, 150, 450) (2, 1) (300, 300, 300) (0, 0) (450, 150, 300) (1, 1)
8 (300, 300, 300) (0, 0) (450, 150, 300) (1, 1) (450, 300, 150) (2, 2)

Each cell after the first shares two vertices with the cell before it, and those two vertices have the labels 0 and 1. The cell of step 8 has the labels 0, 1 and 2, so tenant 0 gets room 0, tenant 1 gets room 1 and tenant 2 gets room 2. The average of its three price vectors is (400,250,250)(400, 250, 250). At these prices tenant 0 pays 200200 for room 0 in its own eyes, against 250250 for each other room; tenant 1 pays 125125 for room 1, against 400400 and 250250; tenant 2 pays 250250 for room 2, which ties with room 1 and beats room 0. So in this example the result is exactly envy-free. The algorithm asked 11 questions, out of 28 grid points and 36 cells.

Correctness

The nn vertices of a cell have coordinate sums that are nn consecutive integers, so they have nn different owners. If the labels are all nn rooms, line L6 gives each tenant one room and each room one tenant, and each tenant chose its room at the prices of its vertex. Within one cell each price varies by at most R/NR/N, so the average price vector is within R/NR/N of every vertex price in every room.

A cell has two doors, or none, unless it is fully labeled, in which case it has one door. So the walk enters each cell through one door and leaves through the other, it never visits a cell twice, and it stops at a fully labeled cell or at another boundary door. For two and three rooms there is exactly one boundary door, so the walk always succeeds. For more rooms, the number of fully labeled cells and the number of boundary doors have the same parity, and Su proves with a dual form of Sperner's lemma, due to Scarf, that a fully labeled cell exists. The details, and the part of the argument that is only partly proved here, are in proofs/correctness.md.

Proof: Su's path-following algorithm returns a fully labeled cell with nearly envy-free pricespartial

Setting. There are n≥2n \ge 2 rooms and nn tenants, both numbered 00 to n−1n - 1, a total rent R>0R > 0 and a grid size N≥nN \ge n. Let d=n−1d = n - 1. A grid point is an integer vector s=(s0,…,sd−1)s = (s_0, \dots, s_{d-1}) in the region T={0≤s0≤s1≤⋯≤sd−1≤N}T = \{0 \le s_0 \le s_1 \le \dots \le s_{d-1} \le N\}. Its room prices are pj=Rxj/Np_j = R x_j / N, where x0=s0x_0 = s_0, xj=sj−sj−1x_j = s_j - s_{j-1} for 1≤j≤d−11 \le j \le d - 1 and xn−1=N−sd−1x_{n-1} = N - s_{d-1}. So x≥0x \ge 0 and ∑jxj=N\sum_j x_j = N, and s↦xs \mapsto x is a bijection from the grid points of TT to the integer points of the price simplex scaled by N/RN/R. Room jj is free at ss when xj=0x_j = 0. A tenant is miserly if it chooses a free room whenever one exists. The owner of ss is σ(s)=(s0+⋯+sd−1) mod n\sigma(s) = (s_0 + \dots + s_{d-1}) \bmod n, and the label ℓ(s)\ell(s) is the room that the owner chooses at the prices of ss. We refer to the lines L1 to L10 of the page.

A cell is a pair (b,π)(b, \pi) of an integer vector bb and a permutation π=(π1,…,πd)\pi = (\pi_1, \dots, \pi_d) of the coordinates. Its vertices are y0=by^0 = b and yt=yt−1+eπty^t = y^{t-1} + e_{\pi_t} for t=1,…,dt = 1, \dots, d. These are the simplices of the Freudenthal (Kuhn) triangulation of Rd\mathbb{R}^d. We use the standard facts about this triangulation: the cells cover Rd\mathbb{R}^d, two cells meet in a common face, and each facet of a cell lies in exactly one other cell. The hyperplanes s0=0s_0 = 0, sj=sj−1s_j = s_{j-1} and sd−1=Ns_{d-1} = N that bound TT are hyperplanes of the triangulation, so the cells whose vertices all lie in TT triangulate TT.

Lemma 1 (the pivot). Let C=(b,π)C = (b, \pi). The other cell that contains the facet C∖{yt}C \setminus \{y^t\} is: for 0<t<d0 < t < d, (b,π′)(b, \pi') where π′\pi' swaps πt\pi_t and πt+1\pi_{t+1}; for t=0t = 0, (b+eπ1,(π2,…,πd,π1))(b + e_{\pi_1}, (\pi_2, \dots, \pi_d, \pi_1)); for t=dt = d, (b−eπd,(πd,π1,…,πd−1))(b - e_{\pi_d}, (\pi_d, \pi_1, \dots, \pi_{d-1})). The facet lies on the boundary of TT if and only if this cell is not inside TT.

Proof. For 0<t<d0 < t < d, the new cell has the vertices y0,…,yt−1y^0, \dots, y^{t-1}, then yt−1+eπt+1y^{t-1} + e_{\pi_{t+1}}, then yt+1,…,ydy^{t+1}, \dots, y^d, so it shares every vertex but yty^t. For t=0t = 0, the new chain starts at y1y^1, adds eπ2,…,eπde_{\pi_2}, \dots, e_{\pi_d} to reach ydy^d, and then adds eπ1e_{\pi_1}; it shares y1,…,ydy^1, \dots, y^d. For t=dt = d, the new chain starts at b−eπdb - e_{\pi_d}, adds eπde_{\pi_d} to reach bb, and then follows y1,…,yd−1y^1, \dots, y^{d-1}. In each case the new vertex differs from yty^t, so the cell is the other cell of the facet. The facet lies inside TT, and the two cells lie on its two sides. If the facet is on the boundary of TT, the other side is outside TT, so the other cell is not inside TT. If it is not on the boundary, both sides near the facet are in TT, and the other cell is a cell of the triangulation of TT. □\square

Lemma 2 (owners). The nn vertices of a cell have nn different owners.

Proof. The coordinate sums of y0,…,ydy^0, \dots, y^d are ∑b,∑b+1,…,∑b+d\sum b, \sum b + 1, \dots, \sum b + d. These are nn consecutive integers, so they are different modulo nn. □\square

Lemma 3 (prices in one cell). Within one cell, each xjx_j takes at most two values, and they differ by 1. So the price of each room varies by at most R/NR/N over the vertices of a cell.

Proof. Along the chain y0,…,ydy^0, \dots, y^d, each coordinate sks_k grows by 1 exactly once. For 1≤j≤d−11 \le j \le d - 1, xj=sj−sj−1x_j = s_j - s_{j-1} grows by 1 at the step of sjs_j and drops by 1 at the step of sj−1s_{j-1}, and is constant otherwise. So it takes two adjacent values. x0=s0x_0 = s_0 and xn−1=N−sd−1x_{n-1} = N - s_{d-1} change once each. □\square

A door is a facet whose dd vertices have the labels 0,1,…,n−20, 1, \dots, n - 2, each once. A cell is fully labeled if its nn vertices have all nn labels.

Lemma 4 (doors of a cell). A fully labeled cell has exactly one door. Any other cell has zero or two doors.

Proof. If the cell is fully labeled, the only door is the facet without the vertex labeled n−1n - 1. Otherwise, if the labels 0,…,n−20, \dots, n - 2 all appear, one of them appears twice and n−1n - 1 does not appear, and the doors are the two facets without one of the two vertices with the repeated label. If some label of 0,…,n−20, \dots, n - 2 is missing, no facet is a door. □\square

Lemma 5 (the walk). Start in the cell of TT that has a boundary door DD, as in line L2. Lines L3 to L10 visit distinct cells, and they stop either at a fully labeled cell (line L5) or when they leave TT through a boundary door other than DD (line L9).

Proof. At each visit, the facet we came through is a door; call its vertex set the entry. If the cell is not fully labeled, the vertex outside the entry has a label ℓ≤n−2\ell \le n - 2 that repeats one vertex uu of the entry, and by Lemma 4 the other door is the facet without uu. Line L8 finds uu and line L9 moves to the cell across that door, by Lemma 1. Consider the graph whose nodes are the cells of TT and one extra node "outside", with an edge for each door, joining the two cells that share it, or a cell and "outside" for a boundary door. By Lemma 4 each cell has degree at most 2, and fully labeled cells have degree 1. The walk follows this graph from "outside" without using an edge twice in a row. A walk in a graph whose inner nodes have degree at most 2 cannot return to a node it has visited before without coming through a node of degree 3 or more, so it never repeats a cell. There are finitely many cells, so it stops at a node of degree 1 or at "outside". □\square

Theorem 1 (the output is right). If the algorithm returns, then the rooms form a permutation, tenant ii chose its room rir_i at the prices of some vertex viv_i of the returned cell, and the returned prices qq are nonnegative, sum to RR, and satisfy ∣qj−pj(vi)∣≤R/N|q_j - p_j(v_i)| \le R/N for every room jj and tenant ii.

Proof. The owners of the cell are all tenants (Lemma 2) and the labels are all rooms (line L5), so line L6 gives each tenant one room and each room one tenant. The owner of viv_i is ii, and ℓ(vi)=ri\ell(v_i) = r_i is its choice at p(vi)p(v_i). qq is the average of nn price vectors, each nonnegative with sum RR. By Lemma 3, pj(v)p_j(v) lies in an interval of length R/NR/N for the vertices vv of the cell, and qjq_j is in the same interval. □\square

So if each tenant's preference changes little when prices change by R/NR/N, the result is close to envy-free. For the test tenants that pay ci(j) pjc_i(j)\, p_j in their own eyes, Theorem 1 gives ci(ri)qri−ci(j)qj≤(ci(ri)+ci(j))R/Nc_i(r_i) q_{r_i} - c_i(j) q_j \le (c_i(r_i) + c_i(j)) R/N, since ci(ri)pri(vi)≤ci(j)pj(vi)c_i(r_i) p_{r_i}(v_i) \le c_i(j) p_j(v_i).

Lemma 6 (where the boundary doors are). If all tenants are miserly and N≥nN \ge n, every boundary door lies in a cell whose base bb has all coordinates at most n−2n - 2.

Proof. A vertex on a boundary facet has a free room, so its label is a free room there. Suppose the door lies on the facet xn−1=0x_{n-1} = 0. For each label k≤n−2k \le n - 2, some vertex of the door has xk=0x_k = 0, so by Lemma 3, xk≤1x_k \le 1 at every vertex. Then N=∑jxj≤n−1<NN = \sum_j x_j \le n - 1 < N at any vertex, a contradiction. So the door lies on a facet xj=0x_j = 0 with j≤n−2j \le n - 2. For each k≤n−2k \le n - 2 with k≠jk \ne j, some vertex has xk=0x_k = 0, so xk≤1x_k \le 1 everywhere; also xj=0x_j = 0 on the door. So at each vertex of the door, sd−1=N−xn−1=∑k≤n−2xk≤n−2s_{d-1} = N - x_{n-1} = \sum_{k \le n - 2} x_k \le n - 2. The base bb is the least vertex of its cell in every coordinate, and the door has d≥1d \ge 1 vertices, so bd−1≤n−2b_{d-1} \le n - 2, and 0≤b0≤⋯≤bd−10 \le b_0 \le \dots \le b_{d-1}. □\square

So line L2 needs to search only a part of TT whose size does not depend on NN.

Theorem 2 (termination for two and three rooms). For n=2n = 2 and n=3n = 3 with miserly tenants and N≥nN \ge n, there is exactly one boundary door. So the walk from it ends at a fully labeled cell.

Proof. For n=2n = 2, a grid point is s0∈{0,…,N}s_0 \in \{0, \dots, N\} with prices proportional to (s0,N−s0)(s_0, N - s_0), a cell is an edge {a,a+1}\{a, a + 1\}, and a door is one vertex with label 0. The boundary points are s0=0s_0 = 0, where only room 0 is free, so the label is 0, and s0=Ns_0 = N, where only room 1 is free, so the label is 1. Exactly one boundary door.

For n=3n = 3, a door is an edge with labels {0,1}\{0, 1\}, and by Lemma 6 it is not on x2=0x_2 = 0. Let cc be the corner s=(0,0)s = (0, 0), with prices proportional to (0,0,N)(0, 0, N); its label is 0 or 1. On the facet x0=0x_0 = 0 (s0=0s_0 = 0), the edges are {(0,a),(0,a+1)}\{(0, a), (0, a + 1)\}. Room 0 is free there, and label 1 needs room 1 free too, so x1=a=0x_1 = a = 0 at that vertex: the only candidate is {c,(0,1)}\{c, (0, 1)\}. At (0,1)(0, 1) only room 0 is free, so its label is 0, and the edge is a door if and only if ℓ(c)=1\ell(c) = 1. On the facet x1=0x_1 = 0 (s0=s1s_0 = s_1), the edges are {(a,a),(a+1,a+1)}\{(a, a), (a + 1, a + 1)\}; label 0 needs x0=a=0x_0 = a = 0, so the only candidate is {c,(1,1)}\{c, (1, 1)\}. At (1,1)(1, 1) only room 1 is free, so its label is 1, and the edge is a door if and only if ℓ(c)=0\ell(c) = 0. Exactly one of the two holds. Both edges lie in the cell with base (0,0)(0, 0) that first raises s1s_1 and then s0s_0, with the vertices (0,0),(0,1),(1,1)(0, 0), (0, 1), (1, 1), which is inside TT, and by Lemma 1 the cells across them are outside TT. By Lemma 5, the walk from the only boundary door cannot leave through another boundary door, so it ends at a fully labeled cell. □\square

For four or more rooms. The graph of Lemma 5 shows that the number of fully labeled cells has the same parity as the number of boundary doors, because every path in it has two ends. If the number of boundary doors is odd, some walk from a boundary door does not end at another boundary door, so it ends at a fully labeled cell, and line L2 tries every boundary door. We do not prove here that the number is odd for n≥4n \ge 4, and this is why the proof is marked partial. Su (1999, Section 7) proves that a fully labeled cell exists for a barycentric subdivision, with a dual form of Sperner's lemma that he credits to Scarf, and he notes that other triangulations can be used. The implementation raises an error if no walk succeeds. In the tests, which count the boundary doors by brute force for four rooms, the number is always odd.

Complexity

The region has Nn−1N^{n-1} cells, and the walk visits each at most once. Each step costs O(n2)O(n^2) operations to build a cell and to compare labels, so the walk costs O(n2Nn−1)O(n^2 N^{n-1}) in the worst case, in the real-RAM sense with one unit per question to a tenant. The search for boundary doors in line L2 looks at fewer than 4n4^n base points, (n−1)!(n - 1)! cells for each, and nn faces for each cell, so it costs O(4nn!n2)O(4^n n! n^2), with no dependence on NN.

The number of questions is at most the number of grid points, (N+n−1n−1)\binom{N + n - 1}{n - 1}, and usually far less, because only the points near the walk are asked. For a fixed number of tenants, halving the price step R/NR/N can multiply the worst case by 2n−12^{n-1}. Path following of this kind can take exponentially many steps in general; finding a fully labeled cell of a Sperner labeling given by a circuit is complete for the class PPAD.

Properties

  • Interactive. It asks one tenant one question at a time and needs no utility numbers, only choices.
  • Approximate. The price error is at most R/NR/N per room; it is not exactly envy-free in general.
  • Deterministic and simple to state. Each step changes one vertex and asks at most one new question.
  • Owners, not tenants, label the cells. Each tenant answers only at the points it owns.

Variants and improvements

  • Barycentric subdivision. Su describes the labeling on an iterated barycentric subdivision of the price simplex and notes that other triangulations, with better convergence, can be used. The implementation uses the Freudenthal triangulation, whose cells are easy to step through.
  • The weaker miserly condition. Su shows that it is enough that a tenant never picks the most expensive room when some room is free.
  • Cake and chores. The same trap-door walk with owner labels finds an approximately envy-free division of a cake into intervals, and, by treating rent as a burden, an approximately envy-free chore division.
  • Exact rent division with money. If each tenant has a value for each room and its utility is value minus price, an exactly envy-free division can be found in polynomial time by a matching and a linear program. The rental harmony page describes this model.

When to use it

Use it when the tenants can answer only "which room would you take at these prices?", when their preferences need not be quasi-linear, and when an error of a small amount of rent per room is acceptable. With quasi-linear values, solve the problem exactly with a matching and a linear program instead.

Pitfalls

  • Tenants who are not miserly. If a tenant picks a room with a positive price when another room is free, there can be no boundary door near the expensive corner, and the walk may not start or may fail.
  • A grid that is too coarse. The guarantee is only within R/NR/N; with a small NN the answer can leave real envy.
  • Asking the wrong tenant. Each point must be asked of its owner. Asking every tenant at every point is a different, slower method.
  • Reusing answers after preferences change. The walk relies on fixed answers, so cache them per point and do not ask again.

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.

su_rental_harmony_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/su-rental-harmony-algorithm/. The authors are listed in prov/QR1JRG.jsonl.

"""Su's path-following algorithm for rental harmony.

There are n rooms and n tenants, both numbered 0 to n - 1, and a total rent
R. The price simplex {p >= 0, sum p = R} is cut by a grid of size N into
small simplices (cells). A point of the grid is stored by its partial sums
s = (s_0, ..., s_{n-2}) with 0 <= s_0 <= ... <= s_{n-2} <= N; the room
prices are R x / N with x_0 = s_0, x_j = s_j - s_{j-1} and
x_{n-1} = N - s_{n-2}. The cells are the Freudenthal (Kuhn) simplices: a
cell (b, pi) has the vertices b, b + e_pi[0], b + e_pi[0] + e_pi[1], ...

Each grid point has an owner, the tenant sum(s) mod n; the n vertices of a
cell have n different owners. The label of a grid point is the room that its
owner chooses at its prices. A cell with all n labels gives the assignment.
"""

from fractions import Fraction
from itertools import permutations, product
from typing import Callable, Sequence

Point = tuple[int, ...]
Cell = tuple[Point, tuple[int, ...]]
Chooser = Callable[[int, list[Fraction]], int]


def prices(s: Point, n: int, rent: Fraction, grid: int) -> list[Fraction]:
    x = [s[0]] + [s[j] - s[j - 1] for j in range(1, n - 1)] + [grid - s[-1]]
    return [Fraction(rent) * xj / grid for xj in x]


def owner(s: Point, n: int) -> int:
    return sum(s) % n


def vertices(cell: Cell) -> list[Point]:
    b, pi = cell
    out = [b]
    cur = list(b)
    for j in pi:
        cur[j] += 1
        out.append(tuple(cur))
    return out


def in_region(s: Point, grid: int) -> bool:
    if s[0] < 0 or s[-1] > grid:
        return False
    return all(s[j - 1] <= s[j] for j in range(1, len(s)))


def cell_in_region(cell: Cell, grid: int) -> bool:
    return all(in_region(v, grid) for v in vertices(cell))


def pivot(cell: Cell, t: int) -> tuple[Cell, int]:
    """The cell across the facet without vertex t, and the index of its new vertex."""
    b, pi = cell
    d = len(pi)
    if 0 < t < d:
        q = list(pi)
        q[t - 1], q[t] = q[t], q[t - 1]
        return (b, tuple(q)), t
    if t == 0:
        nb = list(b)
        nb[pi[0]] += 1
        return (tuple(nb), pi[1:] + pi[:1]), d
    nb = list(b)
    nb[pi[-1]] -= 1
    return (tuple(nb), pi[-1:] + pi[:-1]), 0


class Labeler:
    """Ask each owner its choice at most once per grid point, and count the questions."""

    def __init__(self, n: int, rent, grid: int, choose: Chooser) -> None:
        self.n, self.rent, self.grid, self.choose = n, Fraction(rent), grid, choose
        self.cache: dict[Point, int] = {}

    def __call__(self, s: Point) -> int:
        if s not in self.cache:
            p = prices(s, self.n, self.rent, self.grid)
            room = self.choose(owner(s, self.n), p)
            if not 0 <= room < self.n:
                raise ValueError("a tenant must choose a room 0 to n - 1")
            self.cache[s] = room
        return self.cache[s]

    @property
    def questions(self) -> int:
        return len(self.cache)


def boundary_doors(n: int, grid: int, label: Labeler) -> list[tuple[Cell, int]]:
    """The doors on the boundary, as (cell, index of the vertex not in the door).

    A door is a facet whose labels are exactly 0 to n - 2. With miserly
    tenants and grid >= n, every boundary door lies in a cell whose base has
    all coordinates at most n - 2, near the corner where room n - 1 costs R.
    """
    d = n - 1
    want = set(range(n - 1))
    found = []
    top = min(n - 2, grid)
    for b in product(range(top + 1), repeat=d):
        if not in_region(b, grid):
            continue
        for pi in permutations(range(d)):
            cell = (b, pi)
            if not cell_in_region(cell, grid):
                continue
            vs = vertices(cell)
            for t in range(n):
                labs = [label(v) for k, v in enumerate(vs) if k != t]
                if set(labs) != want:
                    continue
                if not cell_in_region(pivot(cell, t)[0], grid):
                    found.append((cell, t))
    return found


def su_rental_harmony(n: int, rent, grid: int, choose: Chooser):
    """Return (rooms, price, questions, steps).

    rooms[i] is the room of tenant i, price is the average of the vertex prices
    of the fully labeled cell (it sums to the rent), questions is the number of
    grid points asked, and steps is the number of cells visited.
    """
    if n < 2 or grid < n:
        raise ValueError("su_rental_harmony needs n >= 2 and grid >= n")
    label = Labeler(n, rent, grid, choose)  # @line L1
    steps = 0
    for cell, new in boundary_doors(n, grid, label):  # @line L2
        while True:  # @line L3
            steps += 1
            vs = vertices(cell)  # @line L4
            labs = [label(v) for v in vs]
            if len(set(labs)) == n:  # @line L5
                rooms = [0] * n
                for v, r in zip(vs, labs):
                    rooms[owner(v, n)] = r  # @line L6
                ps = [prices(v, n, label.rent, grid) for v in vs]
                price = [sum(p[j] for p in ps) / n for j in range(n)]  # @line L7
                return rooms, price, label.questions, steps
            u = next(k for k in range(n) if k != new and labs[k] == labs[new])  # @line L8
            nxt, nnew = pivot(cell, u)  # @line L9
            if not cell_in_region(nxt, grid):
                break  # the path left through another boundary door
            cell, new = nxt, nnew  # @line L10
    raise RuntimeError("no fully labeled cell found; are the tenants miserly?")


def fully_labeled_cells(n: int, rent, grid: int, choose: Chooser) -> list[Cell]:
    """Brute force: every cell of the region with all n labels (for tests)."""
    label = Labeler(n, rent, grid, choose)
    d = n - 1
    out = []
    for b in product(range(grid + 1), repeat=d):
        if not in_region(b, grid):
            continue
        for pi in permutations(range(d)):
            cell = (b, pi)
            if cell_in_region(cell, grid) and len({label(v) for v in vertices(cell)}) == n:
                out.append(cell)
    return out


def count_cells(n: int, grid: int) -> int:
    d = n - 1
    return sum(
        1
        for b in product(range(grid + 1), repeat=d)
        if in_region(b, grid)
        for pi in permutations(range(d))
        if cell_in_region((b, pi), grid)
    )


def envy(costs: Sequence[Sequence[int]], rooms: list[int], price: list[Fraction]) -> Fraction:
    """For the test tenants who pay costs[i][j] * p_j, the largest extra cost of a tenant."""
    worst = Fraction(0)
    for i, r in enumerate(rooms):
        mine = costs[i][r] * price[r]
        for j in range(len(rooms)):
            worst = max(worst, mine - costs[i][j] * price[j])
    return worst
test_su_rental_harmony_algorithm.py 160 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/su-rental-harmony-algorithm/. The authors are listed in prov/QR1JRG.jsonl.

import random
from fractions import Fraction
from itertools import permutations, product
from math import comb

import pytest

from su_rental_harmony_algorithm import (
    Labeler,
    boundary_doors,
    cell_in_region,
    count_cells,
    envy,
    fully_labeled_cells,
    owner,
    pivot,
    prices,
    su_rental_harmony,
    vertices,
)

F = Fraction


def cost_chooser(costs):
    """Tenant i pays costs[i][j] * p_j in its own eyes and picks the least (ties: smallest room).

    A free room costs 0, so the tenants are miserly, and the choice is a
    continuous preference.
    """

    def choose(i, p):
        return min(range(len(p)), key=lambda j: (costs[i][j] * p[j], j))

    return choose


def value_chooser(vals):
    """Miserly by rule: a free room if there is one, else the best value minus price."""

    def choose(i, p):
        free = [j for j in range(len(p)) if p[j] == 0]
        if free:
            return max(free, key=lambda j: (vals[i][j], -j))
        return max(range(len(p)), key=lambda j: (vals[i][j] - p[j], -j))

    return choose


def check_output(n, rent, grid, choose, rooms, price, questions):
    assert sorted(rooms) == list(range(n))
    assert all(x >= 0 for x in price) and sum(price) == rent
    assert questions <= comb(grid + n - 1, n - 1)


def test_page_example() -> None:
    w = [[2, 1, 1], [1, 2, 1], [1, 1, 1]]
    costs = [[F(1, x) for x in row] for row in w]
    choose = cost_chooser(costs)
    rooms, price, questions, steps = su_rental_harmony(3, F(900), 6, choose)
    assert rooms == [0, 1, 2]
    assert price == [400, 250, 250]
    assert (questions, steps) == (11, 8)
    assert envy(costs, rooms, price) == 0
    assert len(boundary_doors(3, 6, Labeler(3, 900, 6, choose))) == 1
    assert count_cells(3, 6) == 36


def test_envy_bound_on_cost_tenants() -> None:
    rng = random.Random(17)
    for n, grid in [(2, 2), (2, 9), (3, 3), (3, 10), (4, 4), (4, 9)]:
        for _ in range(6):
            costs = [[rng.randint(1, 5) for _ in range(n)] for _ in range(n)]
            rent = F(rng.randint(1, 1000))
            choose = cost_chooser(costs)
            rooms, price, questions, steps = su_rental_harmony(n, rent, grid, choose)
            check_output(n, rent, grid, choose, rooms, price, questions)
            # vertex prices of one cell differ by at most rent / grid per room
            for i, r in enumerate(rooms):
                for j in range(n):
                    extra = costs[i][r] * price[r] - costs[i][j] * price[j]
                    assert extra <= (costs[i][r] + costs[i][j]) * rent / grid


def test_cell_is_fully_labeled_and_count_is_odd() -> None:
    rng = random.Random(4)
    for n, grid in [(2, 7), (3, 6), (3, 8), (4, 5)]:
        for trial in range(5):
            if trial % 2:
                vals = [[rng.randint(0, 9) for _ in range(n)] for _ in range(n)]
                choose = value_chooser(vals)
            else:
                choose = cost_chooser([[rng.randint(1, 4) for _ in range(n)] for _ in range(n)])
            rooms, price, questions, steps = su_rental_harmony(n, 60, grid, choose)
            check_output(n, 60, grid, choose, rooms, price, questions)
            cells = fully_labeled_cells(n, 60, grid, choose)
            assert len(cells) % 2 == 1
            assert steps <= count_cells(n, grid)
            # the answer comes from one of the brute force cells: the owner of
            # each vertex chose the room it is given
            ok = False
            for cell in cells:
                vs = vertices(cell)
                if all(choose(owner(v, n), prices(v, n, F(60), grid)) == rooms[owner(v, n)] for v in vs):
                    ok = True
            assert ok


def all_boundary_doors(n, grid, label):
    """Brute force over every cell of the region and every facet."""
    found = set()
    for b in product(range(grid + 1), repeat=n - 1):
        for pi in permutations(range(n - 1)):
            cell = (b, pi)
            if not cell_in_region(cell, grid):
                continue
            vs = vertices(cell)
            for t in range(n):
                facet = frozenset(v for k, v in enumerate(vs) if k != t)
                if {label(v) for v in facet} == set(range(n - 1)) and not cell_in_region(pivot(cell, t)[0], grid):
                    found.add(facet)
    return found


def test_boundary_doors_against_brute_force() -> None:
    rng = random.Random(9)
    for n, grid in [(2, 5), (3, 3), (3, 5), (3, 8), (4, 4), (4, 6)]:
        for _ in range(6):
            choose = cost_chooser([[rng.randint(1, 6) for _ in range(n)] for _ in range(n)])
            label = Labeler(n, 1, grid, choose)
            near = {
                frozenset(v for k, v in enumerate(vertices(cell)) if k != t)
                for cell, t in boundary_doors(n, grid, label)
            }
            every = all_boundary_doors(n, grid, label)
            assert near == every
            assert len(every) % 2 == 1
            if n <= 3:
                assert len(every) == 1


def test_owners_distinct_in_each_cell() -> None:
    for n, grid in [(3, 4), (4, 4)]:
        for b in product(range(grid + 1), repeat=n - 1):
            for pi in permutations(range(n - 1)):
                assert len({owner(v, n) for v in vertices((b, pi))}) == n


def test_cell_count_is_grid_power() -> None:
    assert count_cells(2, 7) == 7
    assert count_cells(3, 5) == 25
    assert count_cells(4, 4) == 64


def test_rejects_small_grid() -> None:
    with pytest.raises(ValueError):
        su_rental_harmony(3, 10, 2, cost_chooser([[1] * 3] * 3))

History

Forest Simmons used Sperner's lemma with owner labels for cake cutting. He presented the idea to math clubs and school groups and told it to Michael Starbird in 1980, but he never published it. Francis Edward Su published the method in 1999 in the American Mathematical Monthly. He adapted it to rent division, where a twist is needed because the room labels are not a Sperner labeling, and to chore division. He described the trap-door algorithm and invited readers to code it.

References

  1. Francis Edward Su, Rental harmony: Sperner's lemma in fair division, American Mathematical Monthly 106(10) (1999), 930-942, Sections 3 to 5 (owner labels and the trap-door algorithm for cake), Section 7 (rental harmony and the dual Sperner lemma), Section 8 (the weaker miserly condition)
  2. Harold W. Kuhn, Simplicial approximation of fixed points, Proceedings of the National Academy of Sciences of the USA 61 (1968), the triangulation of the simplex by the cells of a cube grid
  3. Michael J. Todd, The Computation of Fixed Points and Applications, Lecture Notes in Economics and Mathematical Systems, Springer, 1976, triangulations and path following for fixed points, as Su cites it for other triangulations

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 correctness
  • 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