Improve implementation of part 1.

This commit is contained in:
Bert Peters
2015-12-19 17:00:50 +01:00
parent 53c2f23ac7
commit bfd6b9c78e

View File

@@ -3,20 +3,33 @@ import fileinput
import re import re
import sys import sys
commandExpr = re.compile(r"^(toggle|turn (on|off)) (\d+),(\d+) through (\d+),(\d+)$") def compact(lightList):
last = None
newList = []
for streak in sorted(lightList):
if last is not None:
if streak[2] == last[2]:
# Repeating state, merge
last = (last[0], streak[1], last[2])
continue
else:
newList.append(last)
last = streak
newList.append(last)
return newList
def colsum(lightList):
return sum(int(state) * (stop - start + 1) for start, stop, state in lightList)
lights = [] lights = []
for x in range(1000): for x in range(1000):
lights.append([]) lights.append([(0, 999, False)])
for y in range(1000):
lights[x].append(False)
for line in fileinput.input(): for line in fileinput.input():
match = commandExpr.search(line) match = re.search(r"^(toggle|turn (on|off)) (\d+),(\d+) through (\d+),(\d+)$", line)
if not match:
print("Invalid string")
sys.exit(1)
xStart = int(match.group(3)) xStart = int(match.group(3))
yStart = int(match.group(4)) yStart = int(match.group(4))
@@ -27,16 +40,32 @@ for line in fileinput.input():
command = match.group(1) command = match.group(1)
for x in range(xStart, xEnd + 1): for x in range(xStart, xEnd + 1):
for y in range(yStart, yEnd + 1): newList = []
if command == "toggle": for start, end, state in lights[x]:
lights[x][y] = not lights[x][y] if not start <= yStart <= end and not yStart <= start <= yEnd:
elif "on" in command: # Block not in range, skip
lights[x][y] = True newList.append((start, end, state))
else: continue
lights[x][y] = False
total = 0 if start < yStart:
for row in lights: # Split the block at the start
total += sum([int(i) for i in row]) newList.append((start, yStart - 1, state))
start = yStart
if end > yEnd:
# Split the block at the end
newList.append((yEnd + 1, end, state))
end = yEnd
if "toggle" in command:
newList.append((start, end, not state))
elif "on" in command:
newList.append((start, end, True))
else:
newList.append((start, end, False))
lights[x] = compact(newList)
total = sum(colsum(x) for x in lights)
print(total) print(total)