Skip to content

Commit 09d1c59

Browse files
committed
☑ Adding Day 12 Part 2 multi-line & one-line solutions!
1 parent d461dca commit 09d1c59

File tree

3 files changed

+34
-7
lines changed

3 files changed

+34
-7
lines changed

2023/day-12.py

+28-2
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
See full progress at https://github.com/savbell/advent-of-code-one-liners
66
'''
77

8+
from functools import cache
89
from itertools import product
910
import re
1011

@@ -49,7 +50,32 @@ def count_permutations(symbols):
4950

5051

5152
######################## PART 2: MULTI-LINE SOLUTION ##########################
52-
# Working on it...
53+
########## Credit to Søren Fuglede Jørgensen for the their solution!! #########
54+
######################## https://github.com/fuglede ###########################
55+
springs = [x.split() for x in q[12].strip().split('\n')]
56+
springs = [(x[0], tuple(map(int, x[1].split(',')))) for x in springs]
57+
springs =[('?'.join([x[0]] * 5) + '.', x[1] * 5) for x in springs]
58+
59+
@cache
60+
def count_permutations(symbols, counts, group_loc=0):
61+
if not symbols:
62+
return not counts and not group_loc
63+
results = 0
64+
possibilities = ['.', '#'] if symbols[0] == '?' else symbols[0]
65+
for p in possibilities:
66+
if p == '#':
67+
results += count_permutations(symbols[1:], counts, group_loc + 1)
68+
else:
69+
if group_loc > 0:
70+
if counts and counts[0] == group_loc:
71+
results += count_permutations(symbols[1:], counts[1:])
72+
else:
73+
results = results + count_permutations(symbols[1:], counts)
74+
return results
75+
76+
counts = [count_permutations(s[0], s[1]) for s in springs]
77+
78+
print('Day 12 Part 2:',sum(counts))
5379

5480
########################## PART 2: ONE-LINE SOLUTION ##########################
55-
# Haven't started yet...
81+
print('Day 12 Part 2:',sum((count_permutations:=cache(lambda symbols, counts, group_loc=0: (not (results:=0) and [(results:=results+count_permutations(symbols[1:], counts, group_loc + 1)) if p == '#' else 1 and (group_loc > 0 and (counts and counts[0] == group_loc and (results:=results+count_permutations(symbols[1:], counts[1:])))) or (group_loc == 0 and (results:=results+count_permutations(symbols[1:], counts))) if p != '#' else 1 for p in (['.', '#'] if symbols[0] == '?' else symbols[0])] and results) if symbols else not counts and not group_loc)) and [count_permutations(s[0], s[1]) for s in [('?'.join([x[0]] * 5) + '.', x[1] * 5) for x in [(x[0], tuple(map(int, x[1].split(',')))) for x in [x.split() for x in q[12].strip().split('\n')]]]]))

0 commit comments

Comments
 (0)