Read the checking program (68 lines of Python)
"""Check an ordered comparator list sorts every binary input and count its comparators."""
import json
import sys
MAX_BYTES = 1848
WIRES = 22
MAX_COMPARATORS = 231
def sorts(wire_count, comparators):
# Zero-one principle: it suffices to sort every binary input.
# Bit j of each integer stores the value on its wire for input j.
byte_count = ((1 << wire_count) + 7) // 8
wires = []
for wire in range(wire_count):
if wire < 3:
masks = (0xAA, 0xCC, 0xF0)
column = bytes([masks[wire]]) * byte_count
else:
block = 1 << (wire - 3)
column = (bytes(block) + b"\xff" * block) * (byte_count // (2 * block))
wires.append(int.from_bytes(column, "little"))
for left, right in comparators:
low, high = wires[left], wires[right]
wires[left], wires[right] = low & high, low | high
# A 1 immediately to the left of a 0 is a descending pair.
return all(left & ~right == 0 for left, right in zip(wires, wires[1:]))
def verify(data):
lines = data.splitlines()
if not 1 <= len(lines) <= MAX_COMPARATORS:
raise ValueError("The submission has the wrong number of comparators.")
comparators = []
for line in lines:
tokens = line.split()
if len(tokens) != 2:
raise ValueError("Each comparator must specify exactly two wire indices.")
if any(len(t) > 2 or not t.isdigit() for t in tokens):
raise ValueError("Wire indices must be nonnegative decimal integers.")
left, right = map(int, tokens)
if not 0 <= left < right < WIRES:
raise ValueError("Comparator indices must be distinct, increasing, and in range.")
comparators.append((left, right))
if not sorts(WIRES, comparators):
raise ValueError("The network leaves at least one binary input unsorted.")
return len(comparators)
def main():
data = sys.stdin.buffer.read(MAX_BYTES + 1)
try:
if len(data) > MAX_BYTES:
raise ValueError("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()