#!/usr/bin/env python3 """Exact check of Heilbronn configurations, scored as Tej Stead's record tables (math.tejstead.com/heilbronn) score them, for n = 20..36 points in two containers: the unit square 0 <= x, y <= 1, and the right triangle x, y >= 0, x + y <= 1. A candidate is a JSON object {"container": "square" or "triangle", "n": n, "points": [[x, y], ...]} with n points; every coordinate is a string holding a plain decimal ("0", "0.125", at most 6 digits before the point and 200 after), as the tables accept them, read as an exact rational. Its value is the smallest area of a triangle formed by three of its points (0 if three are collinear), normalized to a container of area 1 as the tables do: the square's value is that area, the triangle's is twice it. Integer arithmetic over the coordinates' common denominator; no floating-point number enters. Python >= 3.9, standard library only. """ import json import re from fractions import Fraction from itertools import combinations from math import lcm from pathlib import Path CONTAINERS = ("square", "triangle") SIZES = tuple(range(20, 37)) INSTANCES = tuple(f"{c}-n{n}" for c in CONTAINERS for n in SIZES) DECIMAL = re.compile(r"-?\d{1,6}(\.\d{1,200})?") # A value is a new record when it exceeds the record by more than this fraction of it: the tables' own tie window, so # that re-rounding a record's coordinates does not count. (The tables take any strictly larger exact value.) MIN_GAIN = Fraction(1, 10 ** 9) # instance -> the public record: its exact value ("p/q"), who found it, when the tables took it, and where it is listed RECORDS = json.loads(Path(__file__).with_name("records.json").read_text()) RECORD = {k: Fraction(v["value"]) for k, v in RECORDS.items()} class CandidateError(ValueError): pass def coordinate(value) -> Fraction: if not isinstance(value, str): raise CandidateError(f'a coordinate must be a string such as "0.125", not {type(value).__name__}') if not DECIMAL.fullmatch(value): raise CandidateError(f"{value[:40]!r} is not a plain decimal (at most 6 digits before the point, 200 after, no exponent)") return Fraction(value) def points(candidate: dict) -> tuple[str, list[tuple[Fraction, Fraction]]]: """The candidate's instance ("square-n27") and its points; raises CandidateError when it is malformed.""" container, n = candidate.get("container"), candidate.get("n") if container not in CONTAINERS: raise CandidateError('"container" must be "square" or "triangle"') if type(n) is not int or n not in SIZES: raise CandidateError(f'"n" must be one of the integers {SIZES[0]} to {SIZES[-1]}') pts = candidate.get("points") if not isinstance(pts, list) or len(pts) != n: raise CandidateError(f'"points" must be a list of {n} points') if not all(isinstance(p, list) and len(p) == 2 for p in pts): raise CandidateError("each point must be a list [x, y]") out = [(coordinate(x), coordinate(y)) for x, y in pts] for i, (x, y) in enumerate(out): inside = 0 <= x <= 1 and 0 <= y <= 1 if container == "square" else x >= 0 and y >= 0 and x + y <= 1 if not inside: raise CandidateError(f"point {i} ({pts[i][0]}, {pts[i][1]}) is outside the {container}") return f"{container}-n{n}", out def value(instance: str, pts: list[tuple[Fraction, Fraction]]) -> Fraction: q = lcm(*(c.denominator for p in pts for c in p)) P = [(int(x * q), int(y * q)) for x, y in pts] twice = min(abs((bx - ax) * (cy - ay) - (cx - ax) * (by - ay)) for (ax, ay), (bx, by), (cx, cy) in combinations(P, 3)) # the smallest area is twice / (2 q^2); the triangle (area 1/2) reports it doubled return Fraction(twice, 2 * q * q) if instance.startswith("square") else Fraction(twice, q * q) def is_record(instance: str, v: Fraction) -> bool: return v > RECORD[instance] * (1 + MIN_GAIN) def score(best: dict[str, Fraction]) -> Fraction: """The mean over all instances of best / record, where an instance counts as its record when the route has nothing better (main starts from the records, so it scores exactly 1, and any value above a record raises the score).""" return Fraction(sum(max(best.get(k, 0) / RECORD[k], 1) for k in INSTANCES), len(INSTANCES)) def scan(roots): """(file, instance, value) for each candidate (*.json with "points") under these folders, in order. For a file that is unreadable or malformed, instance is None and value says why; other JSON files are not candidates.""" for root in roots: for path in sorted(root.rglob("*.json")) if root.exists() else []: name = str(path.relative_to(root.parent)) try: candidate = json.loads(path.read_text()) except Exception as exc: yield name, None, f"unreadable ({exc})" continue if not isinstance(candidate, dict) or "points" not in candidate: continue try: instance, pts = points(candidate) except CandidateError as exc: yield name, None, f"malformed: {exc}" continue yield name, instance, value(instance, pts) def best_of(found) -> dict[str, tuple[Fraction, str]]: """Each instance's best value among scanned candidates, with the file that holds it.""" best = {} for name, instance, v in found: if instance and (instance not in best or v > best[instance][0]): best[instance] = (v, name) return best def decimal(v: Fraction, digits: int = 16) -> str: """v >= 0 in decimal, rounded down.""" text = str(v.numerator * 10 ** digits // v.denominator).rjust(digits + 1, "0") return f"{text[:-digits]}.{text[-digits:]}" def gain(v: Fraction, over: Fraction) -> str: """v's relative gain over another value.""" return f"{float(v / over - 1):+.3e}" if over else "+inf" def card(instance: str) -> str: r = RECORDS[instance] return f"{decimal(RECORD[instance])} ({r['by']}, {r['date']})"