-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay2.php
59 lines (49 loc) · 1.55 KB
/
Day2.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
<?php
declare(strict_types=1);
namespace XonneX\AdventOfCode\Y2021\Solutions\Day2;
use XonneX\AdventOfCode\Core\AbstractSolution;
class Day2 extends AbstractSolution
{
public function __construct()
{
parent::__construct(2021, 2);
}
protected function partOne(string $input): string
{
$horizontal = 0;
$depth = 0;
foreach (explode("\n", $input) as $command) {
if (str_starts_with($command, 'forward')) {
$value = (int) substr($command, 8);
$horizontal += $value;
} elseif (str_starts_with($command, 'down')) {
$value = (int) substr($command, 5);
$depth += $value;
} else {
$value = (int) substr($command, 3);
$depth -= $value;
}
}
return (string) ($horizontal * $depth);
}
protected function partTwo(string $input): string
{
$horizontal = 0;
$depth = 0;
$aim = 0;
foreach (explode("\n", $input) as $command) {
if (str_starts_with($command, 'forward')) {
$value = (int) substr($command, 8);
$horizontal += $value;
$depth += $aim * $value;
} elseif (str_starts_with($command, 'down')) {
$value = (int) substr($command, 5);
$aim += $value;
} else {
$value = (int) substr($command, 3);
$aim -= $value;
}
}
return (string) ($horizontal * $depth);
}
}