Algorithm Search⌘K

Algorithmadvanced

Dodgson's rule

Also called Dodgson's method, Lewis Carroll's voting rule.

Elects the candidate that needs the fewest swaps of adjacent candidates in ballots to become a Condorcet winner. Winner finding is Theta_2^p-complete (Hemaspaandra, Hemaspaandra and Rothe 1997).

Time
O(m^3 n (n/2 + 2)^(m - 1)) worst
Space
O(m (n/2 + 2)^(m - 1)) extra
Where
m = the number of candidates; n = the number of voters
Properties
not comparison baseddeterministiciterative
Origin
Charles Lutwidge Dodgson, 1876

Dodgson's rule elects the candidate that is closest to being a Condorcet winner. The distance is the Dodgson score: the least number of swaps of two adjacent candidates on the ballots after which the candidate beats every other one by a strict majority. A Condorcet winner has score 0 and wins. When there is none, the rule picks the candidate with the smallest score. Computing the score is NP-hard, and deciding whether a candidate wins is complete for Θ2p\Theta_2^p, the class of problems solvable in polynomial time with logarithmically many queries to an NP oracle. The algorithm below is a dynamic program over the voters. It is exact, and it runs in polynomial time when the number of candidates is fixed.

In plain words

If one candidate beats every other one in head-to-head majority votes, that candidate should win. Often no candidate does. The rule then asks how much the ballots would have to change for a candidate to get there. The only change allowed is to swap two neighbours on one ballot, and each swap costs one. The candidate that needs the fewest swaps wins. Lewis Carroll, the author of the Alice books, proposed this rule. The idea is simple, but finding the fewest swaps is hard in general. When there are only a few candidates, the search is fast, because it only needs to track how many more voters must prefer the candidate to each rival.

The problem

There are mm candidates A={0,…,m−1}A = \{0, \ldots, m - 1\} and a profile PP of n≥1n \ge 1 rankings, each best first. Let N(x,y)N(x, y) be the number of voters who rank xx above yy. Candidate cc is a Condorcet winner when N(c,b)>n/2N(c, b) > n/2 for every b≠cb \ne c, that is, N(c,b)≥qN(c, b) \ge q with q=⌊n/2⌋+1q = \lfloor n/2 \rfloor + 1. A swap exchanges two adjacent candidates on one ballot. The Dodgson score sc(c)\mathrm{sc}(c) is the least number of swaps that turn PP into a profile where cc is a Condorcet winner. The Dodgson winners are the candidates with the least score. Ties go to the candidate with the smallest index, as on every rule page of this area.

A swap that does not involve cc does not change any count N(c,b)N(c, b), and a swap that moves cc down only lowers one. The proof shows that some optimal sequence moves cc up on each ballot and does nothing else. On a ballot where cc is in place ℓ\ell (place 0 is the top), the choices are to move cc up by k=0,…,ℓk = 0, \ldots, \ell places, at cost kk, which puts cc above the kk candidates just above it.

The algorithm

  1. DODGSON-SCORE(P, c)
  2. 1N[x][y] ← number of voters who rank x above y; q ← ⌊n/2⌋ + 1
  3. 2d0[b] ← max(0, q - N[c][b]) for each b ≠ c
  4. 3F ← {d0 ↦ 0}
  5. 4for each ballot r of P do
  6. 5G ← empty map
  7. 6for each (d, cost) in F, and each k ← 0 to (number of candidates above c in r) do
  8. 7d' ← d with 1 subtracted, but not below 0, at the k candidates just above c in r
  9. 8G[d'] ← min(G[d'], cost + k)
  10. 9F ← G
  11. 10return F[(0, ..., 0)]
  12. DODGSON(P, m)
  13. 11return the smallest c with the least DODGSON-SCORE(P, c)

The vector dd holds the deficit of cc against each rival bb: how many more voters must put cc above bb. Line L2 sets the starting deficits. After each ballot, FF maps every deficit vector that can be reached to the least cost that reaches it. A deficit never goes below 0, because a larger majority than needed has no value. Line L10 reads the cost of the zero vector, which is reached at least by moving cc to the top of every ballot. The code also returns all scores and the set of winners.

Example

Take four candidates a,b,c,da, b, c, d (indices 0 to 3) and 7 voters, so q=4q = 4:

voter ranking
1, 2 d≻a≻b≻cd \succ a \succ b \succ c
3 b≻c≻d≻ab \succ c \succ d \succ a
4 c≻d≻b≻ac \succ d \succ b \succ a
5 d≻a≻c≻bd \succ a \succ c \succ b
6 a≻b≻c≻da \succ b \succ c \succ d
7 c≻d≻a≻bc \succ d \succ a \succ b

The majorities are dd over aa (6 to 1), dd over bb (5 to 2), aa over bb (5 to 2), aa over cc (4 to 3), bb over cc (4 to 3) and cc over dd (4 to 3). The cycle d≻a≻c≻dd \succ a \succ c \succ d means that there is no Condorcet winner. The scores are:

  • dd needs one more voter against cc. On ballot 4, cc is just above dd, so one swap is enough: sc(d)=1\mathrm{sc}(d) = 1.
  • cc needs one more voter against aa and one against bb. On ballot 1, one swap passes bb and a second one passes aa. No single swap gives both, so sc(c)=2\mathrm{sc}(c) = 2.
  • aa needs three more voters against dd. Ballots 1, 2 and 5 each give one for one swap: sc(a)=3\mathrm{sc}(a) = 3.
  • bb needs two more voters against aa and two against dd. On ballots 1 and 2, two swaps lift bb over both: sc(b)=4\mathrm{sc}(b) = 4.

So dd wins. For cc, the starting deficits against (a,b,d)(a, b, d) are (1,1,0)(1, 1, 0). On ballot 1 the candidates just above cc are bb, then aa, then dd. The values k=0,1,2k = 0, 1, 2 give F={(1,1,0)↦0,(1,0,0)↦1,(0,0,0)↦2}F = \{(1, 1, 0) \mapsto 0, (1, 0, 0) \mapsto 1, (0, 0, 0) \mapsto 2\}. The value k=3k = 3 also passes dd, which gives the vector (0,0,0)(0, 0, 0) at cost 3, so it is dropped. No later ballot gives a cheaper way to (0,0,0)(0, 0, 0).

Correctness

The proof in proofs/correctness.md first shows that some cheapest way to make cc a Condorcet winner only moves cc up, ballot by ballot. If an optimal sequence puts cc above some candidate bb that was above it, then every candidate between bb and cc must end below cc too, or the sequence pays for one more inversion. So moving cc up past all of them costs no more and gains at least as much. The dynamic program then tries every amount for every ballot and keeps, for each deficit vector, the cheapest way to reach it. Two partial choices with the same deficit vector can be completed in the same ways, so keeping the cheaper one is safe.

Proof: Correctness and properties of the Dodgson score algorithmfull

Let A={0,…,m−1}A = \{0, \ldots, m - 1\} with m≥2m \ge 2, let P=(r1,…,rn)P = (r_1, \ldots, r_n) be a profile of n≥1n \ge 1 rankings, let N(x,y)N(x, y) be the number of voters who rank xx above yy, and let q=⌊n/2⌋+1q = \lfloor n/2 \rfloor + 1. Candidate cc is a Condorcet winner of a profile exactly when N(c,b)≥qN(c, b) \ge q for every b≠cb \ne c. For a ballot rr where cc is in place ℓ\ell and 0≤k≤ℓ0 \le k \le \ell, let upk(r)\mathrm{up}_k(r) be rr with cc moved up kk places; it costs kk swaps, and cc passes the kk candidates just above it. The distance between two profiles is the least number of swaps that turns one into the other; for two rankings it is the number of pairs they order differently, so for profiles it is the sum of these numbers over the ballots.

Claim 1 (moving up is enough). sc(c)\mathrm{sc}(c) equals the least ∑iki\sum_i k_i over the choices 0≤ki≤ℓi0 \le k_i \le \ell_i for which cc is a Condorcet winner of (upk1(r1),…,upkn(rn))(\mathrm{up}_{k_1}(r_1), \ldots, \mathrm{up}_{k_n}(r_n)).

Proof. Each such profile is reached by ∑iki\sum_i k_i swaps, so sc(c)\mathrm{sc}(c) is at most the least sum. For the other direction, let Q=(s1,…,sn)Q = (s_1, \ldots, s_n) be a profile where cc is a Condorcet winner, reached from PP with sc(c)\mathrm{sc}(c) swaps; so the distance from PP to QQ is at most sc(c)\mathrm{sc}(c). On ballot ii, let UiU_i be the set of candidates above cc in rir_i and below cc in sis_i. If UiU_i is empty, let ki=0k_i = 0. Otherwise let uu be the member of UiU_i highest in rir_i, and let kik_i be the number of candidates from uu down to just above cc in rir_i, uu included. Every such candidate vv gives a pair that rir_i and sis_i order differently: if vv is below cc in sis_i, the pair {v,c}\{v, c\}; otherwise vv is above cc and so above uu in sis_i, while uu is above vv in rir_i, and the pair is {u,v}\{u, v\}. These pairs are distinct, so the distance between rir_i and sis_i is at least kik_i, and ∑iki≤sc(c)\sum_i k_i \le \mathrm{sc}(c). Moving cc up kik_i places in rir_i passes a superset of UiU_i. So in Q′=(upki(ri))iQ' = (\mathrm{up}_{k_i}(r_i))_i, for each b≠cb \ne c, cc is above bb on every ballot where it is above bb in QQ: either cc was above bb in rir_i, and moving cc up keeps this, or b∈Uib \in U_i. So NQ′(c,b)≥NQ(c,b)≥qN_{Q'}(c, b) \ge N_Q(c, b) \ge q, and cc is a Condorcet winner of Q′Q'.

Claim 2 (invariant). For a choice of k1,…,kik_1, \ldots, k_i on the first ii ballots, let its deficit vector be d[b]=max⁡(0,q−N(c,b)−gb)d[b] = \max(0, q - N(c, b) - g_b), where gbg_b is the number of ballots j≤ij \le i on which bb is among the kjk_j candidates just above cc. After line L9 has run for the first ii ballots, FF maps exactly the deficit vectors of such choices, each to the least ∑j≤ikj\sum_{j \le i} k_j that gives it.

Proof. By induction on ii. For i=0i = 0 the only choice is empty, its deficit vector is the one of line L2, and its cost is 0, as set by line L3. Assume the claim after i−1i - 1 ballots. A choice for ii ballots is a choice for i−1i - 1 ballots followed by a kik_i, and the new deficit vector depends only on the old one and kik_i: each candidate passed on ballot ii has its deficit lowered by 1, not below 0, which is line L7. So the vectors reachable after ii ballots are those of line L7 applied to the keys of FF. For a vector d′d', a cheapest choice that reaches it ends with some kik_i after a choice with some vector dd. Replacing that first part by a cheapest choice with vector dd gives the same d′d' at no larger cost. So the least cost of d′d' is the least F[d]+kiF[d] + k_i over the pairs (d,ki)(d, k_i) that lead to d′d', which is what lines L6 and L8 compute.

Claim 3 (correctness). DODGSON-SCORE returns sc(c)\mathrm{sc}(c), and line L11 returns the Dodgson winner with the smallest index.

Proof. The choice ki=ℓik_i = \ell_i for all ii puts cc on top of every ballot, so N(c,b)=n≥qN(c, b) = n \ge q and the zero vector is reached; line L10 finds a key. A choice has deficit vector zero exactly when cc is a Condorcet winner of the resulting profile. By Claim 2, line L10 returns the least ∑iki\sum_i k_i among those choices, which is sc(c)\mathrm{sc}(c) by Claim 1. Line L11 compares the scores of all candidates.

Claim 4 (Condorcet consistency). sc(c)=0\mathrm{sc}(c) = 0 exactly when cc is a Condorcet winner of PP, so a Condorcet winner is the unique winner.

Proof. Zero swaps leave PP unchanged. Every other candidate has a positive score, since there is at most one Condorcet winner.

Claim 5 (Pareto). If every voter ranks aa above bb, then sc(a)<sc(b)\mathrm{sc}(a) < \mathrm{sc}(b).

Proof. By Claim 1, take kik_i with sum sc(b)\mathrm{sc}(b) such that bb is a Condorcet winner of Q=(upki(ri))iQ = (\mathrm{up}_{k_i}(r_i))_i, where the moves are of bb. Not all kik_i are 0, because bb loses to aa in PP. On ballot ii, let δi≥1\delta_i \ge 1 be the number of places between aa and bb, so aa is δi\delta_i places above bb. Move aa up ki′=max⁡(0,ki−δi)k'_i = \max(0, k_i - \delta_i) places instead. Then ki′≤kik'_i \le k_i, with ki′<kik'_i < k_i when ki>0k_i > 0, so ∑iki′<sc(b)\sum_i k'_i < \mathrm{sc}(b). In the new ballot, aa is above every x≠ax \ne a that bb is above in upki(ri)\mathrm{up}_{k_i}(r_i): such an xx is below bb in rir_i, or between aa and bb, or above aa and passed by bb, and then it is passed by aa too, because bb passes the ki−δik_i - \delta_i candidates just above aa after it passes aa. So in the new profile N(a,x)≥NQ(b,x)≥qN(a, x) \ge N_Q(b, x) \ge q for every x≠a,bx \ne a, b, and N(a,b)=n≥qN(a, b) = n \ge q. So aa is a Condorcet winner after fewer than sc(b)\mathrm{sc}(b) swaps.

Claim 6 (anonymity and neutrality). Reordering the voters does not change any score. Renaming the candidates by a permutation π\pi maps the score of cc to the score of π(c)\pi(c).

Proof. A swap sequence for one profile becomes, by reordering the ballots or by renaming the candidates, a swap sequence of the same length for the other, and being a Condorcet winner is kept by both changes.

Claim 7 (time). DODGSON-SCORE runs in O(m2n(n/2+2)m−1)O(m^2 n (n/2 + 2)^{m - 1}) time and O(m(n/2+2)m−1)O(m (n/2 + 2)^{m - 1}) space.

Proof. Each of the m−1m - 1 deficits lies in {0,…,q}\{0, \ldots, q\} with q≤n/2+1q \le n/2 + 1, so FF and GG have at most (n/2+2)m−1(n/2 + 2)^{m - 1} keys of m−1m - 1 entries each. Line L1 takes O(nm2)O(n m^2) time. For each of the nn ballots, lines L6 to L8 try at most mm values of kk for each key, and each value takes O(m)O(m) time to build and look up the new vector. Line L11 calls DODGSON-SCORE mm times. ■\blacksquare

Complexity

A deficit lies between 0 and q≤⌊n/2⌋+1q \le \lfloor n/2 \rfloor + 1, so FF has at most (⌊n/2⌋+2)m−1(\lfloor n/2 \rfloor + 2)^{m - 1} entries. Each ballot tries at most mm values of kk for each entry, at cost O(m)O(m) each for the vector. One score costs O(m2n(n/2+2)m−1)O(m^2 n (n/2 + 2)^{m - 1}) time, and all mm scores cost O(m3n(n/2+2)m−1)O(m^3 n (n/2 + 2)^{m - 1}) in the word RAM model, with O(m(n/2+2)m−1)O(m (n/2 + 2)^{m - 1}) space for the maps. This is polynomial in nn for each fixed mm, but exponential in mm.

The exponent cannot be avoided by a much better general method unless P = NP: Bartholdi, Tovey and Trick proved that the score is NP-hard to compute. Deciding whether a candidate is a winner needs the scores of all candidates to be compared, and Hemaspaandra, Hemaspaandra and Rothe proved that it is complete for Θ2p\Theta_2^p, the class PNP[O(log⁡)]\mathrm{P}^{\mathrm{NP}[O(\log)]} in the polynomial hierarchy. The score is fixed-parameter tractable in the number of candidates, by an integer program with a fixed number of variables solved by Lenstra's algorithm, and also in the score itself. It is W[1]-hard in the number of voters.

Properties

The proofs are in proofs/correctness.md, and the tests check each property on all profiles with up to 4 candidates and few voters and on random profiles.

  • Condorcet consistent. A candidate has score 0 exactly when it is a Condorcet winner, so a Condorcet winner is the unique winner.
  • Pareto. If every voter ranks aa above bb, then sc(a)<sc(b)\mathrm{sc}(a) < \mathrm{sc}(b), so bb does not win.
  • Anonymous, and neutral as a correspondence. The resolute rule is not neutral, because of the tie rule.
  • Not homogeneous. Copying every ballot the same number of times can change the winners, because the threshold qq does not scale exactly. The tests have a profile of 7 voters with winners {a,b,d}\{a, b, d\} whose triple, with 21 voters, has the single winner bb.
  • Not monotone. Fishburn showed that for 4 or more candidates, moving the winner up on some ballots can make it lose.
  • Manipulable. By the Gibbard-Satterthwaite theorem, as for every resolute rule with at least 3 possible winners that is not a dictatorship, a voter can sometimes gain by a false ranking. The tests find such a case with 3 candidates and 3 voters.

Variants and improvements

  • Approximation. A greedy algorithm and an LP rounding algorithm approximate the score within the ratio Hm−1=1+1/2+⋯+1/(m−1)H_{m-1} = 1 + 1/2 + \cdots + 1/(m - 1), and a ratio much below ln⁡m\ln m is not possible in polynomial time unless P = NP. A rule that elects the candidate with the smallest approximate score is a different voting rule.
  • Young's rule. It counts the least number of voters to delete so that the candidate becomes a Condorcet winner.
  • Weak Dodgson. It asks for a weak Condorcet winner, one that loses to nobody, instead of a strict one.
  • Kemeny and Slater. Kemeny's rule and Slater's rule also measure a distance to consistency with majorities, but for a whole ranking rather than for one candidate.

When to use it

Use Dodgson's rule when a Condorcet winner should be elected whenever there is one, and the idea of the fewest changes to the ballots is the right way to settle cycles. It is exact and fast for a small number of candidates, with any number of voters. For many candidates use an approximation, or pick a Condorcet method that is easy to compute and monotone, such as Copeland's method, ranked pairs or the Schulze method.

Pitfalls

  • Swaps that do not involve the candidate. They never help, but a search over all swaps still explores them. Restrict the search to moving the candidate up.
  • Moving past the nearest candidates only. On one ballot, cc can only pass the candidates just above it, in order. Treating the candidates that cc passes as a free choice gives scores that are too low.
  • The majority threshold. With nn even, cc needs n/2+1n/2 + 1 voters against each rival, not n/2n/2. The threshold q=⌊n/2⌋+1q = \lfloor n/2 \rfloor + 1 covers both cases.
  • Empty profiles. With no voters, no candidate can become a Condorcet winner. The code returns no score and makes every candidate a winner.

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))
dodgson_rule.py 72 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dodgson-rule/. The authors are listed in prov/81D8GC.jsonl.

from typing import Optional, Sequence

Ranking = Sequence[int]


def pairwise_counts(profile: Sequence[Ranking], m: int) -> list[list[int]]:
    """Return 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 dodgson_score(profile: Sequence[Ranking], m: int, c: int) -> Optional[int]:
    """Return the least number of swaps of adjacent candidates on the ballots that make c a
    Condorcet winner, or None when no number of swaps does (only when there are no voters).

    A dynamic program over the voters. Its state is the vector of deficits: for each b != c,
    how many more voters must put c above b. On each ballot it tries every k, moving c up past
    the k candidates just above it at cost k.
    """
    n = len(profile)
    others = [b for b in range(m) if b != c]
    if not others:
        return 0
    if n == 0:
        return None
    N = pairwise_counts(profile, m)  # @line L1
    q = n // 2 + 1
    slot = {b: t for t, b in enumerate(others)}
    start = tuple(max(0, q - N[c][b]) for b in others)  # @line L2
    F = {start: 0}  # @line L3
    for r in profile:  # @line L4
        pos = list(r).index(c)
        above = [slot[r[pos - 1 - t]] for t in range(pos)]  # nearest first
        G: dict[tuple[int, ...], int] = {}  # @line L5
        for d, cost in F.items():  # @line L6
            cur = list(d)
            for k in range(pos + 1):
                if k > 0:
                    t = above[k - 1]
                    if cur[t] > 0:
                        cur[t] -= 1  # @line L7
                key = tuple(cur)
                if cost + k < G.get(key, cost + k + 1):
                    G[key] = cost + k  # @line L8
        F = G  # @line L9
    return F[tuple(0 for _ in others)]  # @line L10


def dodgson_scores(profile: Sequence[Ranking], m: int) -> list[Optional[int]]:
    """Return the Dodgson score of every candidate."""
    return [dodgson_score(profile, m, c) for c in range(m)]


def dodgson_winners(profile: Sequence[Ranking], m: int) -> frozenset[int]:
    """Return the candidates with the least Dodgson score (all candidates if there are no voters)."""
    s = dodgson_scores(profile, m)
    if any(x is None for x in s):
        return frozenset(range(m))
    best = min(s)
    return frozenset(c for c in range(m) if s[c] == best)  # @line L11


def dodgson(profile: Sequence[Ranking], m: int) -> int:
    """Return the Dodgson winner; a tie goes to the candidate with the smallest index."""
    return min(dodgson_winners(profile, m))
test_dodgson_rule.py 140 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dodgson-rule/. The authors are listed in prov/81D8GC.jsonl.

import random
from collections import deque

from agtprefs import (check_anonymity, check_condorcet_consistency, check_neutrality, check_pareto,
                      condorcet_winner, find_manipulation, pairwise, prefers, random_profile)
from dodgson_rule import dodgson, dodgson_score, dodgson_scores, dodgson_winners, pairwise_counts

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

# The worked example of the page: 7 voters, 4 candidates, no Condorcet winner.
EXAMPLE = ((D, A, B, C), (D, A, B, C), (B, C, D, A), (C, D, B, A), (D, A, C, B), (A, B, C, D),
           (C, D, A, B))


def swap_distance(P, m, c):
    """The Dodgson score by breadth-first search over all profiles one adjacent swap apart."""
    start = tuple(tuple(r) for r in P)
    dist = {start: 0}
    queue = deque([start])
    while queue:
        Q = queue.popleft()
        if condorcet_winner(Q, m) == c:
            return dist[Q]
        for i, r in enumerate(Q):
            for j in range(m - 1):
                s = list(r)
                s[j], s[j + 1] = s[j + 1], s[j]
                R = Q[:i] + (tuple(s),) + Q[i + 1:]
                if R not in dist:
                    dist[R] = dist[Q] + 1
                    queue.append(R)
    return None


def test_example():
    N = pairwise_counts(EXAMPLE, 4)
    assert N == pairwise(EXAMPLE, 4)
    assert N[D][A] == 6 and N[D][B] == 5 and N[C][D] == 4
    assert N[A][B] == 5 and N[A][C] == 4 and N[B][C] == 4
    assert condorcet_winner(EXAMPLE, 4) is None
    assert dodgson_scores(EXAMPLE, 4) == [3, 4, 2, 1]
    assert dodgson_winners(EXAMPLE, 4) == frozenset({D})
    assert dodgson(EXAMPLE, 4) == D


def test_edge_cases():
    assert dodgson_score((), 1, 0) == 0
    assert dodgson_score((), 3, 1) is None
    assert dodgson_winners((), 3) == frozenset({0, 1, 2})
    assert dodgson_scores(((2, 0, 1),), 3) == [1, 2, 0]
    cycle = ((A, B, C), (B, C, A), (C, A, B))
    assert dodgson_scores(cycle, 3) == [1, 1, 1]
    assert dodgson(cycle, 3) == A


def test_matches_breadth_first_search():
    rng = random.Random(1)
    for _ in range(60):
        m = rng.randint(2, 4)
        n = rng.randint(1, 2 if m == 4 else 3)
        P = random_profile(rng, m, n)
        for c in range(m):
            assert dodgson_score(P, m, c) == swap_distance(P, m, c)


def test_condorcet_winner_has_score_zero():
    rng = random.Random(2)
    for _ in range(150):
        m, n = rng.randint(2, 5), rng.randint(1, 9)
        P = random_profile(rng, m, n)
        s = dodgson_scores(P, m)
        w = condorcet_winner(P, m)
        assert (w is not None) == (0 in s)
        if w is not None:
            assert s[w] == 0 and dodgson_winners(P, m) == frozenset({w})


def test_axioms_on_full_domains():
    for m, n in ((2, 3), (3, 1), (3, 2), (3, 3), (4, 1)):
        assert check_anonymity(dodgson_winners, m, n) is None
        assert check_neutrality(dodgson_winners, m, n) is None
        assert check_pareto(dodgson_winners, m, n) is None
        assert check_condorcet_consistency(dodgson_winners, m, n) is None


def test_axioms_on_random_profiles():
    for m, n, seed in ((4, 5, 3), (5, 5, 4)):
        rng = random.Random(seed)
        Ps = [random_profile(rng, m, n) for _ in range(25)]
        assert check_anonymity(dodgson_winners, m, n, Ps) is None
        assert check_neutrality(dodgson_winners, m, n, Ps) is None
        assert check_pareto(dodgson_winners, m, n, Ps) is None
        assert check_condorcet_consistency(dodgson_winners, m, n, Ps) is None


def test_pareto_score_gap():
    rng = random.Random(6)
    for _ in range(300):
        m, n = rng.randint(2, 5), rng.randint(1, 7)
        P = random_profile(rng, m, n)
        s = dodgson_scores(P, m)
        for a in range(m):
            for b in range(m):
                if a != b and all(prefers(r, a, b) for r in P):
                    assert s[a] < s[b]


def test_not_homogeneous():
    P = ((A, D, C, B), (A, D, C, B), (C, D, B, A), (D, B, A, C), (B, A, D, C), (B, A, C, D),
         (C, B, A, D))
    assert dodgson_scores(P, 4) == [2, 2, 3, 2]
    assert dodgson_winners(P, 4) == frozenset({A, B, D})
    assert dodgson_scores(P * 3, 4) == [5, 4, 7, 5]
    assert dodgson_winners(P * 3, 4) == frozenset({B})


def test_resolute_rule_is_not_neutral():
    assert dodgson(((A, B), (B, A)), 2) == A
    assert check_neutrality(dodgson, 2, 2) is not None


def test_manipulation_exists():
    found = find_manipulation(dodgson, 3, 3)
    assert found is not None
    P, i, s = found
    Q = P[:i] + (s,) + P[i + 1:]
    assert prefers(P[i], dodgson(Q, 3), dodgson(P, 3))


def test_larger_input():
    rng = random.Random(7)
    P = random_profile(rng, 6, 15)
    s = dodgson_scores(P, 6)
    assert all(x is not None and x >= 0 for x in s)
    w = dodgson(P, 6)
    assert s[w] == min(s)
    assert s[w] <= 6 * 15

History

Charles Lutwidge Dodgson, the Oxford mathematician who wrote as Lewis Carroll, proposed the rule in a pamphlet of 1876. Fishburn later showed that the rule is not monotone. In 1989 Bartholdi, Tovey and Trick proved that the score and the winner are NP-hard to compute, one of the first results in computational social choice. In 1997 Hemaspaandra, Hemaspaandra and Rothe proved that the winner problem is complete for parallel access to NP, that is, for Θ2p\Theta_2^p. Later work by Caragiannis and coauthors and by others gave approximation algorithms and parameterized algorithms.

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 5 (Ioannis Caragiannis, Edith Hemaspaandra and Lane A. Hemaspaandra, Dodgson's rule and Young's rule): Theorem 5.1 on the Theta_2^p-completeness, Section 5.5 on the fixed-parameter results, Theorem 5.6 on the ratio H_(m-1) of the greedy and the LP algorithms, Theorem 5.10 on inapproximability, and the failure of monotonicity found by Fishburn
  2. Edith Hemaspaandra, Lane A. Hemaspaandra and Jörg Rothe, Exact analysis of Dodgson elections: Lewis Carroll's 1876 voting system is complete for parallel access to NP, Journal of the ACM 44(6) (1997), 806-825, the main theorem: deciding whether a candidate is a Dodgson winner is complete for parallel access to NP
  3. John J. Bartholdi III, Craig A. Tovey and Michael A. Trick, Voting schemes for which it can be difficult to tell who won the election, Social Choice and Welfare 6(2) (1989), 157-165, the NP-hardness of the Dodgson score and of the Dodgson winner

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