advent/2018/11.py
2018-12-11 22:23:03 -08:00

102 lines
3.0 KiB
Python

class Grid:
def __init__(self, serial):
self.serial = serial
self.cells = []
self.populate()
def populate(self):
for y in range(1, 301):
self.cells.append([])
for x in range(1, 301):
self.cells[y - 1].append([])
power = self.cell_power(x, y)
self.set(x, y, power)
def get(self, x, y):
return self.cells[y - 1][x - 1]
def set(self, x, y, value):
self.cells[y - 1][x - 1] = value
def cell_power(self, x, y):
rack = x + 10
p = (rack * y + self.serial) * rack
p = (p // 100) % 10 # keep only hundreds digit
return p - 5
class Cursor:
def __init__(self, parent_grid):
self.grid = parent_grid
self.x = self.y = 1
self.calc_power()
def step(self, direction):
if direction in ('right', 'left'):
axis = 'vertical'
new_x, new_y = 1, 0
elif direction in ('up', 'down'):
axis = 'horizontal'
new_x, new_y = 0, 1
if direction in ('right', 'down'):
delta_new, delta_old = 3, 0
elif direction in ('left', 'up'):
delta_new, delta_old = -1, 2
new_x, new_y = new_x * -1, new_y * -1
new_points = self.get_row(delta_new, axis)
old_points = self.get_row(delta_old, axis)
self.total_power += sum(new_points)
self.total_power -= sum(old_points)
self.x, self.y = self.x + new_x, self.y + new_y
def get_row(self, delta, axis):
points = []
if axis == 'vertical':
for y in range(self.y, self.y + 3):
points.append(self.grid.get(self.x + delta, y))
elif axis == 'horizontal':
for x in range(self.x, self.x + 3):
points.append(self.grid.get(x, self.y + delta))
return points
def jump(self, x, y):
self.x = x
self.y = y
self.calc_power()
def calc_power(self):
self.total_power = 0
for y in range(3):
for x in range(3):
self.total_power += self.grid.get(self.x + x, self.y + y)
def find_max(self):
coords, max_power = (0, 0), 0
prev_dir = 'down'
while True:
if self.total_power > max_power:
coords, max_power = (self.x, self.y), self.total_power
if self.x in (1, 298) and prev_dir != 'down': # cursor is at edge of grid
direction = 'down'
elif self.y % 2 == 0: # go left on even lines
direction = 'left'
else: # go right on odd lines
direction = 'right'
prev_dir = direction
try:
self.step(direction)
except IndexError:
break
return coords, max_power
grid = Grid(7857)
cursor = Cursor(grid)
coords, max_power = cursor.find_max()
print(f'Part 1: {coords[0]}, {coords[1]}, {max_power}')