-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay11.php
116 lines (93 loc) · 2.99 KB
/
Day11.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
<?php
declare(strict_types=1);
namespace XonneX\AdventOfCode\Y2021\Solutions\Day11;
use RuntimeException;
use XonneX\AdventOfCode\Core\AbstractSolution;
use function explode;
use function str_split;
use const PHP_EOL;
class Day11 extends AbstractSolution
{
public function __construct()
{
parent::__construct(2021, 11);
}
protected function partOne(string $input): string
{
$grid = [];
foreach (explode("\n", $input) as $x => $line) {
foreach (str_split($line) as $y => $energyLevel) {
$octopus = new Octopus();
$octopus->energyLevel = (int) $energyLevel;
$grid[$x][$y] = $octopus;
}
}
$flashCounter = 0;
for ($i = 0; $i < 100; $i++) {
$flashCounter += $this->flash($grid);
}
return (string) $flashCounter;
}
protected function partTwo(string $input): string
{
$grid = [];
foreach (explode("\n", $input) as $x => $line) {
foreach (str_split($line) as $y => $energyLevel) {
$octopus = new Octopus();
$octopus->energyLevel = (int) $energyLevel;
$grid[$x][$y] = $octopus;
}
}
$i = 1;
while ($this->flash($grid) !== 100) {
$i++;
}
return (string) $i;
}
/**
* @param Octopus[][] $grid
*/
private function flash(array $grid): int
{
$flashCounter = 0;
foreach ($grid as $row) {
foreach ($row as $entry) {
$entry->energyLevel++;
$entry->hasFlashed = false;
}
}
$found = true;
while ($found) {
$found = false;
foreach ($grid as $x => $row) {
foreach ($row as $y => $octopus) {
if (
$octopus->energyLevel > 9
&& !$octopus->hasFlashed
) {
$octopus->energyLevel = 0;
$octopus->hasFlashed = true;
$found = true;
$flashCounter++;
$others = [
$grid[$x - 1][$y] ?? null,
$grid[$x - 1][$y + 1] ?? null,
$grid[$x][$y + 1] ?? null,
$grid[$x + 1][$y + 1] ?? null,
$grid[$x + 1][$y] ?? null,
$grid[$x + 1][$y - 1] ?? null,
$grid[$x][$y - 1] ?? null,
$grid[$x - 1][$y - 1] ?? null,
];
foreach ($others as $other) {
if ($other !== null && !$other->hasFlashed) {
$other->energyLevel++;
}
}
}
}
}
}
return $flashCounter;
}
}