In this series, I'll share my progress with the 2023 version of Advent of Code.
Check the first post for a short intro to this series.
You can also follow my progress on GitHub.
December 12th
The puzzle of day 12 is again a breeze for part one, and a real hair-puller for part two.
My pitfall for this puzzle: Stuck on part two. Obviously, the implementation of part one is not going to cut it. I'll try to get back to this puzzle at a later time.
UPDATE: I finally managed this finish the second part. Considering how straightforward the code is, I can't believe this took me so long. Full disclosure: I consulted Reddit for some guidance because I wandered off in the wrong direction myself.
Solution here, do not click if you want to solve the puzzle first yourself
#!/usr/bin/env python3
import re
from functools import cache
rows = []
with open('input-small.txt') as infile:
lines = infile.readlines()
for line in lines:
parts = line.strip().split(' ')
springs = parts[0]
groups = [int(g) for g in parts[1].split(',')]
rows.append((springs, groups))
def generate(s):
result = []
if '?' not in s:
result.append(s)
else:
result.extend(generate(s.replace('?', '#', 1)))
result.extend(generate(s.replace('?', '.', 1)))
return result
def is_valid(springs, groups):
spring_groups = [len(p) for p in re.split('[.]+', springs) if p != '']
g = list(groups)
return spring_groups == g
@cache
def check(s, groups):
if len(groups) == 0:
if '#' not in s:
return 1
else:
return 0
s = s.strip('.')
dot_index = s.find('.')
question_index = s.find('?')
if question_index >= 0 and (question_index < dot_index or dot_index < 0):
return \
check(s.replace('?', '#', 1), groups) + \
check(s.replace('?', '.', 1), groups)
else:
if dot_index < 0 and len(s) == groups[0]:
return check('', groups[1:])
elif dot_index == groups[0]:
return check(s[dot_index:], groups[1:])
else:
return 0
total = 0
for r in rows:
springs = ''
groups = []
for i in range(5):
springs += r[0]
springs += '?' if i < 4 else ''
groups.extend(r[1])
valid = check(springs, tuple(groups))
total += valid
print(total)
That's it! See you again tomorrow!
Top comments (0)