Algorithm Search⌘K

Algorithmintro

Instant-runoff voting

Also called IRV, alternative vote, ranked-choice voting.

Repeatedly eliminates the candidate with the fewest first places and transfers its ballots until one candidate has a majority.

Time
O(L + m^2) worst
Space
O(n + m) extra
Where
L = the total length of the ballots; m = the number of candidates; n = the number of voters
Properties
not comparison baseddeterministiciterative
Origin
Thomas Hare, William Robert Ware, 1871

Instant-runoff voting (IRV) is a single-winner voting rule on ranked ballots that eliminates candidates one at a time. In each round every ballot counts for its highest-ranked candidate that is still in the race; if one candidate has more than half of these ballots it wins, and otherwise the candidate with the fewest ballots is eliminated and its ballots move to their next choices. It is the single-winner case of the single transferable vote, and it is called the alternative vote in the United Kingdom and ranked-choice voting in the United States. It fixes the vote splitting of plurality voting in many cases, but it is not monotone and it can eliminate the Condorcet winner.

In plain words

Each voter ranks the candidates from best to worst. First count only the top choices. If someone has more than half, that candidate wins. If not, drop the candidate with the fewest votes, and give each of its ballots to the next candidate on that ballot who is still in the race. Count again, and repeat until someone has more than half of the ballots that still count. It works like a series of runoff elections, but the voters vote only once.

The problem

There are mm candidates A={0,…,m−1}A = \{0, \ldots, m - 1\} and nn voters. Voter ii gives a ballot rir_i, a sequence of distinct candidates, best first. A full ranking lists all mm candidates; a truncated ballot lists fewer, and it is exhausted when none of its candidates is still in the race. The input is the preference profile P=(r1,…,rn)P = (r_1, \ldots, r_n) and the output is one winner.

For a set CC of continuing candidates, a ballot counts for its first entry in CC. Write tC(a)t_C(a) for the number of ballots that count for aa, and TC=∑a∈CtC(a)T_C = \sum_{a \in C} t_C(a) for the number of ballots that are not exhausted. The rule starts with C=AC = A. If some a∈Ca \in C has 2tC(a)>TC2 t_C(a) > T_C, or C={a}C = \{a\}, it returns aa. Otherwise it removes from CC the candidate with the smallest tCt_C. Among tied candidates it removes the one with the largest index, so that the smallest index wins a final tie, as on the other rule pages of this area.

The algorithm

The direct method recounts every ballot in each round. The method below keeps, for each candidate, the pile of ballots that count for it, and a pointer into each ballot. When a candidate is eliminated, only the ballots on its pile move, and each pointer only moves forward.

  1. INSTANT-RUNOFF(P, m) ▷ P = (r_1, ..., r_n), each ballot best first
  2. 1C ← {0, ..., m - 1}; ptr[i] ← 1 for each voter i
  3. 2put each nonempty ballot i on pile[r_i[1]]
  4. 3loop
  5. 4T ← the sum of |pile[a]| over a in C ▷ ballots that are not exhausted
  6. 5if some a in C has 2 |pile[a]| > T, or C = {a} then
  7. 6return a
  8. 7x ← the a in C with the smallest |pile[a]|; the largest index among ties
  9. 8C ← C \ {x}
  10. 9for each ballot i on pile[x] do
  11. 10advance ptr[i] to the next entry of r_i that is in C
  12. 11if ptr[i] is within r_i then put i on pile[r_i[ptr[i]]], else i is exhausted

Lines L1 and L2 do the first count. Each pass of the loop is one round: lines L4 to L6 test for a winner, lines L7 and L8 eliminate the weakest candidate, and lines L9 to L11 transfer its ballots. The code also returns the counts of every round, which is how results are usually published.

Example

Take the nine voters of the plurality voting page:

voters ranking
4 a≻b≻ca \succ b \succ c
3 b≻c≻ab \succ c \succ a
2 c≻b≻ac \succ b \succ a
round aa bb cc TT action
1 4 3 2 9 no one has 5 or more; eliminate cc, its 2 ballots go to bb
2 4 5 out 9 bb has 5 of 9 and wins

Plurality elects aa here, which loses to both other candidates in pairs. IRV elects bb, the Condorcet winner, because the cc-voters' second choice now counts.

IRV can still miss the Condorcet winner. With 2 voters a≻b≻ca \succ b \succ c, 1 voter b≻a≻cb \succ a \succ c and 2 voters c≻b≻ac \succ b \succ a, the moderate bb beats aa by 3 to 2 and cc by 3 to 2, but it has the fewest first places. Round 1 has counts (2,1,2)(2, 1, 2) and eliminates bb, and aa then wins by 3 to 2. This is the center squeeze.

Two more failures, both with no tie for last place in any round, show that more support can hurt a candidate:

  • Not monotone. With 6 voters a≻b≻ca \succ b \succ c, 2 voters b≻a≻cb \succ a \succ c, 4 voters b≻c≻ab \succ c \succ a and 5 voters c≻a≻bc \succ a \succ b, the first counts are (6,6,5)(6, 6, 5), cc is eliminated, and aa wins by 11 to 6. If the 2 voters b≻a≻cb \succ a \succ c move aa to the top, the counts are (8,4,5)(8, 4, 5), now bb is eliminated, its 4 ballots go to cc, and cc wins by 9 to 8. The winner lost by gaining votes.
  • No-show paradox. With 2 voters a≻c≻ba \succ c \succ b, 4 voters b≻c≻ab \succ c \succ a and 3 voters c≻b≻ac \succ b \succ a, aa is eliminated first and cc wins by 5 to 4. If 2 more voters a≻c≻ba \succ c \succ b come to vote, the counts are (4,4,3)(4, 4, 3), cc is eliminated, and bb wins by 7 to 4. The two new voters prefer cc to bb, so they would do better to stay at home.

Correctness

The method computes the rule of the problem section. The proof in proofs/correctness.md shows two invariants at line L4: the continuing set CC is the same as in the direct method, and for each a∈Ca \in C, pile[a]pile[a] holds exactly the ballots that count for aa, so ∣pile[a]∣=tC(a)|pile[a]| = t_C(a) and T=TCT = T_C. The second invariant holds because a ballot counts for aa exactly when its pointer is at aa; eliminating xx changes the count of a ballot only if that ballot was on pile[x]pile[x], and line L10 moves its pointer to the next entry in CC.

The proof also shows that stopping at a majority in line L5 does not change the winner. If 2tC(a)>TC2 t_C(a) > T_C, every other candidate in CC has fewer ballots than aa, so aa is never the one eliminated, and tC(a)t_C(a) never goes down as CC shrinks. Eliminating to the end would also elect aa. The tests check the method against the direct recount, against elimination to the end, and on truncated ballots.

Proof: Correctness and properties of instant-runoff votingfull

Let A={0,…,m−1}A = \{0, \ldots, m - 1\} with m≥1m \ge 1, and let P=(r1,…,rn)P = (r_1, \ldots, r_n) be ballots, each a sequence of distinct candidates, best first. For C⊆AC \subseteq A, ballot ii counts for the first entry of rir_i that is in CC, if there is one. Let tC(a)t_C(a) be the number of ballots that count for aa and TC=∑a∈CtC(a)T_C = \sum_{a \in C} t_C(a).

The direct rule starts with C=AC = A and repeats: if some a∈Ca \in C has 2tC(a)>TC2 t_C(a) > T_C, or C={a}C = \{a\}, return aa; else remove from CC the element xx with the smallest tC(x)t_C(x), the largest index among ties. Call the sequence of sets it visits C0=A⊋C1⊋⋯C_0 = A \supsetneq C_1 \supsetneq \cdots.

Claim 1 (invariant). At the start of the kk-th pass of line L4, the set CC of the method is CkC_k, and for every a∈Ca \in C, pile[a]pile[a] is the set of ballots that count for aa with respect to CC. For every ballot ii on pile[a]pile[a], ri[ptr[i]]=ar_i[ptr[i]] = a, and every entry of rir_i before position ptr[i]ptr[i] is outside CC.

Proof. By induction on kk. For k=0k = 0, C=AC = A, every nonempty ballot counts for its first entry, and line L2 puts it on that pile with ptr[i]=1ptr[i] = 1. Empty ballots count for nobody and are on no pile.

Assume the claim at pass kk and that the method does not return. Then ∣pile[a]∣=tCk(a)|pile[a]| = t_{C_k}(a), so line L7 picks the same xx as the direct rule, and line L8 makes C=Ck∖{x}=Ck+1C = C_k \setminus \{x\} = C_{k+1}. Take a ballot ii. If it counted for some a≠xa \ne x, all its entries before aa are outside CkC_k, hence outside Ck+1C_{k+1}, and a∈Ck+1a \in C_{k+1}, so it still counts for aa; the method does not touch it. If it counted for xx, it is on pile[x]pile[x], and line L10 moves ptr[i]ptr[i] to the first later entry in Ck+1C_{k+1}; all entries before it are outside Ck+1C_{k+1} (the ones before xx by the hypothesis, xx itself, and the skipped ones by line L10). So the ballot now counts for ri[ptr[i]]r_i[ptr[i]], and line L11 puts it on that pile, or it is exhausted and counts for nobody. If it counted for nobody, it still counts for nobody. Clearing pile[x]pile[x] completes the step.

Claim 2 (correctness). The method returns the winner of the direct rule.

Proof. By Claim 1, in each pass line L4 computes T=TCkT = T_{C_k} and line L5 tests the same condition as the direct rule. If it holds, both return the same aa. Otherwise both remove the same xx. Each pass removes one candidate, so after at most m−1m - 1 passes ∣C∣=1|C| = 1 and the method returns.

Claim 3 (early stop). If 2tC(a)>TC2 t_C(a) > T_C for some a∈Ca \in C, then eliminating until one candidate is left, by the same elimination rule, also elects aa.

Proof. While aa is in CC and ∣C∣≥2|C| \ge 2, every b∈C∖{a}b \in C \setminus \{a\} has tC(b)≤TC−tC(a)<tC(a)t_C(b) \le T_C - t_C(a) < t_C(a), so aa is not the candidate of smallest count and is not removed. Removing another candidate does not decrease tC(a)t_C(a), since a ballot that counts for aa still counts for aa, and it does not increase TCT_C, since a ballot can only become exhausted. So the condition 2tC(a)>TC2 t_C(a) > T_C holds in every later round, and aa is the last candidate left.

Claim 4 (majority criterion). If more than n/2n/2 ballots have aa first, the rule returns aa in round 1.

Proof. tA(a)>n/2≥TA/2t_A(a) > n/2 \ge T_A/2, and no other candidate can also have more than half.

Claim 5 (Condorcet loser criterion). Assume full rankings. If ℓ\ell loses to every other candidate in pairs, that is nP(ℓ,b)<nP(b,ℓ)n_P(\ell, b) < n_P(b, \ell) for all b≠ℓb \ne \ell, where nP(x,y)n_P(x, y) is the number of voters who rank xx above yy, then the rule does not return ℓ\ell (for m≥2m \ge 2).

Proof. With full rankings no ballot is exhausted, so TC=nT_C = n. If the rule returns ℓ\ell at a round with ∣C∣≥3|C| \ge 3 or by a strict majority, then tC(ℓ)>n/2t_C(\ell) > n/2; every ballot that counts for ℓ\ell ranks ℓ\ell above every other member of CC, so for any b∈C∖{ℓ}b \in C \setminus \{\ell\}, nP(ℓ,b)>n/2n_P(\ell, b) > n/2, a contradiction. Otherwise ℓ\ell can only be returned when C={ℓ}C = \{\ell\}, so the rule must pass through a round with C={ℓ,b}C = \{\ell, b\} for some bb. In that round each ballot counts for the one of ℓ,b\ell, b that it ranks higher, so tC(ℓ)=nP(ℓ,b)<nP(b,ℓ)=tC(b)t_C(\ell) = n_P(\ell, b) < n_P(b, \ell) = t_C(b). The two counts add up to nn, so bb has a strict majority and is returned. In no case is ℓ\ell returned.

Claim 6 (Pareto). Assume full rankings and n≥1n \ge 1. If every voter ranks aa above bb, the rule does not return bb.

Proof. While a∈Ca \in C, no ballot counts for bb, because aa comes before bb on every ballot. Suppose aa is removed in some round while bb is in CC. Then tC(a)≤tC(b)=0t_C(a) \le t_C(b) = 0, so aa had no ballots and its removal moves none: t(b)t(b) stays 0. From then on, as long as bb is in CC, the smallest count in CC is 0, so every removed candidate has count 0 and moves no ballots, and t(b)t(b) stays 0. Since TC=n≥1T_C = n \ge 1, some candidate in CC has a positive count, so bb never has a majority, and C={b}C = \{b\} would need all candidates with ballots to be removed, which never happens while bb, with count 0, is still in. Hence bb is removed before the end, and it is not returned.

Claim 7 (anonymity). The winner does not depend on the order of the ballots.

Proof. Every quantity that the direct rule uses, tCt_C and TCT_C, counts ballots and does not depend on their order.

Claim 8 (two candidates). If m=2m = 2 and the ballots are full rankings, the rule returns 0 exactly when 2nP(0,1)≥n2 n_P(0, 1) \ge n.

Proof. In round 1, t(0)=nP(0,1)t(0) = n_P(0, 1) and t(1)=n−t(0)t(1) = n - t(0). If 2t(0)>n2 t(0) > n the rule returns 0, and if 2t(1)>n2 t(1) > n it returns 1. If t(0)=t(1)t(0) = t(1), neither has a majority, the tie rule removes 1, and the rule returns 0.

Claim 9 (time). The method runs in O(L+m2)O(L + m^2) time with L=∑i∣ri∣L = \sum_i |r_i|, plus O(n+m)O(n + m) for the setup, and in O(n+m)O(n + m) extra space.

Proof. Lines L1 and L2 take O(n+m)O(n + m) time. Each round removes one candidate, so there are at most mm rounds, and lines L4 to L8 cost O(m)O(m) per round. In lines L9 to L11 each unit of work moves a pointer forward by one entry, and the pointer of ballot ii never passes the end of rir_i, so the total over all rounds is O(n+L)O(n + L). A ballot is on at most one pile at a time, so the piles use O(n+m)O(n + m) space, and the pointers use O(n)O(n). ■\blacksquare

Complexity

Lines L1 and L2 take O(n+m)O(n + m) time. There are at most mm rounds, and lines L4 to L8 take O(m)O(m) time per round, so O(m2)O(m^2) in total. In lines L9 to L11, every step of a pointer moves it forward in its ballot, and a ballot moves to a new pile only after such a step, so all transfers of the whole count take O(n+L)O(n + L) time, where L=∑i∣ri∣≤nmL = \sum_i |r_i| \le n m. The total is O(L+m2)O(L + m^2), which is O(nm+m2)O(n m + m^2) for full rankings, linear in the input when n≥mn \ge m. The extra space is the nn pointers and the piles, which together hold each ballot once: O(n+m)O(n + m). The direct recount costs O(nm)O(n m) per round and O(nm2)O(n m^2) in total.

Properties

The tests check each claim by brute force over all profiles of full rankings with 3 candidates and up to 5 voters, or 4 candidates and up to 3 voters, and find the counterexamples by search. The proofs of the positive claims are in proofs/correctness.md.

  • Anonymous. The order of the voters does not matter.
  • Neutral, as a correspondence. The set of candidates that win under some way of breaking elimination ties (parallel-universe tie-breaking) is renamed with the candidates. The resolute rule is not neutral, because of the tie-break by index.
  • Majority criterion. A candidate ranked first by more than half of the voters wins in round 1.
  • Condorcet loser criterion. With full rankings, IRV never elects a candidate that loses to every other candidate in pairs. In the last round only two candidates remain, so their counts are their pairwise counts, and an early stop needs a majority of first places.
  • Pareto. With full rankings, a candidate bb that every voter ranks below some aa has no ballots while aa is in the race, and is eliminated before any candidate with ballots.
  • Not Condorcet consistent. The center squeeze above is a counterexample.
  • Not monotone. With 3 candidates, the smallest failure by one voter raising the winner one place has 7 voters and goes through a tie. Doron and Kronick (1977) described this failure for the single transferable vote.
  • Not participation-safe. The no-show example above is a counterexample.
  • Manipulable, but hard to manipulate. The search finds a profile with 3 candidates and 3 voters where one voter gains by a false ranking, as the Gibbard-Satterthwaite theorem predicts. Bartholdi and Orlin (1991) proved that it is NP-complete to decide whether a voter can make a given candidate win, so the voting manipulation problem for IRV has no known polynomial-time algorithm.
  • Majority rule for 2 candidates. With m=2m = 2 the rule elects the majority winner, ties to candidate 0.

Variants and improvements

  • Two-round system. Eliminate all candidates except the top two at once, and hold a second election. It needs a second trip to the polls, and the voters can change their minds.
  • Contingent vote and supplementary vote. One count, then all but the top two are eliminated and their ballots transferred. The supplementary vote limits each ballot to two choices.
  • Batch elimination. Eliminate at once all candidates whose combined count is below the count of the next candidate. None of them can win, so the winner does not change, and the count is shorter.
  • Coombs' method. Eliminate the candidate ranked last by the most voters, not the one with the fewest first places.
  • Baldwin's and Nanson's methods. Eliminate by the Borda count: the candidate with the lowest score, or all candidates below the average. Both are Condorcet consistent.
  • Single transferable vote. For kk seats, a candidate is elected when it reaches a quota, and its surplus ballots are transferred too. See single transferable vote.

When to use it

Use IRV for a single-winner election with ranked ballots when you want the winner to have a majority of the ballots that still count in the last round, and you want to avoid a second trip to the polls. It removes most spoiler effects of plurality voting when one or two minor candidates are far behind. If the main concern is to elect the candidate that beats every other in pairs, use a Condorcet method such as the Copeland method or ranked pairs. If ballots must be simple, consider approval voting.

Pitfalls

  • Majority of what. With truncated ballots, "more than half" can mean half of all ballots or half of the ballots that are not exhausted. When ballots are exhausted, the first rule can find no majority and must go on to the last two candidates, while the second rule stops earlier. If the first rule then eliminates to the end, the two rules elect the same candidate, but the published rounds differ. This page uses the continuing ballots; state which rule you use.
  • The elimination tie rule. A tie for last place decides who is eliminated and can decide the winner. Laws often use earlier rounds or a lot. Fix the rule and test it; a scan that keeps the first minimum and one that keeps the last minimum can give different winners on the same profile.
  • Recounting from scratch. Recounting all ballots in each round costs O(nm2)O(n m^2). With piles and pointers the work is O(nm+m2)O(n m + m^2).
  • Skipping eliminated candidates once. When a ballot moves, its next choice may already be eliminated. Line L10 must skip every eliminated candidate, not just one.
  • The name ranked-choice voting. In the United States it means IRV, but it is also used for the single transferable vote and for any rule on ranked ballots. Say which rule you mean.

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.

agtprefs.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the algorithmic game theory pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Preference profiles, majority relations and brute force axiom checkers.

The candidates are 0, ..., m - 1. A ranking is a tuple of all m candidates, best first:
(2, 0, 1) means that 2 is preferred to 0 and 0 to 1. A profile is a tuple of n rankings,
one per voter. An approval ballot is a frozenset of candidates, and an approval profile is
a tuple of n ballots.

A rule is a function rule(profile, m). A resolute rule returns one candidate (an int); a
correspondence returns a nonempty frozenset of candidates. The checkers accept both: they
turn an int w into frozenset({w}).

Each checker takes the rule, m and n, and by default tries every profile of all_profiles(m,
n). Pass profiles= to check a given list of profiles instead (for example approval profiles,
or a random sample when the full domain is too large). Each checker returns None when the
property holds on every profile it tried, and else a counterexample tuple.

There is no voting rule in this module. Every count is an exact integer.
"""

from itertools import permutations, product


# ---------------------------------------------------------------- rankings and profiles


def all_rankings(m):
    """Return the list of the m! rankings of 0, ..., m - 1, in lexicographic order."""
    return list(permutations(range(m)))


def all_profiles(m, n):
    """Yield every profile of n rankings of m candidates: (m!)^n profiles, voters ordered."""
    return product(all_rankings(m), repeat=n)


def random_profile(rng, m, n):
    """Return a profile of n rankings drawn uniformly and independently (impartial culture)."""
    return tuple(tuple(rng.sample(range(m), m)) for _ in range(n))


def position(r, a):
    """Return the position of candidate a in ranking r: 0 for the top."""
    return r.index(a)


def prefers(r, a, b):
    """Return True if ranking r puts a above b."""
    return r.index(a) < r.index(b)


def pairwise(profile, m):
    """Return the m by m matrix N with N[a][b] the number of voters who rank a above b."""
    N = [[0] * m for _ in range(m)]
    for r in profile:
        for i, a in enumerate(r):
            for b in r[i + 1:]:
                N[a][b] += 1
    return N


def margins(profile, m):
    """Return the m by m matrix of margins N[a][b] - N[b][a]."""
    N = pairwise(profile, m)
    return [[N[a][b] - N[b][a] for b in range(m)] for a in range(m)]


def condorcet_winner(profile, m):
    """Return the candidate with a positive margin over every other candidate, or None."""
    M = margins(profile, m)
    for a in range(m):
        if all(M[a][b] > 0 for b in range(m) if b != a):
            return a
    return None


def weak_condorcet_winners(profile, m):
    """Return the frozenset of candidates whose margin over every other candidate is >= 0."""
    M = margins(profile, m)
    return frozenset(a for a in range(m) if all(M[a][b] >= 0 for b in range(m) if b != a))


def kendall_tau(r1, r2):
    """Return the number of pairs of candidates that r1 and r2 order differently."""
    pos = {a: i for i, a in enumerate(r2)}
    seq = [pos[a] for a in r1]
    return sum(1 for i in range(len(seq)) for j in range(i + 1, len(seq)) if seq[i] > seq[j])


def is_single_peaked_on(profile, axis):
    """Return True if every ranking of the profile is single-peaked on the axis.

    axis is a tuple of all candidates, left to right. A ranking is single-peaked on the axis
    exactly when, for each k, its k best candidates form a contiguous block of the axis.
    """
    where = {a: i for i, a in enumerate(axis)}
    for r in profile:
        lo = hi = where[r[0]]
        for a in r[1:]:
            p = where[a]
            if p == lo - 1:
                lo = p
            elif p == hi + 1:
                hi = p
            else:
                return False
    return True


def lex_tiebreak(candidates):
    """Return the candidate with the smallest index: the default tie-breaking rule."""
    return min(candidates)


def random_approval_profile(rng, m, n, p):
    """Return n approval ballots; each voter approves each candidate with probability p."""
    return tuple(frozenset(a for a in range(m) if rng.random() < p) for _ in range(n))


def permute_profile(profile, pi):
    """Rename the candidates: candidate a becomes pi[a]. Works for rankings and approval ballots."""
    out = []
    for ballot in profile:
        if isinstance(ballot, (set, frozenset)):
            out.append(frozenset(pi[a] for a in ballot))
        else:
            out.append(tuple(pi[a] for a in ballot))
    return tuple(out)


# ---------------------------------------------------------------- axiom checkers


def _as_set(result):
    if isinstance(result, (set, frozenset)):
        return frozenset(result)
    return frozenset([result])


def _domain(m, n, profiles):
    return all_profiles(m, n) if profiles is None else profiles


def _candidate_generators(m):
    """A transposition and an m-cycle: together they generate every permutation of the candidates."""
    gens = []
    if m >= 2:
        swap = list(range(m))
        swap[0], swap[1] = 1, 0
        gens.append(tuple(swap))
    if m >= 3:
        gens.append(tuple((a + 1) % m for a in range(m)))
    return gens


def check_anonymity(rule, m, n, profiles=None):
    """Check that permuting the voters does not change the result.

    It tries the swap of voters 0 and 1 and the cyclic shift of the voters. These generate all
    permutations, so on the full domain this is a complete test. Returns None or
    (profile, permuted_profile).
    """
    for P in _domain(m, n, profiles):
        P = tuple(P)
        if len(P) < 2:
            continue
        base = _as_set(rule(P, m))
        others = [(P[1], P[0]) + P[2:], P[1:] + P[:1]]
        for Q in others:
            if _as_set(rule(Q, m)) != base:
                return (P, Q)
    return None


def check_neutrality(rule, m, n, profiles=None):
    """Check that renaming the candidates by pi renames the result by pi.

    It tries a transposition and an m-cycle of the candidates, which generate all permutations.
    A resolute rule with a fixed tie-breaking order usually fails this test; test its
    correspondence instead. Returns None or (profile, pi).
    """
    gens = _candidate_generators(m)
    for P in _domain(m, n, profiles):
        P = tuple(P)
        base = _as_set(rule(P, m))
        for pi in gens:
            if _as_set(rule(permute_profile(P, pi), m)) != frozenset(pi[a] for a in base):
                return (P, pi)
    return None


def check_pareto(rule, m, n, profiles=None):
    """Check that no candidate b wins when every voter ranks some a above b.

    Returns None or (profile, a, b).
    """
    for P in _domain(m, n, profiles):
        P = tuple(P)
        W = _as_set(rule(P, m))
        N = pairwise(P, m)
        for b in W:
            for a in range(m):
                if a != b and N[a][b] == len(P):
                    return (P, a, b)
    return None


def check_condorcet_consistency(rule, m, n, profiles=None):
    """Check that a Condorcet winner, when one exists, is the unique winner.

    Returns None or (profile, condorcet_winner).
    """
    for P in _domain(m, n, profiles):
        P = tuple(P)
        c = condorcet_winner(P, m)
        if c is not None and _as_set(rule(P, m)) != frozenset([c]):
            return (P, c)
    return None


def _raise_once(r, w):
    """Return r with w moved up one place, or None if w is already on top."""
    i = r.index(w)
    if i == 0:
        return None
    s = list(r)
    s[i - 1], s[i] = s[i], s[i - 1]
    return tuple(s)


def check_monotonicity(rule, m, n, profiles=None):
    """Check that a winner stays a winner when one voter moves it up one place.

    Every raise of w, with no other change in the relative order of the others, is a chain of
    such one-place moves, so on the full domain this is a complete test. For a correspondence
    the test is that w stays in the winning set. Returns None or (profile, raised_profile, w).
    """
    for P in _domain(m, n, profiles):
        P = tuple(P)
        for w in _as_set(rule(P, m)):
            for i, r in enumerate(P):
                s = _raise_once(r, w)
                if s is None:
                    continue
                Q = P[:i] + (s,) + P[i + 1:]
                if w not in _as_set(rule(Q, m)):
                    return (P, Q, w)
    return None


def find_manipulation(rule, m, n, profiles=None):
    """Search for a voter who gets a strictly better winner by a false ranking.

    The rule must be resolute (a correspondence must return one winner on every profile it
    is called on). Returns None or (profile, voter, false_ranking): with the false ranking in
    place of the voter's true one, the winner is one that the true ranking strictly prefers.
    """
    rankings = all_rankings(m)
    for P in _domain(m, n, profiles):
        P = tuple(P)
        w = _single(rule(P, m))
        for i, r in enumerate(P):
            if r[0] == w:
                continue
            for s in rankings:
                if s == r:
                    continue
                Q = P[:i] + (s,) + P[i + 1:]
                if prefers(r, _single(rule(Q, m)), w):
                    return (P, i, s)
    return None


def _single(result):
    W = _as_set(result)
    if len(W) != 1:
        raise ValueError("find_manipulation needs a resolute rule")
    return next(iter(W))
instant_runoff_voting.py 58 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/instant-runoff-voting/. The authors are listed in prov/P7TC87.jsonl.

from typing import Sequence

Ranking = Sequence[int]


def instant_runoff_rounds(profile: Sequence[Ranking], m: int) -> tuple[int, list[tuple[list[int], int]]]:
    """Run instant-runoff voting and return (winner, rounds).

    The candidates are 0, ..., m - 1 (m >= 1). Each ballot ranks distinct candidates, best
    first; a ballot may be truncated and leave some candidates out, and it is exhausted when
    none of its candidates is still in the race. Each entry of rounds is (count, x): count[a]
    is the number of ballots on the pile of a in that round (0 for eliminated candidates), and
    x is the candidate eliminated in that round, or -1 in the last round.

    The count stops when a continuing candidate has more than half of the ballots that are not
    exhausted, or when one candidate is left. Among the continuing candidates with the fewest
    ballots, the one with the largest index is eliminated, so that the smallest index wins a
    final tie. Time O(L + m^2) with L the total length of the ballots, which is O(n m + m^2)
    for full rankings; extra space O(n + m).
    """
    continuing = [True] * m  # @line L1
    ptr = [0] * len(profile)
    piles: list[list[int]] = [[] for _ in range(m)]
    for i, r in enumerate(profile):  # @line L2
        if len(r) > 0:
            piles[r[0]].append(i)
    left = m
    rounds = []
    while True:  # @line L3
        active = sum(len(piles[a]) for a in range(m) if continuing[a])  # @line L4
        count = [len(piles[a]) if continuing[a] else 0 for a in range(m)]
        for a in range(m):  # @line L5
            if continuing[a] and (2 * count[a] > active or left == 1):
                rounds.append((count, -1))
                return a, rounds  # @line L6
        x = -1
        for a in range(m):  # @line L7
            if continuing[a] and (x == -1 or count[a] <= count[x]):
                x = a
        rounds.append((count, x))
        continuing[x] = False  # @line L8
        left -= 1
        for i in piles[x]:  # @line L9
            r = profile[i]
            ptr[i] += 1
            while ptr[i] < len(r) and not continuing[r[ptr[i]]]:  # @line L10
                ptr[i] += 1
            if ptr[i] < len(r):  # @line L11
                piles[r[ptr[i]]].append(i)
        piles[x] = []


def instant_runoff(profile: Sequence[Ranking], m: int) -> int:
    """Return the instant-runoff winner, with the tie rules of instant_runoff_rounds."""
    return instant_runoff_rounds(profile, m)[0]
test_instant_runoff_voting.py 202 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/instant-runoff-voting/. The authors are listed in prov/P7TC87.jsonl.

import itertools
import random

from agtprefs import (all_profiles, all_rankings, check_anonymity, check_condorcet_consistency,
                      check_monotonicity, check_neutrality, check_pareto, condorcet_winner,
                      find_manipulation, margins, permute_profile, prefers, random_profile)
from instant_runoff_voting import instant_runoff, instant_runoff_rounds

A, B, C, D = 0, 1, 2, 3


def naive_irv(profile, m):
    """Recount every ballot from scratch in each round, with the same tie rules."""
    cont = set(range(m))
    while True:
        count = {a: 0 for a in cont}
        for r in profile:
            tops = [a for a in r if a in cont]
            if tops:
                count[tops[0]] += 1
        active = sum(count.values())
        for a in sorted(cont):
            if 2 * count[a] > active or len(cont) == 1:
                return a
        low = min(count.values())
        cont.remove(max(a for a in cont if count[a] == low))


def put_winners(profile, m):
    """The winners under every way of breaking elimination ties (parallel universes)."""
    out = set()

    def run(cont):
        if len(cont) == 1:
            out.update(cont)
            return
        count = {a: 0 for a in cont}
        for r in profile:
            tops = [a for a in r if a in cont]
            if tops:
                count[tops[0]] += 1
        low = min(count.values())
        for x in [a for a in cont if count[a] == low]:
            run(cont - {x})

    run(frozenset(range(m)))
    return frozenset(out)


def condorcet_loser(P, m):
    M = margins(P, m)
    for a in range(m):
        if all(M[a][b] < 0 for b in range(m) if b != a):
            return a
    return None


def multisets(m, n):
    return [tuple(c) for c in itertools.combinations_with_replacement(all_rankings(m), n)]


# The worked example: the nine voters of the plurality page.
EXAMPLE = ((A, B, C),) * 4 + ((B, C, A),) * 3 + ((C, B, A),) * 2


def test_worked_example():
    w, rounds = instant_runoff_rounds(EXAMPLE, 3)
    assert rounds == [([4, 3, 2], C), ([4, 5, 0], -1)]
    assert w == B == condorcet_winner(EXAMPLE, 3)


def test_matches_naive_recount():
    rng = random.Random(41)
    for _ in range(3000):
        m, n = rng.randint(1, 6), rng.randint(0, 11)
        if rng.random() < 0.5:
            P = random_profile(rng, m, n)
        else:  # truncated ballots
            P = tuple(tuple(rng.sample(range(m), rng.randint(0, m))) for _ in range(n))
        assert instant_runoff(P, m) == naive_irv(P, m)


def test_early_stop_equals_running_to_the_end():
    # Stopping at a majority of the continuing ballots gives the same winner as eliminating
    # until one candidate is left.
    def to_the_end(P, m):
        cont = set(range(m))
        while len(cont) > 1:
            count = {a: sum(1 for r in P if [x for x in r if x in cont][:1] == [a]) for a in cont}
            low = min(count.values())
            cont.remove(max(a for a in cont if count[a] == low))
        return cont.pop()

    rng = random.Random(42)
    for _ in range(1500):
        m, n = rng.randint(1, 6), rng.randint(1, 11)
        P = random_profile(rng, m, n)
        assert instant_runoff(P, m) == to_the_end(P, m)


def test_rounds_are_consistent():
    rng = random.Random(43)
    for _ in range(500):
        m, n = rng.randint(1, 6), rng.randint(1, 11)
        P = random_profile(rng, m, n)
        w, rounds = instant_runoff_rounds(P, m)
        out = set()
        for count, x in rounds:
            assert all(count[a] == 0 for a in out)
            assert sum(count) == n  # full rankings are never exhausted
            if x >= 0:
                assert count[x] == min(count[a] for a in range(m) if a not in out)
                out.add(x)
        assert len(rounds) <= m and w not in out


def test_edge_cases():
    assert instant_runoff((), 3) == 0
    assert instant_runoff(((), ()), 2) == 0
    assert instant_runoff(((0,),), 1) == 0
    assert instant_runoff(((1, 0), (0, 1)), 2) == 0  # a final tie goes to the smaller index
    assert instant_runoff(((2,), (1,), (1,)), 3) == 1  # truncated ballots


def test_majority_and_condorcet_loser_criteria():
    for m, n in [(3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (4, 2), (4, 3)]:
        for P in all_profiles(m, n):
            w = instant_runoff(P, m)
            for a in range(m):
                if 2 * sum(1 for r in P if r[0] == a) > n:
                    assert w == a
            assert w != condorcet_loser(P, m)
            assert w in put_winners(P, m)


def test_axioms_by_brute_force():
    for m, n in [(3, 3), (3, 4), (4, 2), (4, 3)]:
        assert check_anonymity(instant_runoff, m, n) is None
        assert check_pareto(instant_runoff, m, n) is None
        assert check_neutrality(put_winners, m, n) is None
    # The resolute rule with the fixed tie-break is not neutral.
    assert check_neutrality(instant_runoff, 3, 2) is not None


def test_two_candidates_is_majority_rule():
    for n in range(1, 8):
        for P in all_profiles(2, n):
            k = sum(1 for r in P if r[0] == 0)
            assert instant_runoff(P, 2) == (0 if 2 * k >= n else 1)
        assert find_manipulation(instant_runoff, 2, n) is None


def test_not_condorcet_consistent():
    # The center squeeze: b beats a and c in pairs, but has the fewest first places.
    P = ((A, B, C),) * 2 + ((B, A, C),) + ((C, B, A),) * 2
    assert condorcet_winner(P, 3) == B
    assert instant_runoff_rounds(P, 3) == (A, [([2, 1, 2], B), ([3, 0, 2], -1)])
    found = check_condorcet_consistency(instant_runoff, 3, 3)
    assert found is not None and instant_runoff(found[0], 3) != found[1]


def test_not_monotone():
    # With 3 candidates, the smallest failure of monotonicity by a one-place raise has 7
    # voters, and it goes through a tie.
    for n in range(1, 7):
        assert check_monotonicity(instant_runoff, 3, n, profiles=multisets(3, n)) is None
    P, Q, w = check_monotonicity(instant_runoff, 3, 7, profiles=multisets(3, 7))
    assert instant_runoff(P, 3) == w != instant_runoff(Q, 3)
    # A failure with no ties: 6 a > b > c, 2 b > a > c, 4 b > c > a, 5 c > a > b. a wins.
    # If the 2 voters b > a > c move a to the top, b drops below c and c wins.
    P = ((A, B, C),) * 6 + ((B, A, C),) * 2 + ((B, C, A),) * 4 + ((C, A, B),) * 5
    Q = ((A, B, C),) * 8 + ((B, C, A),) * 4 + ((C, A, B),) * 5
    assert instant_runoff_rounds(P, 3) == (A, [([6, 6, 5], C), ([11, 6, 0], -1)])
    assert instant_runoff_rounds(Q, 3) == (C, [([8, 4, 5], B), ([8, 0, 9], -1)])


def test_no_show_paradox():
    # 2 a > c > b, 4 b > c > a, 3 c > b > a: c wins. Two more voters a > c > b make b win,
    # and they prefer c to b, so they do better by staying home.
    P = ((A, C, B),) * 2 + ((B, C, A),) * 4 + ((C, B, A),) * 3
    assert instant_runoff_rounds(P, 3) == (C, [([2, 4, 3], A), ([0, 4, 5], -1)])
    Q = P + ((A, C, B),) * 2
    assert instant_runoff_rounds(Q, 3) == (B, [([4, 4, 3], C), ([4, 7, 0], -1)])
    assert prefers((A, C, B), C, B)


def test_manipulable():
    P, i, s = find_manipulation(instant_runoff, 3, 3)
    Q = P[:i] + (s,) + P[i + 1:]
    assert prefers(P[i], instant_runoff(Q, 3), instant_runoff(P, 3))


def test_renaming_and_put_on_ties():
    # With 3 voters and one first place each, the tie rule decides; the parallel-universe
    # correspondence returns every candidate.
    P = ((A, B, C), (B, C, A), (C, A, B))
    assert put_winners(P, 3) == {A, B, C}
    pi = (2, 0, 1)
    assert put_winners(permute_profile(P, pi), 3) == {pi[a] for a in put_winners(P, 3)}

History

Thomas Hare in Britain and Carl Andrae in Denmark devised the single transferable vote in the 1850s, as a rule to elect several members. The single-winner form, in which a candidate is elected by a majority and the weakest is eliminated, is usually credited to the American architect William Robert Ware, about 1871. Australia has used it for its House of Representatives since 1918, Ireland uses it to elect its president, and the American state of Maine first used it in 2018. Doron and Kronick (1977) showed that the rule is not monotone, and Bartholdi and Orlin (1991) showed that manipulating it is NP-complete, a first example of computational hardness as a barrier to strategic voting.

References

  1. Felix Brandt, Vincent Conitzer, Ulle Endriss, Jérôme Lang and Ariel D. Procaccia (eds.), Handbook of Computational Social Choice, Cambridge University Press, 2016, Chapter 2 (William S. Zwicker, Introduction to the theory of voting), Section 2.4 (Condorcet extensions, scoring rules and run-offs)
  2. Gideon Doron and Richard Kronick, Single transferable vote: an example of a perverse social choice function, American Journal of Political Science 21(2) (1977), 303-311, the failure of monotonicity
  3. John J. Bartholdi III and James B. Orlin, Single transferable vote resists strategic voting, Social Choice and Welfare 8(4) (1991), 341-354, the proof that it is NP-complete to decide whether a voter can manipulate the single-winner rule

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
  • a scene preset for the example