Skip to content

Commit f2857cb

Browse files
committed
complete day 13 part 2
1 parent 365ca48 commit f2857cb

File tree

1 file changed

+21
-5
lines changed

1 file changed

+21
-5
lines changed

src/Days/Day13.php

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -41,10 +41,15 @@ class Day13 extends Day
4141
public function solvePart1(mixed $input): int|string|null
4242
{
4343
return $this->parseInput($input)
44+
// compare each pair and return the comparison result
4445
->map(fn (array $pair): int => $this->compare($pair[0], $pair[1]))
46+
// filter for the pairs that are in the right order
4547
->filter(fn (int $comparison): bool => -1 === $comparison)
48+
// get the keys of the pairs that are in the right order
4649
->keys()
50+
// map the keys to their position in the array + 1 (since we want 1-indexed positions)
4751
->map(fn (int $key): int => $key + 1)
52+
// sum the keys
4853
->sum();
4954
}
5055

@@ -53,11 +58,22 @@ public function solvePart1(mixed $input): int|string|null
5358
*/
5459
public function solvePart2(mixed $input): int|string|null
5560
{
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);
6177
}
6278

6379
/**

0 commit comments

Comments
 (0)