#!/usr/bin/python3 import fileinput import re sensors = [] beacons = set() xmin, xmax = 0, 0 maxdistance = 0 r = r'Sensor at x=(-?\d+), y=(-?\d+).*beacon is at x=(-?\d+), y=(-?\d+)' for line in fileinput.input(): result = re.search(r, line) sx, sy, bx, by = list(map(int, result.groups())) if sx < xmin: xmin = sx if bx < xmin: xmin = bx if sx > xmax: xmax = sx if bx > xmax: xmax = bx dist = abs(bx-sx) + abs(by-sy) if dist > maxdistance: maxdistance = dist sensors.append((sx,sy,dist)) beacons.add((bx,by)) # Iterate over a row. The farthest west we can go is the westernmost X # coordinate we've seen (xmin) minus the largest Manhattan distance we've seen. # The farthest east is xmax + maxdistance. # And we have to add 1 because Python. y = 2000000 total = 0 print('xmin = %d, max = %d, maxdistance = %d' % (xmin, xmax, maxdistance)) for x in range(xmin - maxdistance, xmax + maxdistance + 1): if (x,y) in beacons: continue # Check whether this coordinate is within coverage range of any sensor. match = False for s in sensors: sx, sy, range = s dist = abs(sx-x) + abs(sy-y) if dist <= range: total += 1 # print('(%d,%d) in range of sensor(%d,%d,%d) dist %d' % (x, y, sx, sy, range, dist)) match = True break # if not match: # print('(%d,%d) not covered' % (x, y)) print(total)