-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay12.php
124 lines (102 loc) · 3.15 KB
/
Day12.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
<?php
declare(strict_types=1);
namespace XonneX\AdventOfCode\Y2020\Solutions\Day12;
use XonneX\AdventOfCode\Core\AbstractSolution;
class Day12 extends AbstractSolution
{
public function __construct()
{
parent::__construct(2020, 12);
}
protected function partOne(string $input): string
{
$x = 0;
$y = 0;
$direction = 'E';
$instructions = explode("\n", $input);
foreach ($instructions as $instruction) {
$op = $instruction[0];
$val = (int) substr($instruction, 1);
if ($op === 'N') {
$y += $val;
} elseif ($op === 'S') {
$y -= $val;
} elseif ($op === 'E') {
$x += $val;
} elseif ($op === 'W') {
$x -= $val;
} elseif ($op === 'L' || $op === 'R') {
$direction = $this->calculateDirection($direction, $op, $val);
} elseif ($op === 'F') {
if ($direction === 'E') {
$x += $val;
} elseif ($direction === 'S') {
$y -= $val;
} elseif ($direction === 'W') {
$x -= $val;
} elseif ($direction === 'N') {
$y += $val;
}
}
}
return (string) (abs($x) + abs($y));
}
private function calculateDirection(string $direction, string $rotation, int $degrees): string
{
$translation = [
'E' => 0,
'S' => 90,
'W' => 180,
'N' => 270,
];
$deg = $translation[$direction];
if ($rotation === 'L') {
$deg -= $degrees;
} elseif ($rotation === 'R') {
$deg += $degrees;
}
if ($deg < 0) {
$deg = 360 + $deg;
}
return array_search($deg % 360, $translation);
}
protected function partTwo(string $input): string
{
$shipX = 0;
$shipY = 0;
$x = 10;
$y = 1;
$instructions = explode("\n", $input);
foreach ($instructions as $instruction) {
$op = $instruction[0];
$val = (int) substr($instruction, 1);
if ($op === 'N') {
$y += $val;
} elseif ($op === 'S') {
$y -= $val;
} elseif ($op === 'E') {
$x += $val;
} elseif ($op === 'W') {
$x -= $val;
} elseif ($op === 'L') {
for ($i = 0; $i < $val / 90; $i++) {
$tmpX = $x;
$tmpY = $y;
$x = $tmpY * -1;
$y = $tmpX;
}
} elseif ($op === 'R') {
for ($i = 0; $i < $val / 90; $i++) {
$tmpX = $x;
$tmpY = $y;
$x = $tmpY;
$y = $tmpX * -1;
}
} elseif ($op === 'F') {
$shipX += $val * $x;
$shipY += $val * $y;
}
}
return (string) (abs($shipX) + abs($shipY));
}
}