Day 9 - Advent of Code 2016
Working solutions for the day 9 puzzles.
Part One
""" day_09_01.py """
# usage: python3 day_09_01.py < input
import sys
def length(text):
""" calculate uncompressed length """
raw = list(text)
count = 0
while True:
try:
x = raw.pop(0)
except IndexError:
break
if x.isspace():
continue
if x == '(':
width = ''
while (x := raw.pop(0)) != 'x':
width += x
repeat = ''
while (x := raw.pop(0)) != ')':
repeat += x
for _ in range(int(width)):
raw.pop(0)
count += int(width) * int(repeat)
else:
count += 1
return count
assert length('ADVENT') == 6
assert length('A(1x5)BC') == 7
assert length('(3x3)XYZ') == 9
assert length('A(2x2)BCD(2x2)EFG') == 11
assert length('(6x1)(1x3)A') == 6
assert length('X(8x2)(3x3)ABCY') == 18
in_file = sys.stdin.read()
print(length(in_file))
Part Two
""" day_09_02.py """
# usage: python3 day_09_02.py < input
from collections import deque
import sys
def length(text):
""" calculate uncompressed length v2 """
raw = deque(text)
count = 0
while True:
try:
x = raw.popleft()
except IndexError:
break
if x.isspace():
continue
if x == '(':
width = ''
while (x := raw.popleft()) != 'x':
width += x
repeat = ''
while (x := raw.popleft()) != ')':
repeat += x
pattern = deque()
for _ in range(int(width)):
pattern.append(raw.popleft())
raw.extendleft(reversed(int(repeat) * pattern))
else:
count += 1
return count
assert length('(3x3)XYZ') == 9
assert length('X(8x2)(3x3)ABCY') == 20
assert length('(27x12)(20x12)(13x14)(7x10)(1x12)A') == 241920
assert length('(25x3)(3x3)ABC(2x3)XY(5x2)PQRSTX(18x9)(3x2)TWO(5x7)SEVEN') == 445
in_file = sys.stdin.read()
print(length(in_file))