"""3SUM, the question itself: among n numbers, do three of them sum to zero? No data file: the figure makes a small instance (seeded) and solves it by brute force, keeping the first seed whose instance has exactly one such triple, so the three numbers drawn really are the only answer. The numbers sit on the line where they fall; the arcs walk from 0 by each of the three in turn and come back to 0. """ import random from pathlib import Path import kit N, LO, HI = 18, -60, 60 for seed in range(1000): rnd = random.Random(seed) nums = rnd.sample([v for v in range(LO, HI + 1) if v], N) triples = [(a, b, c) for i, a in enumerate(nums) for j, b in enumerate(nums[i + 1:], i + 1) for c in nums[j + 1:] if a + b + c == 0] if len(triples) == 1 and min(abs(v) for v in triples[0]) > 8: break else: raise SystemExit('no instance with exactly one triple') a, b, c = sorted(triples[0]) assert a + b + c == 0 base, X_ = 232.0, lambda v: 320 + v * (288 / HI) body = kit.line(X_(LO - 4), base, X_(HI + 4), base, 'faint-s', 3) body += kit.line(X_(0), base - 14, X_(0), base + 14, 'faint-s', 3) # the walk: start at 0, step by each of the three in turn, and land back on 0 walk = [0, c, c + a, 0] for i, (p, q) in enumerate(zip(walk, walk[1:])): y = base - 136 + 42 * i head = 11 if q > p else -11 body += kit.line(X_(p), y, X_(q), y, 'f-s', 5) body += kit.path(f'M{kit.f1(X_(q) - head)} {kit.f1(y - 9)}L{kit.f1(X_(q))} {kit.f1(y)}' f'L{kit.f1(X_(q) - head)} {kit.f1(y + 9)}', 'f-s', 5) body += kit.line(X_(q), y + 6, X_(q), base - 14 if q else base + 14, 'faint-s', 2, ' stroke-dasharray="3 6"') body += ''.join(kit.dot(X_(v), base, 9, 'ink') for v in nums if v not in (a, b, c)) body += ''.join(kit.dot(X_(v), base, 15, 'f') for v in (a, b, c)) sums = f'{a}' + ''.join(f' + {v}' if v > 0 else f' - {-v}' for v in (b, c)) label = f'{N} numbers · {sums} = 0 · the only triple' kit.write(__file__, 'computer-science', body, label, f'{N} numbers on a line; the only three of them that sum to zero are {a}, {b} and {c}') print(label, 'seed', seed)