Read the checking program (81 lines of Python)
"""Check a layered comparator network on all binary inputs and score its depth."""
import json
import sys
WIRES = 22
MAX_BYTES = 1474
def sorts(wire_count, layers):
# By the zero-one principle, binary inputs suffice. Each bit of a wire's
# integer represents one input. Process blocks to bound memory use.
varying = min(wire_count, 20)
rows = 1 << varying
byte_count = (rows + 7) // 8
ones = (1 << rows) - 1
columns = []
for wire in range(varying):
if wire < 3:
pattern = (0xAA, 0xCC, 0xF0)[wire]
column = bytes([pattern]) * byte_count
else:
block = 1 << (wire - 3)
column = (bytes(block) + b"\xff" * block) * (byte_count // (2 * block))
columns.append(int.from_bytes(column, "little") & ones)
for fixed in range(1 << (wire_count - varying)):
wires = columns + [
ones if fixed & (1 << wire) else 0
for wire in range(wire_count - varying)
]
for layer in layers:
for left, right in layer:
low, high = wires[left], wires[right]
wires[left], wires[right] = low & high, low | high
if any(left & ~right for left, right in zip(wires, wires[1:])):
return False
return True
def verify(data, wire_count=WIRES):
lines = data.splitlines()
if not 1 <= len(lines) <= wire_count:
raise ValueError("Use between one and the number of wires in layers.")
layers = []
for line in lines:
entries = line.split()
if not 2 <= len(entries) <= wire_count or len(entries) % 2:
raise ValueError("Each layer must contain one or more pairs of wire indices.")
if any(len(token) > 2 or not token.isdigit() for token in entries):
raise ValueError("Wire indices must be short nonnegative decimal integers.")
indices = list(map(int, entries))
if len(set(indices)) != len(indices):
raise ValueError("A wire occurs twice in the same layer.")
layer = list(zip(indices[::2], indices[1::2]))
if any(not 0 <= left < right < wire_count for left, right in layer):
raise ValueError("Each pair must have increasing indices in range.")
layers.append(layer)
if not sorts(wire_count, layers):
raise ValueError("The network leaves a binary input unsorted.")
return len(layers)
def main():
data = sys.stdin.buffer.read(MAX_BYTES + 1)
try:
if len(data) > MAX_BYTES:
raise ValueError("The submission exceeds the byte limit.")
if not data.isascii() or any(c < 32 and c not in (9, 10, 13) for c in data):
raise ValueError("Use plain ASCII text.")
score = verify(data)
except ValueError as error:
result = {"valid": False, "score": None, "message": str(error)}
else:
result = {"valid": True, "score": score, "message": "The construction is valid."}
print(json.dumps(result, separators=(",", ":")))
if __name__ == "__main__":
main()