#!/usr/bin/env python3 """Independent second implementation, used only to cross-check count.py. Usage: python3 altcount.py It answers the same problem with a different algorithm and different parsing code, so that agreement between the two is evidence about the mathematics and not about one shared code path. Algorithm: enumerate PAIRS instead of triples. Scale the points to integers (Xi, Yi) with common denominator L as usual, so a unit circle has radius L in the scaled plane. For a pair with difference (dx, dy) and q = dx^2 + dy^2, a circle of radius L through both points has its center on the perpendicular bisector through the midpoint M, at distance sqrt(L^2 - q/4) from M, i.e. C = M +- (-dy, dx) * sqrt(4 L^2 - q) / (2 sqrt(q)). Writing m = 4 L^2 - q, the offset is rational exactly when m/q is the square of a rational, that is when m*q is a perfect square, m*q = p^2; then C = ( (q*sx -+ dy*p) / (2 q), (q*sy +- dx*p) / (2 q) ), where (sx, sy) = 2M is the componentwise sum of the two points. Only these rational centers can carry three rational points (three rational points have a rational circumcenter), so this enumeration is complete for the problem; each surviving center is kept iff at least three of the points satisfy the integer incidence test (m'*Xi - nx)^2 + (m'*Yi - ny)^2 == (m'*L)^2 after reduction. """ import json import re import sys from functools import cmp_to_key from math import gcd, isqrt USAGE = "usage: python3 altcount.py " FRACTION = re.compile(r"[+-]?[0-9]+/[0-9]+") class Invalid(Exception): pass def parse_coord(value, where): if type(value) is bool: raise Invalid(where + ": boolean coordinate") if type(value) is int: return (value, 1) if type(value) is float: raise Invalid(where + ": floating-point coordinate") if type(value) is not str: raise Invalid(where + ": coordinate is not a rational") if FRACTION.fullmatch(value) is None: raise Invalid(where + ": %r is not of the form p/q" % (value,)) p_text, q_text = value.split("/") p = int(p_text) q = int(q_text) if q == 0: raise Invalid(where + ": zero denominator") g = gcd(abs(p), q) return (p // g, q // g) def scale_points(points): n = len(points) scale = 1 for px, py in points: scale = scale // gcd(scale, px[1]) * px[1] scale = scale // gcd(scale, py[1]) * py[1] xs = [px[0] * (scale // px[1]) for px, py in points] ys = [py[0] * (scale // py[1]) for px, py in points] return scale, xs, ys def solve(points): n = len(points) scale, xs, ys = scale_points(points) four_l2 = 4 * scale * scale candidates = set() for i in range(n - 1): xi = xs[i] yi = ys[i] for j in range(i + 1, n): dx = xs[j] - xi dy = ys[j] - yi q = dx * dx + dy * dy if q > four_l2: continue # farther apart than the diameter m = four_l2 - q p = isqrt(m * q) if p * p != m * q: continue # both centers irrational sx = xi + xs[j] sy = yi + ys[j] den = 2 * q for sign in (1, -1): nx = q * sx - sign * dy * p ny = q * sy + sign * dx * p g = gcd(gcd(abs(nx), abs(ny)), den) nx //= g ny //= g den_g = den // g if den_g < 0: nx = -nx ny = -ny den_g = -den_g candidates.add((nx, ny, den_g)) centers = [] for nx, ny, den in candidates: target = den * den * scale * scale count = 0 for idx in range(n): u = den * xs[idx] - nx v = den * ys[idx] - ny if u * u + v * v == target: count += 1 if count < 3: continue total = den * scale gx = gcd(abs(nx), total) gy = gcd(abs(ny), total) centers.append(((nx // gx, total // gx), (ny // gy, total // gy))) centers.sort(key=cmp_to_key(compare)) return centers def compare(left, right): for axis in (0, 1): (ln, ld) = left[axis] (rn, rd) = right[axis] diff = ln * rd - rn * ld if diff: return -1 if diff < 0 else 1 return 0 def render(pair): num, den = pair return str(num) if den == 1 else "%d/%d" % (num, den) def read_points(document): if not isinstance(document, dict): raise Invalid("not a JSON object") schema = document.get("schema") if type(schema) is not int or schema != 1: raise Invalid("schema must be 1") raw = document.get("points") if not isinstance(raw, list): raise Invalid("points must be a list") if not 3 <= len(raw) <= 80: raise Invalid("need 3 to 80 points") points = [] seen = set() for index, item in enumerate(raw): if not isinstance(item, list) or len(item) != 2: raise Invalid("point %d is not a pair" % index) px = parse_coord(item[0], "point %d x" % index) py = parse_coord(item[1], "point %d y" % index) if (px, py) in seen: raise Invalid("point %d duplicates an earlier point" % index) seen.add((px, py)) points.append((px, py)) return len(points), points def main(argv): if len(argv) != 2: sys.stderr.write(USAGE + "\n") return 1 try: with open(argv[1], "rb") as handle: blob = handle.read() except OSError as exc: sys.stderr.write("cannot read %s: %s\n" % (argv[1], exc.strerror or exc)) return 1 try: document = json.loads(blob) except (ValueError, RecursionError) as exc: sys.stderr.write("not valid JSON: %s\n" % (exc,)) return 1 try: _, points = read_points(document) except Invalid as exc: sys.stderr.write("%s\n" % (exc,)) return 1 centers = solve(points) sys.stdout.write(json.dumps({ "n": len(points), "unit_circles": len(centers), "centers": [[render(cx), render(cy)] for cx, cy in centers], }) + "\n") return 0 if __name__ == "__main__": sys.exit(main(sys.argv))