Day 3: Foggy Forest
Megathread guidelines
- Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
- You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://topaz.github.io/paste/ if you prefer sending it through a URL
FAQ
- What is this?: Here is a post with a large amount of details: https://programming.dev/post/6637268
- Where do I participate?: https://adventofcode.com/
- Is there a leaderboard for the community?: We have a programming.dev leaderboard with the info on how to join in this post: https://programming.dev/post/6631465


PHP
My first full-time job was mostly PHP, and since that was in the noughties, I wanted to see what had changed. Not enough! It’s still very inconsistent, although the new features do take some of the pain away.
Unfortunately, I found the new pipe operator to frequently involve enough boilerplate that it was cleaner not to bother, .e.g
$x |> (fn($s) => str_replace(" ", "-", $s)). NerdFont’s triangle ligature is quite satisfying, at least!Going from p1 to p2 meant looking at 69773 -> 193909310 candidate squares, although I’m sure there’s simple optimisations to be made. 2.3 secs to run, so I wasn’t waiting around.
function parse($input) { $ar = []; $lines = explode("\n", $input); foreach ($lines as $line) { $ar[] = array_map(fn($ch) => ($ch == '#'), str_split($line)); } return $ar; } function run($input) { $num_orth = 0; $num_diag = 0; $trees = parse($input); // start at SW, for cleaner maths for ($y = count($trees) - 1; $y >= 1; $y--) { for ($x = count($trees[0]) - 1; $x >= 1; $x--) { // bounding box $max = max($x, $y); // sweep in, checking other corners for ($i = $max; $i > 0; $i--) { // but also skew for ($o = 0; $o < $max; $o++) { if (($trees[$y ][$x ] ?? false) && // root (SE) ($trees[$y-$i ][$x -$o] ?? false) && // NE ($trees[$y-$i+$o][$x-$i-$o] ?? false) && // NW ($trees[$y +$o][$x-$i ] ?? false)) // SW { if (!$o) {$num_orth++;} $num_diag++; } } } } } return [$num_orth, $num_diag]; }