8000 Day 9, part1 · FailedCode/adventofcode-2022-php@209f176 · GitHub
[go: up one dir, main page]

Skip to content

Commit 209f176

Browse files
committed
Day 9, part1
1 parent 944cc65 commit 209f176

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

src/Days/Day9.php

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
<?php
2+
3+
namespace Failedcode\Aoc2022\Days;
4+
5+
class Day9 extends AbstractDay
6+
{
7+
public function solve_part_1(): string
8+
{
9+
$moves = $this->getMoves();
10+
$headX = $headY = 0;
11+
$tailX = $tailY = 0;
12+
$tailPositions = [];
13+
foreach ($moves as $move) {
14+
list($x, $y) = $move;
15+
$tailPositions["{$tailX}|{$tailY}"] = true;
16+
$headX += $x;
17+
$headY += $y;
18+
19+
if (!$this->inRange($headX, $headY, $tailX, $tailY)) {
20+
$xdiff = $headX - $tailX;
21+
$ydiff = $headY - $tailY;
22+
if ($headX != $tailX && $headY != $tailY) {
23+
// diagonal
24+
$tailX += $this->sign($xdiff);
25+
$tailY += $this->sign($ydiff);
26+
} elseif (abs($xdiff) > abs($ydiff)) {
27+
$tailX += $this->sign($xdiff);
28+
} elseif (abs($ydiff) > abs($xdiff)) {
29+
$tailY += $this->sign($ydiff);
30+
}
31+
$tailPositions["{$tailX}|{$tailY}"] = true;
32+
}
33+
}
34+
35+
return count($tailPositions);
36+
}
37+
38+
public function solve_part_2(): string
39+
{
40+
return "TODO";
41+
}
42+
43+
protected function sign($n)
44+
{
45+
if ($n > 0) {
46+
return 1;
47+
}
48+
if ($n < 0) {
49+
return -1;
50+
}
51+
return 0;
52+
}
53+
54+
protected function inRange($x1, $y1, $x2, $y2)
55+
{
56+
return abs($x1 - $x2) < 2 && abs($y1 - $y2) < 2;
57+
}
58+
59+
protected function getMoves()
60+
{
61+
$moves = [];
62+
$inputList = $this->util->loadInput(9);
63+
foreach ($inputList as $row) {
64+
if (empty($row)) {
65+
continue;
66+
}
67+
list($dir, $n) = explode(' ', trim($row), 2);
68+
for ($i = 0; $i < (int)$n; $i += 1) {
69+
switch ($dir) {
70+
case 'R': $moves[] = [1, 0]; break;
71+
case 'L': $moves[] = [-1, 0]; break;
72+
case 'D': $moves[] = [0, 1]; break;
73+
case 'U': $moves[] = [0, -1]; break;
74+
}
75+
}
76+
}
77+
return $moves;
78+
}
79+
}

0 commit comments

Comments
 (0)
0