Skip to content

Instantly share code, notes, and snippets.

@unbibium
Created December 16, 2021 03:56
Show Gist options
  • Save unbibium/72b5139bb2fc4135044774fd93a59cf0 to your computer and use it in GitHub Desktop.
Save unbibium/72b5139bb2fc4135044774fd93a59cf0 to your computer and use it in GitHub Desktop.
faulty 2021 day 15
#!/usr/bin/env python3
#
# https://adventofcode.com/2021/day/15
import sys, os,math
from collections import deque
class Maze:
def __init__(self, lines, size=1):
self.size = size
self.grid = {}
for y, line in enumerate(lines):
self.grid.update( { (x, y): int(ch)
for x, ch in enumerate(line.rstrip()) } )
self.yrange = len(lines)
self.xrange = len(lines[0].rstrip())
self.exit = (self.xrange-1, self.yrange-1)
def find_all_minimums(self):
checked = { (0,0): 0 } # trying really hard not to count origin
to_check = { (0,1), (1,0) }
while to_check:
checking, to_check = to_check, set()
for pos in checking:
for n in self.neighbors(pos):
if n in checked:
checked[pos] = min(checked.get(pos, math.inf), self[pos] + checked[n] )
else:
to_check.add(n)
for y in range(10):
for x in range(10):
print("%3d" % checked[ (x,y) ], end='')
print()
return checked[ self.exit ]
def neighbors(self, pos):
if pos[0]>0: yield (pos[0]-1, pos[1])
if pos[1]>0: yield (pos[0], pos[1]-1)
if pos[0]<self.exit[0]: yield (pos[0]+1, pos[1])
if pos[1]<self.exit[1]: yield (pos[0], pos[1]+1)
def __getitem__(self, xy):
return self.grid[xy]
# changes for part 2
class BigMaze(Maze):
def __init__(self, lines):
super().__init__(lines)
self.exit = ((self.xrange*5)-1, (self.yrange*5)-1)
def __getitem__(self, xy):
x, y = xy
if x==y==0: return 0 #origin has no risk
px, cx = divmod(x,self.xrange)
py, cy = divmod(y,self.yrange)
if not (px or py):
return self.grid[xy]
return (self.grid[(cx,cy)]-1 + px + py) % 9 + 1
if __name__ == '__main__':
if len(sys.argv)<2:
print("Usage",sys.argv[0],"filename")
sys.exit(1)
with open(sys.argv[1]) as f:
lines = f.readlines()
maze = Maze(lines)
print("part1:", maze.find_all_minimums(), " ex == 40; p1 == 685")
maze5 = BigMaze(lines)
print("part2:", maze5.find_all_minimums(), " ex == 315; p2 < 3011")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment