Created
January 7, 2016 02:43
-
-
Save slackorama/28ee736134692321b3fe to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
board = [[0 for x in xrange(1000)] for x in xrange(1000)] | |
on_off = re.compile(r'(toggle|turn on|turn off) ([0-9]+),([0-9]+) through ([0-9]+),([0-9]+)') | |
def count_on(board): | |
return sum([sum(row) for row in board]) | |
def toggle(v): | |
if v == 1: | |
return 0 | |
return 1 | |
def do_line(line): | |
m = on_off.match(line) | |
if m: | |
action = m.group(1) | |
if action == 'turn on': | |
val = lambda x: 1 | |
elif action == 'turn off': | |
val = lambda x: 0 | |
else: | |
val = toggle | |
start_x = int(m.group(2)) | |
start_y = int(m.group(3)) | |
end_x = int(m.group(4)) + 1 | |
end_y = int(m.group(5)) + 1 | |
for x in range(start_x, end_x): | |
for y in range(start_y, end_y): | |
# print('{},{}'.format(x,y)) | |
board[x][y] = val(board[x][y]) | |
do_line('turn on 0,0 through 999,999') | |
assert count_on(board) == 1000000 | |
do_line('toggle 0,0 through 999,0') | |
assert count_on(board) == 999000 | |
do_line('turn on 0,0 through 999,999') | |
assert count_on(board) == 1000000 | |
do_line('turn off 499,499 through 500,500') | |
assert count_on(board) == 999996 | |
# reset board | |
do_line('turn off 0,0 through 999,999') | |
with open('inst.txt') as f: | |
for l in f: | |
do_line(l) | |
print(count_on(board)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment