Skip to content

Instantly share code, notes, and snippets.

@vadim2404
Created December 15, 2023 21:49
Show Gist options
  • Save vadim2404/ee0ea252e8809607ddb08489f4e2f2c2 to your computer and use it in GitHub Desktop.
Save vadim2404/ee0ea252e8809607ddb08489f4e2f2c2 to your computer and use it in GitHub Desktop.
day12_part2.py
#!/usr/bin/env python3
from functools import cache
def solve(pattern: str, groups: list[int]) -> int:
@cache
def dp(start_pos: int, g: int) -> int:
if start_pos == len(pattern):
return int(g == len(groups))
result = 0
if pattern[start_pos] != '#':
result += dp(start_pos + 1, g)
try:
end_pos = start_pos + groups[g]
if not '.' in pattern[start_pos:end_pos] and pattern[end_pos] != '#':
result += dp(end_pos + 1, g + 1)
except IndexError:
pass
return result
return dp(0, 0)
with open("input.txt") as f:
ans = 0
for line in f:
pattern, groups = line.strip().split()
groups = list(map(int, groups.split(','))) * 5
pattern = "?".join([pattern] * 5)
ans += solve(f"{pattern}.", groups)
print(ans)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment