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

Skip to content

Commit f01444d

Browse files
committed
Day 9, part2
1 parent 209f176 commit f01444d

File tree

1 file changed

+45
-2
lines changed

1 file changed

+45
-2
lines changed

src/Days/Day9.php

Lines changed: 45 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,9 @@ public function solve_part_1(): string
1010
$headX = $headY = 0;
1111
$tailX = $tailY = 0;
1212
$tailPositions = [];
13+
$tailPositions["{$tailX}|{$tailY}"] = true;
1314
foreach ($moves as $move) {
1415
list($x, $y) = $move;
15-
$tailPositions["{$tailX}|{$tailY}"] = true;
1616
$headX += $x;
1717
$headY += $y;
1818

@@ -37,7 +37,41 @@ public function solve_part_1(): string
3737

3838
public function solve_part_2(): string
3939
{
40-
return "TODO";
40+
$X = 0;
41+
$Y = 1;
42+
$moves = $this->getMoves();
43+
$knotCount = 10;
44+
$knots = $this->fillArray($knotCount);
45+
$tailPositions = [];
46+
$tailPositions["0|0"] = true;
47+
foreach ($moves as $move) {
48+
list($x, $y) = $move;
49+
50+
$knots[0][$X] += $x;
51+
$knots[0][$Y] += $y;
52+
for ($i = 1; $i < $knotCount; $i += 1) {
53+
if ($this->inRange($knots[$i-1][$X], $knots[$i-1][$Y], $knots[$i][$X], $knots[$i][$Y])) {
54+
break;
55+
} else {
56+
$xdiff = $knots[$i-1][$X] - $knots[$i][$X];
57+
$ydiff = $knots[$i-1][$Y] - $knots[$i][$Y];
58+
if ($knots[$i-1][$X] != $knots[$i][$X] && $knots[$i-1][$Y] != $knots[$i][$Y]) {
59+
// diagonal
60+
$knots[$i][$X] += $this->sign($xdiff);
61+
$knots[$i][$Y] += $this->sign($ydiff);
62+
} elseif (abs($xdiff) > abs($ydiff)) {
63+
$knots[$i][$X] += $this->sign($xdiff);
64+
} elseif (abs($ydiff) > abs($xdiff)) {
65+
$knots[$i][$Y] += $this->sign($ydiff);
66+
}
67+
if ($i === $knotCount-1) {
68+
$tailPositions["{$knots[$i][$X]}|{$knots[$i][$Y]}"] = true;
69+
}
70+
}
71+
}
72+
73+
}
74+
return count($tailPositions);
4175
}
4276

4377
protected function sign($n)
@@ -51,6 +85,15 @@ protected function sign($n)
5185
return 0;
5286
}
5387

88+
protected function fillArray($n)
89+
{
90+
$result = [];
91+
for ($i = 0; $i < $n; $i += 1) {
92+
$result[] = [0, 0];
93+
}
94+
return $result;
95+
}
96+
5497
protected function inRange($x1, $y1, $x2, $y2)
5598
{
5699
return abs($x1 - $x2) < 2 && abs($y1 - $y2) < 2;

0 commit comments

Comments
 (0)
0