-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay6.php
63 lines (49 loc) · 1.73 KB
/
Day6.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
<?php
declare(strict_types=1);
namespace App\Days;
use App\Contracts\Day;
use Illuminate\Support\Collection;
class Day6 extends Day
{
public const EXAMPLE1 = <<<eof
mjqjpqmgbljsphdztnvjfqwrcgsmlb
eof;
/**
* How many characters need to be processed before the first start-of-packet marker is detected?
*/
public function solvePart1(mixed $input): int|string|null
{
return $this->processBuffer($this->parseInput($input), 4);
}
/**
* How many characters need to be processed before the first start-of-message marker is detected?
*/
public function solvePart2(mixed $input): int|string|null
{
return $this->processBuffer($this->parseInput($input), 14);
}
protected function processBuffer(Collection $input, int $distinctCount): int
{
$uniqueValues = collect();
$offset = 1;
$input->each(function (string $character, int $index) use ($uniqueValues, $distinctCount, &$offset) {
// add character to our set but only keep the last 4
$uniqueValues->push($character);
if ($uniqueValues->count() > $distinctCount) {
$uniqueValues->shift();
}
if ($distinctCount === $uniqueValues->unique()->count()) {
// return the index incremented by 1, returning false terminates the loop early
$offset = ++$index;
return false;
}
return true;
});
return $offset;
}
protected function parseInput(mixed $input): Collection
{
$input = is_array($input) ? $input : explode("\n", $input);
return collect($input)->flatMap(fn ($line) => mb_str_split($line));
}
}