From 2b0ef33a08fe3e591d91f9eb534ebbc578b657a6 Mon Sep 17 00:00:00 2001 From: Andrew Ekstedt Date: Wed, 14 Dec 2022 22:50:07 -0800 Subject: [PATCH] day 15 python wip optimizations --- day15/sol.py | 57 +++++++++++++++++++++++++++++++++++----------------- 1 file changed, 39 insertions(+), 18 deletions(-) diff --git a/day15/sol.py b/day15/sol.py index 1b72943..f154faf 100644 --- a/day15/sol.py +++ b/day15/sol.py @@ -23,27 +23,48 @@ for sx,sy,bx,by in data: print(len(none)) -# find the closest sensor to x,y within dist -def mindist(x,y): - for sx,sy,bx,by in data: - dx = abs(sx-bx) - dy = abs(sy-by) - dist = dx+dy - dx = abs(x-sx) - dy = abs(y-sy) - d2 = dx+dy - if d2 <= dist: - yield dist-d2 +objs = [] +for sx,sy,bx,by in data: + dist = abs(sx-bx) + abs(sy-by) + objs.append((sx,sy,dist)) -for y in range(0, 4000000+1): +# find the closest sensor to x,y within dist +def mindist(x,y, objs=objs): + for sx,sy,dist in yobjs: + d = abs(x-sx) + abs(y-sy) + if d <= dist: + yield dist-d + +# y=2573243 +Y = 2500000 +Y = 0 + +objs.sort() + +for y in range(Y, 4000000+1): + ranges = [] + for sx,sy,dist in objs: + dy = abs(y-sy) + if dy <= dist: + dx = dist - dy + ranges.append((sx-dx,sx+dx)) + ranges.sort() x = 0 - while x <= 4000000: - for d in mindist(x,y): - x += d+1 + for a,b in ranges: + if b < x: + continue + if x < a: + print(x,y,"=",x*4000000+y) break - else: - print(x,y) + x = b+1 + if x > 4000000: break - if y % 10000 == 0: + #try: + # d = max(mindist(x,y,objs=yobjs)) + # x += d+1 + #except ValueError: + # print(x,y) + # break + if y % 100000 == 0: print(y)