This repository has been archived by the owner on Jul 5, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day13.php
92 lines (78 loc) · 1.84 KB
/
Day13.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
<?php
class Layer {
private $direction = '1';
private $position = 0;
private $maxPosition = 0;
/**
* Layer constructor.
*
* @param int $positions
*/
public function __construct($positions)
{
$this->maxPosition = $positions - 1;
}
public function move()
{
if ($this->maxPosition == -1) {
return;
}
if ($this->position == 0) {
$this->direction = 1;
}
if ($this->position == $this->maxPosition) {
$this->direction = -1;
}
$this->position += $this->direction;
}
public function isDetecting()
{
return $this->maxPosition != -1 && $this->position == 0;
}
public function getRange()
{
return $this->maxPosition + 1;
}
public function reset()
{
$this->position = 0;
$this->direction = 1;
}
}
$input = file_get_contents('input13');
/** @var Layer[] $layers */
$layers = [];
foreach (explode("\n", trim($input)) as $item) {
list($depth, $range) = explode(": ", $item);
$layers[$depth] = new Layer($range);
}
$severity = 0;
for ($currentDepth = 0; $currentDepth <= max(array_keys($layers)); $currentDepth++) {
foreach ($layers as $depth => $layer) {
if ($depth == $currentDepth) {
if ($layer->isDetecting()) {
$severity += $depth * $layer->getRange();
}
}
$layer->move();
}
}
echo "1: $severity\n";
foreach($layers as $layer) {
$layer->reset();
}
$wait = 0;
while (true) {
$caught = false;
foreach ($layers as $depth => $layer) {
if (($wait + $depth) % (2 * ($layer->getRange() -1)) == 0) {
$caught = true;
$wait++;
break;
}
}
if (!$caught) {
echo "part 2 = $wait\n";
break;
}
}