"""Exact finite self-checks for the proof of Drexel–Peng–Richey Question 24."""

from collections import Counter
from fractions import Fraction
from itertools import product
from math import comb


def overlap_sum(a, b, mass):
    """Equation (4) of the paper, using nonempty suffix-prefix matches."""
    return sum(
        1 / mass[b[:k]]
        for k in range(1, min(len(a), len(b)) + 1)
        if a.endswith(b[:k])
    )


def check(n, p):
    by_length = {
        m: ["".join(bits) for bits in product("01", repeat=m)]
        for m in range(1, n + 1)
    }
    mass = {
        u: p ** u.count("1") * (1 - p) ** u.count("0")
        for words in by_length.values() for u in words
    }
    wait = {u: overlap_sum(u, u, mass) for u in mass}
    thresholds = (Fraction(1, 4), Fraction(1, 2), Fraction(3, 4))
    qualified = Counter()
    total = 0
    for m in range(2, n + 1):
        for ell in range(1, m):
            histogram = Counter()
            for v, w in product(by_length[m], by_length[ell]):
                if w in v:
                    win = Fraction(0)
                else:
                    # The paper's exact race formula, equation (6).
                    a = wait[w] - overlap_sum(w, v, mass)
                    b = wait[v] - overlap_sum(v, w, mass)
                    win = a / (a + b)
                assert 0 <= win <= 1
                # Both directions of the mass comparison for strict victory.
                assert win <= mass[v] * wait[w] <= mass[v] / (p * mass[w])
                assert 1 - win <= mass[w] * wait[v] <= mass[w] / (p * mass[v])
                histogram[v.count("1") + w.count("0")] += 1
                for alpha in thresholds:
                    qualified[alpha] += win >= alpha
                total += 1
            assert [histogram[k] for k in range(m + ell + 1)] == [
                comb(m + ell, k) for k in range(m + ell + 1)
            ]
    assert 3 * total == 4 ** (n + 1) - 3 * 2 ** (n + 2) + 8
    counts = ", ".join(str(qualified[a]) for a in thresholds)
    print(f"n={n}  p={p}  pairs={total}  counts at 1/4, 1/2, 3/4: {counts}")


if __name__ == "__main__":
    check(6, Fraction(1, 4))
    check(6, Fraction(1, 3))
