"""Exact distributions of all 1,024 length-two mesh patterns."""

from collections import Counter
from itertools import permutations
from sys import argv


SIDE = 3
SHADING_COUNT = 1 << (SIDE * SIDE)


def pair_masks(word):
    for i, a in enumerate(word):
        for j in range(i + 1, len(word)):
            b = word[j]
            low, high = sorted((a, b))
            occupied = 0
            for k, value in enumerate(word):
                if k == i or k == j:
                    continue
                x = int(k > i) + int(k > j)
                y = int(value > low) + int(value > high)
                occupied |= 1 << (SIDE * x + y)
            yield (0 if a < b else SHADING_COUNT), occupied


def occurrence_counts(word):
    counts = [0] * (2 * SHADING_COUNT)
    for offset, occupied in pair_masks(word):
        free = (SHADING_COUNT - 1) ^ occupied
        shading = free
        while True:
            counts[offset + shading] += 1
            if shading == 0:
                break
            shading = (shading - 1) & free
    return counts


def classify(limit):
    histories = [[] for _ in range(2 * SHADING_COUNT)]
    avoidance = [[] for _ in histories]
    for size in range(1, limit + 1):
        frequencies = [Counter() for _ in histories]
        for word in permutations(range(size)):
            for tally, occurrences in zip(frequencies, occurrence_counts(word)):
                tally[occurrences] += 1
        for history, zero, tally in zip(histories, avoidance, frequencies):
            history.append(tuple(sorted(tally.items())))
            zero.append(tally[0])
        print(size, len({tuple(row) for row in histories}),
              len({tuple(row) for row in avoidance}), flush=True)
    return histories, avoidance


if __name__ == "__main__":
    limit = int(argv[1]) if len(argv) > 1 else 7
    histories, avoidance = classify(limit)
    if limit >= 7:
        assert len({tuple(row) for row in histories}) == 105
        assert len({tuple(row) for row in avoidance}) == 46

