-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay3.php
94 lines (84 loc) · 3.19 KB
/
Day3.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?php
declare(strict_types=1);
namespace App\Days;
use App\Contracts\Day;
use Illuminate\Support\Collection;
class Day3 extends Day
{
public const EXAMPLE1 = <<<eof
vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
PmmdzqPrVvPwwTWBwg
wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
ttgJtRGJQctTZtZT
CrZsJsPPZsGzwwsLwLmpwMDw
eof;
/**
* Find the item type that appears in both compartments of each rucksack. What is the sum of the priorities of those item types?
*/
public function solvePart1(mixed $input): int|string|null
{
// given rucksack always has the same number of items in each of its two compartments,
// so the first half of the characters represent items in the first compartment,
// while the second half of the characters represent items in the second compartment.
return $this->parseInput($input)
// split the characters in half for each compartment in the rucksack
->map(function (string $line) {
$halfLength = intdiv(mb_strlen($line), 2);
return [
mb_substr($line, 0, $halfLength),
mb_substr($line, $halfLength),
];
})
// find common characters
->map(function (array $parts) {
[$part1, $part2] = $parts;
$commonChars = array_intersect(
mb_str_split($part1),
mb_str_split($part2)
);
return array_unique($commonChars);
})
// convert to a priority
->map(
fn (array $commonChars) => collect($commonChars)
->map(
fn ($char) => ctype_lower($char)
? ord($char) - ord('a') + 1 // a-z: 1-26
: ord($char) - ord('A') + 27 // A-Z: 27-52
)->toArray()
)
// sum them all
->map(fn ($chunk) => array_sum($chunk))->sum();
}
public function solvePart2(mixed $input): int|string|null
{
return $this->parseInput($input)
// split into groups of 3
->chunk(3)
// identify the badge: the badge is the only item type carried by all three Elves.
->map(function (Collection $chunk) {
[$first, $second, $third] = $chunk->values();
return array_unique(array_intersect(
mb_str_split($first),
mb_str_split($second),
mb_str_split($third),
));
})
// convert to a priority
->map(
fn (array $commonChars) => collect($commonChars)
->map(
fn ($char) => ctype_lower($char)
? ord($char) - ord('a') + 1 // a-z: 1-26
: ord($char) - ord('A') + 27 // A-Z: 27-52
)->toArray()
)
// sum them all
->map(fn ($chunk) => array_sum($chunk))->sum();
}
public function getExample2(): mixed
{
return static::EXAMPLE1;
}
}