May is Coding
December 8th, 2023 PHP

🎄 Advent of Code Day 08

Today's quest is called Haunted Wasteland. You are riding a camel across a desert island. You find a map in one of the camel's bags. The map contains instructions on how to navigate through the desert and a bunch of knots. It looks like this

RL

AAA = (BBB, CCC)
BBB = (DDD, EEE)
CCC = (ZZZ, GGG)
DDD = (DDD, DDD)
EEE = (EEE, EEE)
GGG = (GGG, GGG)
ZZZ = (ZZZ, ZZZ)


You start at node AAA and need to get to node ZZZZ. And you need to know how many steps it takes to get to node ZZZ.

Part 1

Parsing map into arrays was easy

$map = array_slice($map, 1);
$map = array_map(function ($value) {
    [$point, $lr] = explode(' = ', str_replace(['(', ')'], '', str_replace(['(', ')'], '', $value)));
    [$L, $R] = explode(', ', $lr);
    return compact('point', 'L', 'R');
}, $map);

at the end I had map

[
    point => AAA,
    L => XXX,
    R =? BBB,
]

And now all I had to do was go through all the instructions and see if I needed to go left or right.

while ($currentPoint != 'ZZZ') {
    $currentPoint = move($currentPoint, $map, $leftRight[$i]);
    $i++;
    if ($i >= strlen($leftRight) ) {
        $i = 0;
    }

    $steps++;
}

The map guide says that if you go to the end of the instructions on which side to choose, you have to repeat them from start to finish. To ensure this, I simply reset the counter when I reach the end of the instructions.

if ($i >= strlen($leftRight) ) {
    $i = 0;
}

To find next point I using array_search

function move($startpoint, $map, $leftRight)
{
    $point = array_search($startpoint, array_column($map, 'point'));
    return $map[$point][$leftRight];
}

This one was relatively easy part. Alt least easier than day 3 and I'm happy with my solution.