In [1]:
from collections import namedtuple
In [2]:
class Screen:
def __init__(self, rows=6, cols=50):
self.rows = rows
self.cols = cols
self.screen = [[0 for _ in range(cols)] for _ in range(rows)]
def load(self, instruction):
if instruction.startswith('rect'):
cols, rows = [range(int(i)) for i in instruction.split()[1].split('x')]
for row in rows:
for col in cols:
self._turn_on(row, col)
else:
_, axis, position, _, movement = instruction.split()
position = int(position.split('=')[1])
movement = int(movement)
if axis == 'row':
self._rotate_row(position, movement)
else:
self._rotate_column(position, movement)
#for row in range(self.rows):
# for _ in range(int(movement)):
# print(movement)
# self._switch(row % self.rows, position)
def _set_value(self, row, column, value):
self.screen[row][column] = value
def _turn_on(self, row, column):
self._set_value(row, column, 1)
def _turn_off(self, row, column):
self._set_value(row, column, 0)
def _switch(self, row, column):
self.screen[row][column] = 0 if self.screen[row][column] else 1
def _rotate_column(self, column, movement):
values = [self.screen[r][column] for r in range(self.rows)]
for index, row in enumerate(range(self.rows)):
self._set_value(row, column, values[(index - movement) % self.rows])
def _rotate_row(self, row, movement):
values = [self.screen[row][c] for c in range(self.cols)]
for index, col in enumerate(range(self.cols)):
self._set_value(row, col, values[(index - movement) % self.cols])
def print_screen(self):
for r in self.screen:
print(''.join(['#' if c else '.' for c in r]))
def get_screen(self):
return self.screen
def get_lit_pixels(self):
return sum([sum(i) for i in self.screen])
In [3]:
# Test
screen = Screen(rows=3, cols=7)
screen.load('rect 3x2')
screen.load('rotate column x=1 by 1')
screen.load('rotate row y=0 by 4')
screen.load('rotate column x=1 by 1')
assert screen.get_screen() == [[0, 1, 0, 0, 1, 0, 1], [1, 0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0]]
assert screen.get_lit_pixels() == 6
In [4]:
data = [line.strip() for line in open('data/day_8.txt', 'r')]
screen = Screen()
for instruction in data:
screen.load(instruction)
screen.get_lit_pixels()
Out[4]:
In [5]:
screen.print_screen()