"""Count monochromatic boxes in a 2-colouring of an a x b x c grid. A box is {x1, x2} x {y1, y2} x {z1, z2} with x1 < x2, y1 < y2, z1 < z2. It is monochromatic when all 8 of its cells have the same colour. Input: a text file with a*b*c characters '0' or '1' (other characters are ignored), read in the order x (slowest), y, z (fastest). Usage: python3 check_boxes.py cube12-A.txt 12 (a cube: a = b = c = 12) python3 check_boxes.py block5x7x51.txt 5 7 51 """ import sys from itertools import combinations path = sys.argv[1] dims = [int(v) for v in sys.argv[2:]] a, b, c = dims * 3 if len(dims) == 1 else dims bits = [int(ch) for ch in open(path).read() if ch in "01"] assert len(bits) == a * b * c, f"expected {a * b * c} cells, found {len(bits)}" cell = lambda x, y, z: bits[(x * b + y) * c + z] total = boxes = 0 for x1, x2 in combinations(range(a), 2): for y1, y2 in combinations(range(b), 2): for z1, z2 in combinations(range(c), 2): total += 1 colours = {cell(x, y, z) for x in (x1, x2) for y in (y1, y2) for z in (z1, z2)} boxes += len(colours) == 1 print(f"{a} x {b} x {c} grid, {total} boxes checked, {boxes} monochromatic")