"""Compare periodic rows using integer arithmetic. Requires only Python 3."""

from itertools import product


def row_entry(lower, upper, weights):
    """Follow each possible seam bit. The ice rule fixes every subsequent bit."""
    a, b, c = weights
    total = 0
    for seam in (0, 1):
        west = seam
        weight = 1
        for south, north in zip(lower, upper):
            east = west + south - north
            if east not in (0, 1):
                break
            if west == south:
                weight *= a
            elif west == east:
                weight *= b
            else:
                weight *= c
            west = east
        else:
            if west == seam:
                total += weight
    return total


def row(states, weights):
    return [[row_entry(lower, upper, weights) for lower in states] for upper in states]


def multiply(left, right):
    return [[sum(x * y for x, y in zip(r, col)) for col in zip(*right)] for r in left]


def main():
    for width in range(2, 6):
        states = list(product((0, 1), repeat=width))
        a, b, c = (row(states, w) for w in ((1, 1, 1), (3, 8, 7), (2, 1, 3)))
        assert multiply(a, b) == multiply(b, a)
        ac, ca = multiply(a, c), multiply(c, a)
        assert (ac == ca) == (width < 4)
        print(f"Width {width}: AB = BA; AC = CA: {ac == ca}")
        if width == 4:
            i, j = states.index((0, 0, 1, 1)), states.index((0, 1, 0, 1))
            assert (ac[i][j], ca[i][j]) == (161, 107)
            print(f"0101 to 0011: AC gives {ac[i][j]}, CA gives {ca[i][j]}")


if __name__ == "__main__":
    main()
