|
| 1 | +import re |
| 2 | +from more_itertools import pairwise |
| 3 | + |
| 4 | +cityblock = lambda x1, y1, x2, y2: abs(x1-x2) + abs(y1-y2) |
| 5 | + |
| 6 | +# file_name = "test.txt" |
| 7 | +# row_part1 = 10 |
| 8 | +# xy_bounds = (0, 20) |
| 9 | + |
| 10 | +file_name = "input.txt" |
| 11 | +row_part1 = 2_000_000 |
| 12 | +xy_bounds = (0, 4_000_000) |
| 13 | + |
| 14 | +with open(file_name) as f: |
| 15 | + data = [[int(x) for x in re.findall("-?\d+", l)] for l in f] |
| 16 | + |
| 17 | +sensors_beacons = set((sx, sy) for sx, sy, _, _ in data) | set((bx, by) for _, _, bx, by in data) |
| 18 | + |
| 19 | +for row in range(*xy_bounds): |
| 20 | + intervals = [] |
| 21 | + for sx, sy, bx, by in data: |
| 22 | + d = cityblock(sx, sy, bx, by) - cityblock(sx, sy, sx, row) |
| 23 | + if d >= 0: |
| 24 | + intervals.append((sx-d, sx+d)) |
| 25 | + |
| 26 | + res = [] |
| 27 | + s, e = 0, 0 |
| 28 | + for i, ((lb1, ub1), (lb2, ub2)) in enumerate(pairwise(sorted(intervals))): |
| 29 | + if i == 0: |
| 30 | + s, e = lb1, ub1 |
| 31 | + if lb2 <= (e+1): |
| 32 | + e = max(e, ub2) |
| 33 | + else: |
| 34 | + res.append((s, e)) |
| 35 | + s, e = lb2, ub2 |
| 36 | + res.append((s, e)) |
| 37 | + |
| 38 | + if row == row_part1: |
| 39 | + n_beacons_in_row = len(set((bx, by) for _, _, bx, by in data if by == row)) |
| 40 | + print(sum([ub-lb+1 for lb, ub in res]) - n_beacons_in_row) |
| 41 | + |
| 42 | + reduced = [(lb, ub) for lb, ub in res if ub >= xy_bounds[0] and lb <= xy_bounds[1]] |
| 43 | + if len(reduced) == 1: |
| 44 | + continue |
| 45 | + |
| 46 | + x, y = reduced[0][1]+1, row |
| 47 | + if (x, y) not in sensors_beacons: |
| 48 | + print(4_000_000*x+y) |
0 commit comments