<?php $instructions = explode("\n", file_get_contents('./input.txt')); $h = [0,0]; $t = [0,0]; $places = ["0-0"]; $grid = [ ['#'], ]; foreach ($instructions as $instruction) { [$direction, $length] = explode(' ', $instruction); for ($i = 0; $i < $length; $i++) { $newH = $h; switch ($direction) { case 'U': $newH[0]++; break; case 'R': $newH[1]++; break; case 'D': $newH[0]--; break; case 'L': $newH[1]--; break; } if (areTooFarAway($newH, $t)) { $t = $h; $places[] = implode('-', $h); $grid[$h[0]][$h[1]] = '#'; } $h = $newH; } } displayGrid($grid); echo count(array_unique($places)); /** * @param int[] $x * @param int[] $y * * @return bool */ function areTooFarAway($x, $y): bool { for ($i = $x[0] - 1, $l = $x[0] + 1; $i <= $l; $i++) { for ($j = $x[1] - 1, $m = $x[1] + 1; $j <= $m; $j++) { if ($y[0] === $i && $y[1] === $j) { return false; } } } return true; } /** * @param array $grid * * @return void */ function displayGrid($grid): void { $maxRow = 0; foreach ($grid as $item) { $maxRow = max($maxRow, count($item)); } $grid = array_reverse($grid); foreach ($grid as $iValue) { for ($j = 0; $j <= $maxRow; $j++) { if (isset($iValue[$j])) { echo $iValue[$j]; } else { echo '.'; } } echo "\n"; } }