File tree 3 files changed +449
-0
lines changed
3 files changed +449
-0
lines changed Original file line number Diff line number Diff line change
1
+ from collections .abc import Iterable
2
+ from functools import cache
3
+ from itertools import groupby
4
+
5
+ from utils .file import read_input
6
+
7
+ lines = read_input (__package__ )
8
+ patterns = {pattern .strip () for pattern in lines [0 ].split ("," )}
9
+ patterns_first_letter = {key : set (group ) for key , group in groupby (sorted (patterns ), lambda x : x [0 ])}
10
+ max_lengths = {key : max (len (pattern ) for pattern in patterns ) for key , patterns in patterns_first_letter .items ()}
11
+ designs = lines [1 :]
12
+
13
+
14
+ @cache
15
+ def is_possible (design : str ) -> bool :
16
+ if not design :
17
+ return True
18
+ for i in range (len (design )):
19
+ if design [: i + 1 ] not in patterns_first_letter .get (design [0 ], []):
20
+ continue
21
+ if is_possible (design [i + 1 :]):
22
+ return True
23
+ return False
24
+
25
+
26
+ possible_designs = [design for design in designs if is_possible (design )]
27
+
28
+ # print("Part 1:", len(possible_designs))
29
+
30
+
31
+ @cache
32
+ def combinations (design : str ) -> int :
33
+ end = max_lengths .get (design [0 ], 0 )
34
+ if not end :
35
+ return 0
36
+
37
+ result = 0
38
+ for i in range (end ):
39
+ if design [: i + 1 ] not in patterns_first_letter .get (design [0 ], []):
40
+ continue
41
+ if i + 1 == len (design ):
42
+ return result + 1
43
+ result += combinations (design [i + 1 :])
44
+ return result
45
+
46
+
47
+ print ("Part 2:" , sum (combinations (d ) for d in possible_designs ))
You can’t perform that action at this time.
0 commit comments