99from aoc .common import InputData
1010from aoc .common import SolutionBase
1111from aoc .common import aoc_samples
12- from aoc .common import log
1312
1413Input = InputData
1514Output1 = int
@@ -28,62 +27,27 @@ class Solution(SolutionBase[Input, Output1, Output2]):
2827 def parse_input (self , input_data : InputData ) -> Input :
2928 return input_data
3029
30+ def solve_line (self , line : str , digits : int ) -> int :
31+ @cache
32+ def dfs (start : int , left : int ) -> int :
33+ if left == 0 :
34+ return 0
35+ if len (line ) - start == left :
36+ return int (line [start :])
37+ a = int (line [start ]) * 10 ** (left - 1 ) + dfs (start + 1 , left - 1 )
38+ b = dfs (start + 1 , left )
39+ return max (int (a ), b )
40+
41+ return dfs (0 , digits )
42+
43+ def solve (self , inputs : Input , digits : int ) -> int :
44+ return sum (self .solve_line (line , digits ) for line in inputs )
45+
3146 def part_1 (self , inputs : Input ) -> Output1 :
32- ans = 0
33- for line in inputs :
34- first = max (enumerate (line [:- 1 ]), key = lambda e : (e [1 ], - e [0 ]))
35- second = max (
36- enumerate (line [first [0 ] + 1 :]), key = lambda e : (e [1 ], - e [0 ])
37- )
38- ans += int (first [1 ] + second [1 ])
39- return ans
47+ return self .solve (inputs , digits = 2 )
4048
4149 def part_2 (self , inputs : Input ) -> Output2 :
42- @cache
43- def dfs (left : int , start : int ) -> int :
44- if start >= len (line ):
45- return 0
46- if left == 1 :
47- if start == len (line ) - 1 :
48- return int (line [- 1 ])
49- return max (int (line [start ]), dfs (1 , start + 1 ))
50- cur = dfs (left - 1 , start + 1 )
51- nxt = dfs (left , start + 1 )
52- if cur > 0 :
53- return max (int (line [start ] + str (cur )), nxt )
54- return nxt
55-
56- dfs .cache_clear ()
57- line = "1"
58- test = dfs (1 , 0 )
59- assert test == 1 , test
60- dfs .cache_clear ()
61- line = "21"
62- test = dfs (1 , 0 )
63- assert test == 2 , test
64- dfs .cache_clear ()
65- line = "12"
66- test = dfs (1 , 0 )
67- assert test == 2 , test
68- dfs .cache_clear ()
69- line = "12"
70- test = dfs (2 , 0 )
71- assert test == 12 , test
72- dfs .cache_clear ()
73- line = "123"
74- test = dfs (2 , 0 )
75- assert test == 23 , test
76- dfs .cache_clear ()
77- line = "321"
78- test = dfs (2 , 0 )
79- assert test == 32 , test
80- ans = 0
81- for line in inputs : # noqa:B007
82- dfs .cache_clear ()
83- best = dfs (12 , 0 )
84- log (best )
85- ans += best
86- return ans
50+ return self .solve (inputs , digits = 12 )
8751
8852 @aoc_samples (
8953 (
0 commit comments