-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay5.php
108 lines (82 loc) · 2.85 KB
/
Day5.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<?php
declare(strict_types=1);
namespace XonneX\AdventOfCode\Y2020\Solutions\Day5;
use RuntimeException;
use XonneX\AdventOfCode\Core\AbstractSolution;
class Day5 extends AbstractSolution
{
private const FRONT = 'F';
private const BACK = 'B';
private const LEFT = 'L';
private const RIGHT = 'R';
public function __construct()
{
parent::__construct(2020, 5);
}
protected function partOne(string $input): string
{
$instructionLines = explode("\n", $input);
$highestSeatId = 0;
foreach ($instructionLines as $instructionLine) {
$seatId = $this->calculateSeatId($instructionLine);
if ($seatId > $highestSeatId) {
$highestSeatId = $seatId;
}
}
return (string)$highestSeatId;
}
public function calculateSeatId(string $instructionLine): int
{
$rowsStart = 0;
$rowsEnd = 127;
$rowInstructions = str_split(substr($instructionLine, 0, 7));
foreach ($rowInstructions as $instruction) {
$middle = ($rowsEnd - $rowsStart + 1) / 2;
if ($instruction === self::FRONT) {
$rowsEnd -= $middle;
} elseif ($instruction === self::BACK) {
$rowsStart += $middle;
} else {
throw new RuntimeException('Well, shit...');
}
}
$columnsStart = 0;
$columnsEnd = 7;
$columnInstructions = str_split(substr($instructionLine, 7, 3));
foreach ($columnInstructions as $instruction) {
$middle = ($columnsEnd - $columnsStart + 1) / 2;
if ($instruction === self::LEFT) {
$columnsEnd -= $middle;
} elseif ($instruction === self::RIGHT) {
$columnsStart += $middle;
} else {
throw new RuntimeException('Well, shit...');
}
}
return $rowsEnd * 8 + $columnsEnd;
}
protected function partTwo(string $input): string
{
$instructionLines = explode("\n", $input);
$seatIds = [];
foreach ($instructionLines as $instructionLine) {
$seatIds[] = $this->calculateSeatId($instructionLine);
}
sort($seatIds);
$minValue = array_shift($seatIds);
$maxValue = array_pop($seatIds);
$missingSeatIds = range($minValue, $maxValue);
foreach ($seatIds as $missingSeatId) {
unset($missingSeatIds[array_search($missingSeatId, $missingSeatIds, true)]);
}
foreach ($missingSeatIds as $missingSeatId) {
if (
in_array($missingSeatId + 1, $seatIds, true)
&& in_array($missingSeatId - 1, $seatIds, true)
) {
return (string)$missingSeatId;
}
}
throw new RuntimeException('Well, shit...');
}
}