"""Independent reproduction of iis:2611.00134 (Question 5.4 of arXiv:2611.29890).

Simulates Monopoly and backgammon parking literally from Section 1.1-1.2 of the
paper, compares displacement multisets for every preference list in [n]^n, and
checks the claimed criterion and recurrence.
"""
import itertools, sys
from collections import Counter

def first_free(occ):
    return occ.index(None)

def monopoly(alpha):
    n = len(alpha); occ = [None] * n
    for car, a in enumerate(alpha):
        p = a - 1
        occ[p if occ[p] is None else first_free(occ)] = car
    return occ

def backgammon(alpha):
    n = len(alpha); occ = [None] * n
    for car, a in enumerate(alpha):
        p = a - 1
        bumped = occ[p]
        occ[p] = car
        if bumped is not None:
            occ[first_free(occ)] = bumped
    return occ

def disp_multiset(alpha, occ):
    return Counter(abs(spot - (alpha[car] - 1)) for spot, car in enumerate(occ)
                   if spot != alpha[car] - 1)

def criterion(alpha):
    # The occupied sets agree in both schemes, so tracking Monopoly's filled set suffices.
    n = len(alpha); filled = set(); seen = set()
    for a in alpha:
        if a not in seen and a in filled:
            return False
        seen.add(a)
        filled.add(a if a not in filled else min(set(range(1, n + 1)) - filled))
    return True

def recurrence(n):
    a = [1] + [0] * n
    for t in range(n):
        b = [0] * (n + 1)
        for d in range(n + 1):
            b[d] = d * a[d] + ((n - t) * a[d - 1] if d else 0)
        a = b
    return a

# paper's worked examples (Examples 1.12, 1.13)
for alpha, M, B in [((1,4,4,3,2,2), {2:1,3:1,4:1}, {1:1,4:1}), ((1,3,3,1), {1:1,3:1}, {1:1,3:1})]:
    assert disp_multiset(alpha, monopoly(alpha)) == Counter(M), alpha
    assert disp_multiset(alpha, backgammon(alpha)) == Counter(B), alpha
assert [c + 1 for c in monopoly((1,4,4,3,2,2))] == [1,3,4,2,5,6]   # O_M = 134256
assert [c + 1 for c in backgammon((1,4,4,3,2,2))] == [1,6,4,3,2,5]  # O_B = 164325
# the claimant's worked counterexample: M = {1,2}, B = {1}
assert disp_multiset((2,2,1), monopoly((2,2,1))) == Counter({1:1, 2:1})
assert disp_multiset((2,2,1), backgammon((2,2,1))) == Counter({1:1})

lo, hi = (int(x) for x in sys.argv[1:3])
for n in range(lo, hi + 1):
    same = 0; by_d = Counter(); mismatch = 0
    for alpha in itertools.product(range(1, n + 1), repeat=n):
        eq = disp_multiset(alpha, monopoly(alpha)) == disp_multiset(alpha, backgammon(alpha))
        if eq != criterion(alpha):
            mismatch += 1
        if eq:
            same += 1; by_d[len(set(alpha))] += 1
    rec = recurrence(n)
    print(n, same, sum(rec), [by_d[d] for d in range(1, n + 1)] == rec[1:], "criterion mismatches:", mismatch)
