"""Aztec tilings classified by the particle positions on a Johansson zig-zag.

All coordinates are the lower-left corners of unit cells. A domino matching
is enumerated once by pairing the first free cell with each free neighbor.
Only the Python standard library is required.
"""
from collections import Counter
from fractions import Fraction
from itertools import combinations
from math import comb, prod


def diamond(order):
    return {(x, y) for x in range(-order, order) for y in range(-order, order)
            if abs(2*x + 1) + abs(2*y + 1) <= 2*order}


def tilings(cells):
    if not cells:
        yield {}
        return
    x, y = start = min(cells)
    for end in ((x-1, y), (x+1, y), (x, y-1), (x, y+1)):
        if end in cells:
            for remaining in tilings(cells - {start, end}):
                yield {**remaining, start: end, end: start}


def slice_positions(matching, order, level):
    positions = []
    for k in range(order + 1):
        x, y = -level + k, order - k - level
        partner = matching[x, y]
        if partner in ((x-1, y), (x, y-1)):
            positions.append(order - k)
    return tuple(sorted(positions))


if __name__ == "__main__":
    for order in (1, 2, 3, 4):
        sample = list(tilings(diamond(order)))
        assert len(sample) == 2**(order*(order+1)//2)
        for level in range(1, order + 1):
            counts = Counter(slice_positions(t, order, level) for t in sample)
            weights = {}
            for positions in combinations(range(order + 1), level):
                differences = prod(j-i for i, j in combinations(positions, 2))
                weights[positions] = differences**2 * prod(comb(order, h) for h in positions)
            total_weight = sum(weights.values())
            assert counts.keys() == weights.keys()
            for positions, count in counts.items():
                assert Fraction(count, len(sample)) == Fraction(weights[positions], total_weight)
            if level == 1 or (order, level) == (3, 2):
                print("Order", order, "level", level, sorted(counts.items()), "total", len(sample))
