from functools import lru_cache
from math import comb


def count(pattern, copies):
    width = len(pattern)
    size = 2 + copies * (width - 2)
    predecessors = [0] * size
    order = sorted(range(width), key=pattern.__getitem__)
    for i in range(copies):
        offset = i * (width - 2)
        for x, y in zip(order, order[1:]):
            predecessors[offset + y] |= 1 << (offset + x)

    @lru_cache(None)
    def extensions(used):
        if used == (1 << size) - 1:
            return 1
        return sum(
            extensions(used | (1 << x))
            for x, required in enumerate(predecessors)
            if not (used >> x & 1) and required & used == required
        )

    return extensions(0)


cases = 0
for width in range(4, 13):
    for a in range(2, width - 1):
        for b in range(a + 1, width):
            middle = [v for v in range(2, width) if v not in (a, b)]
            # Reverse the interior to test independence of its choice of order.
            pattern = [1, a, *reversed(middle), b, width]
            for copies in range(1, 7):
                expected = comb(width - b + a - 3, a - 2) ** (copies - 1)
                assert count(pattern, copies) == expected
                cases += 1
print(f"{cases} pattern and copy-count combinations agree")
