"""Exact counts on a street with more spots than cars, arXiv:2611.29890, Q5.5.
Spots have zero-based indices in this program. Cars have labels 1,...,n.
"""
from collections import Counter
from functools import lru_cache
from itertools import product
from math import comb, prod


def simulate(m, word, bump):
    street = [0] * m
    for car, p in enumerate(word, 1):
        if street[p] == 0:
            street[p] = car
        else:
            e = street.index(0)
            if bump:
                street[e], street[p] = street[p], car
            else:
                street[e] = car
    return tuple(street)


def predicted_set(m, word):
    preferred = set(word)
    remaining = [j for j in range(m) if j not in preferred]
    return frozenset(preferred.union(remaining[:len(word)-len(preferred)]))


def count_set(m, occupied):
    n = len(occupied)
    prefix = next((j for j in range(m) if j not in occupied), m)
    tail = n - prefix
    return sum((-1)**j * comb(tail, j) * (n-j)**n for j in range(tail+1))


def count_monopoly(street):
    prior_max = 0
    choices = []
    for label in street:
        if label == 0:
            break
        if label > prior_max:
            choices.append(label)
            prior_max = label
    return prod(choices)


@lru_cache(maxsize=None)
def count_backgammon(street):
    last = max(street, default=0)
    if last == 0:
        return 1
    j = street.index(last)
    prev = list(street)
    prev[j] = 0
    result = count_backgammon(tuple(prev))
    for s, label in enumerate(street):
        if label == 0:
            break
        if s != j:
            prev = list(street)
            prev[j], prev[s] = label, 0
            result += count_backgammon(tuple(prev))
    return result


def verify(m, n):
    sets, monopoly, backgammon = Counter(), Counter(), Counter()
    for word in product(range(m), repeat=n):
        a = simulate(m, word, False)
        b = simulate(m, word, True)
        occupied = predicted_set(m, word)
        assert occupied == frozenset(i for i, car in enumerate(a) if car)
        assert occupied == frozenset(i for i, car in enumerate(b) if car)
        sets[occupied] += 1
        monopoly[a] += 1
        backgammon[b] += 1
    assert len(sets) == comb(m, n)
    assert all(count_set(m, s) == v for s, v in sets.items())
    assert len(monopoly) == len(backgammon) == prod(range(m-n+1, m+1))
    assert all(count_monopoly(a) == v for a, v in monopoly.items())
    assert all(count_backgammon(b) == v for b, v in backgammon.items())
    return m**n


if __name__ == '__main__':
    tests = [(m,n) for m in range(1,8) for n in range(min(m,5)+1)]
    print(len(tests), 'street sizes;', sum(verify(m,n) for m,n in tests), 'preference lists checked under both rules.')
    for s in ({0,1,2},{0,1,3},{0,2,3},{1,2,3}):
        print([j+1 for j in sorted(s)], count_set(4,s))
