Read the checking program (83 lines of Python)
"""Check a sum of rank-one terms equals the matrix multiplication tensor and count terms."""
import json
import sys
import re
from itertools import product
MAX_BYTES = 54462
SHAPE = (3, 4, 6)
MAX_TERMS = 72
PATTERN = b'-?[0-9]{1,12}'
def check_tensor(m, n, p, denominator, terms):
# Accumulate the tensor numerators with common denominator denominator**3.
stride = m * p
actual = [0] * (m * n * n * p * stride)
for left, right, output in terms:
for i, a in left:
for j, b in right:
scalar = a*b
offset = (i * n * p + j) * stride
for k, c in output:
actual[offset + k] += scalar*c
target = [0] * len(actual)
for i, j, k in product(range(m), range(n), range(p)):
left = i * n + j
right = j * p + k
output = i * p + k
target[(left * n * p + right) * stride + output] = denominator**3
return actual == target
def verify(data):
lines = data.splitlines()
if not 2 <= len(lines) <= MAX_TERMS + 1:
raise ValueError("The submission has the wrong number of terms.")
if re.fullmatch(rb"[1-9][0-9]{0,11}", lines[0]) is None:
raise ValueError("The first line must be a positive denominator of up to 12 digits.")
denominator = int(lines[0])
m, n, p = SHAPE
left_size, right_size, out_size = m*n, n*p, m*p
terms = []
for line in lines[1:]:
tokens = line.split()
if len(tokens) != left_size + right_size + out_size:
raise ValueError("Each term must specify all three coefficient vectors.")
coefficients = []
for token in tokens:
if re.fullmatch(PATTERN, token) is None:
raise ValueError("A coefficient has an invalid numerator.")
coefficients.append(int(token))
cuts = (0, left_size, left_size + right_size, len(coefficients))
term = [
[(i, value) for i, value in enumerate(coefficients[start:end]) if value]
for start, end in zip(cuts, cuts[1:])
]
if not all(term):
raise ValueError("A rank one term has an identically zero factor.")
terms.append(term)
if not check_tensor(m, n, p, denominator, terms):
raise ValueError("The rank one terms do not sum to the matrix multiplication tensor.")
return len(terms)
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()