-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay3.php
74 lines (56 loc) · 1.72 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
<?php
declare(strict_types=1);
namespace XonneX\AdventOfCode\Y2020\Solutions\Day3;
use XonneX\AdventOfCode\Core\AbstractSolution;
class Day3 extends AbstractSolution
{
private const TREE = '#';
public function __construct()
{
parent::__construct(2020, 3);
}
protected function partOne(string $input): string
{
$lines = explode("\n", $input);
$rows = [];
foreach ($lines as $line) {
$rows[] = str_split($line);
}
return (string) $this->calculateTreeEncountersForSlope($rows, 3, 1);
}
protected function partTwo(string $input): string
{
$lines = explode("\n", $input);
$rows = [];
foreach ($lines as $line) {
$rows[] = str_split($line);
}
return (string) (
$this->calculateTreeEncountersForSlope($rows, 1, 1)
* $this->calculateTreeEncountersForSlope($rows, 3, 1)
* $this->calculateTreeEncountersForSlope($rows, 5, 1)
* $this->calculateTreeEncountersForSlope($rows, 7, 1)
* $this->calculateTreeEncountersForSlope($rows, 1, 2)
);
}
private function calculateTreeEncountersForSlope(array $map, int $goRight, int $goDown): int
{
$maxX = count($map[0]);
$maxY = count($map);
$x = 1;
$y = 1;
$treeEncounterCounter = 0;
while ($y < $maxY) {
$x += $goRight;
$y += $goDown;
if ($x > $maxX) {
$x -= $maxX;
}
$square = $map[$y - 1][$x - 1];
if ($square === self::TREE) {
$treeEncounterCounter++;
}
}
return $treeEncounterCounter;
}
}