#!/usr/bin/env python3 """Exact count of distinct radius-1 circles through at least three rational points. Route: the circle equation. A circle is written x^2 + y^2 + D x + E y + F = 0. For a non-collinear triple P1, P2, P3, subtracting P1's equation from P2's and P3's gives the 2 by 2 linear system (x2-x1) D + (y2-y1) E = (x1^2+y1^2) - (x2^2+y2^2) (x3-x1) D + (y3-y1) E = (x1^2+y1^2) - (x3^2+y3^2). Its determinant is the 3 by 3 determinant of the stacked system [[x1,y1,1],[x2,y2,1],[x3,y3,1]], so it vanishes exactly when the triple is collinear; such triples are skipped. Otherwise (D,E) is solved by Cramer's rule over the rationals and F follows from P1. The centre is (-D/2,-E/2) and the radius is exactly 1 iff D^2 + E^2 - 4F == 4. Candidate centres are deduplicated exactly and recounted against every input point, also exactly. All decisions use Python integers and fractions.Fraction; no float ever enters a comparison or an arithmetic step (float coordinates are rejected up front). """ import json import re import sys from fractions import Fraction # Exact arithmetic should not be limited by CPython's decimal-string guard. if hasattr(sys, "set_int_max_str_digits"): try: sys.set_int_max_str_digits(0) except ValueError: pass FRACTION_RE = re.compile(r"-?[0-9]+/[0-9]+") class InvalidConfig(Exception): pass def parse_coordinate(value): """Return the exact Fraction for one JSON coordinate, or raise InvalidConfig.""" if isinstance(value, bool): raise InvalidConfig("boolean coordinate") if isinstance(value, int): return Fraction(value, 1) if isinstance(value, float): raise InvalidConfig("floating-point coordinate") if isinstance(value, str): if FRACTION_RE.fullmatch(value) is None: raise InvalidConfig("coordinate string is not exactly a fraction p/q") num_text, den_text = value.split("/") num = int(num_text) den = int(den_text) if den <= 0: raise InvalidConfig("fraction denominator is not positive") return Fraction(num, den) raise InvalidConfig("coordinate is neither an integer nor a fraction string") def parse_configuration(document): """Validate the document and return its list of exact (x, y) points.""" if not isinstance(document, dict): raise InvalidConfig("top level is not a JSON object") if "schema" not in document: raise InvalidConfig("missing schema") schema = document["schema"] if type(schema) is not int or schema != 1: raise InvalidConfig("schema must be the integer 1") if "points" not in document: raise InvalidConfig("missing points") raw_points = document["points"] if not isinstance(raw_points, list): raise InvalidConfig("points is not a list") n = len(raw_points) if n < 3 or n > 80: raise InvalidConfig("number of points must be between 3 and 80") points = [] seen = set() for index, raw in enumerate(raw_points): if not isinstance(raw, list) or len(raw) != 2: raise InvalidConfig("point %d is not a pair" % index) point = (parse_coordinate(raw[0]), parse_coordinate(raw[1])) if point in seen: raise InvalidConfig("duplicate point at index %d" % index) seen.add(point) points.append(point) return points def count_unit_circles(points): """Return the sorted list of exact centres of unit circles through >=3 points.""" n = len(points) xs = [point[0] for point in points] ys = [point[1] for point in points] squares = [xs[i] * xs[i] + ys[i] * ys[i] for i in range(n)] four = Fraction(4, 1) one = Fraction(1, 1) two = Fraction(2, 1) # Any two points of a unit circle are at distance at most 2. This exact # necessary condition only prunes triples that cannot lie on such a circle. near = [[False] * n for _ in range(n)] for i in range(n): xi = xs[i] yi = ys[i] for j in range(i + 1, n): dx = xs[j] - xi dy = ys[j] - yi if dx * dx + dy * dy <= four: near[i][j] = True near[j][i] = True centres = set() for i in range(n): xi = xs[i] yi = ys[i] si = squares[i] near_i = near[i] for j in range(i + 1, n): if not near_i[j]: continue xj = xs[j] yj = ys[j] dx2 = xj - xi dy2 = yj - yi b2 = si - squares[j] near_j = near[j] for k in range(j + 1, n): if not near_i[k] or not near_j[k]: continue dx3 = xs[k] - xi dy3 = ys[k] - yi det = dx2 * dy3 - dx3 * dy2 if det == 0: # The 2x2 determinant equals the 3x3 stacked determinant, # so this is exactly the collinear case: no circle. continue b3 = si - squares[k] d_coef = (b2 * dy3 - b3 * dy2) / det e_coef = (dx2 * b3 - dx3 * b2) / det f_coef = -(si + d_coef * xi + e_coef * yi) if d_coef * d_coef + e_coef * e_coef - 4 * f_coef == 4: centres.add((-d_coef / two, -e_coef / two)) # Exact recount of incidences against all input points. result = [] for cx, cy in centres: hits = 0 for x, y in points: dx = x - cx dy = y - cy if dx * dx + dy * dy == one: hits += 1 if hits >= 3: break if hits >= 3: result.append((cx, cy)) result.sort() return result def format_fraction(value): """Canonical output: 'a' when integral, otherwise reduced 'p/q' with q > 1.""" if value.denominator == 1: return str(value.numerator) return "%d/%d" % (value.numerator, value.denominator) def main(argv): if len(argv) != 2: print("usage: count.py ", file=sys.stderr) return 1 path = argv[1] try: with open(path, "r", encoding="utf-8") as handle: text = handle.read() except OSError as exc: print("cannot read configuration: %s" % exc, file=sys.stderr) return 1 except ValueError: print("invalid configuration: file is not readable UTF-8 text", file=sys.stderr) return 1 try: try: document = json.loads(text) except Exception: raise InvalidConfig("file is not valid JSON") points = parse_configuration(document) centres = count_unit_circles(points) except InvalidConfig as exc: print("invalid configuration: %s" % exc, file=sys.stderr) return 1 output = { "n": len(points), "unit_circles": len(centres), "centers": [[format_fraction(cx), format_fraction(cy)] for cx, cy in centres], } print(json.dumps(output, separators=(",", ":"))) return 0 if __name__ == "__main__": sys.exit(main(sys.argv))