|
5 | 5 | See full progress at https://github.com/savbell/advent-of-code-one-liners
|
6 | 6 | '''
|
7 | 7 |
|
| 8 | +from functools import cache |
8 | 9 | from itertools import product
|
9 | 10 | import re
|
10 | 11 |
|
@@ -49,7 +50,32 @@ def count_permutations(symbols):
|
49 | 50 |
|
50 | 51 |
|
51 | 52 | ######################## 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)) |
53 | 79 |
|
54 | 80 | ########################## 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