@@ -41,10 +41,15 @@ class Day13 extends Day
41
41
public function solvePart1 (mixed $ input ): int |string |null
42
42
{
43
43
return $ this ->parseInput ($ input )
44
+ // compare each pair and return the comparison result
44
45
->map (fn (array $ pair ): int => $ this ->compare ($ pair [0 ], $ pair [1 ]))
46
+ // filter for the pairs that are in the right order
45
47
->filter (fn (int $ comparison ): bool => -1 === $ comparison )
48
+ // get the keys of the pairs that are in the right order
46
49
->keys ()
50
+ // map the keys to their position in the array + 1 (since we want 1-indexed positions)
47
51
->map (fn (int $ key ): int => $ key + 1 )
52
+ // sum the keys
48
53
->sum ();
49
54
}
50
55
@@ -53,11 +58,22 @@ public function solvePart1(mixed $input): int|string|null
53
58
*/
54
59
public function solvePart2 (mixed $ input ): int |string |null
55
60
{
56
- $ input = $ this ->parseInput ($ input );
57
-
58
- // todo: implement solution for Part 2
59
-
60
- return null ;
61
+ return $ this ->parseInput ($ input )
62
+ // flattern the array so it's no longer in pairs
63
+ ->flatten (1 )
64
+ // add the divider packets
65
+ ->push ([[2 ]], [[6 ]])
66
+ // sort the packets using the compare function
67
+ ->sort (fn (array $ left , array $ right ): int => $ this ->compare ($ left , $ right ))
68
+ ->values ()
69
+ // filter for the divider packets
70
+ ->filter (fn (array $ item ): bool => $ item === [[2 ]] || $ item === [[6 ]])
71
+ // get the keys of the divider packets
72
+ ->keys ()
73
+ // map the keys to their position in the array + 1 (since we want 1-indexed positions)
74
+ ->map (fn (int $ key ): int => $ key + 1 )
75
+ // reduce the keys to a single value by multiplying them together
76
+ ->reduce (fn (int $ carry , int $ item ): int => $ carry * $ item , 1 );
61
77
}
62
78
63
79
/**
0 commit comments