0 Comments Posted in:

Today’s Advent of Code challenge was a fun one. It reminded me a bit of those follow the line children’s puzzles. You simply had to follow the path of a line drawn in ASCII art with |, and + characters, and collect letters as you go. The line could cross over itself, but apart from that, the rules weren’t too complex – just keep going until you hit a + character at which point you’re turning a corner.

My solver already reads the input file as an array of strings, which is fine for this puzzle. I simply needed to track current position, direction (left, down, up, right), the letters I’d seen (for part 1) and the total number of steps taken (for part 2).

Here’s my code after a little bit of tidying up:

function solve(input,part) {
    const letters = [];
    let [x,y] = [input[0].indexOf('|'),0]
    let dir = "D", n = 0;
    for(;input[y][x] != " ";n++) {
        let c = input[y][x];
        if (c >= "A" && c <= "Z") letters.push(c)

        if (dir === "D" || dir === "U") {
            if (c === "+") [x,dir] = input[y][x-1] != " " ? [x-1,"L"] : [x+1,"R"]
            else y += (dir === "D") ? 1 : -1;
        else {
            if (c === "+") [y,dir] = input[y-1][x] != " " ? [y-1,"U"] : [y+1,"D"]
            else x += (dir === "L") ? -1 : 1;
    return part === 1 ? letters.join('') : n;

One thing I like to do after I’ve picked up my two stars for each day is to browse the other solutions on the Advent of Code subreddit. You can learn a lot from seeing how other people tackle the same problem using other languages, and often much more succinctly or using clever alternative approaches. I liked this Python solution taking advantage of Python’s built in complex number support, which is handy for tracking x,y coordinates.

Often someone will visualize their solution in some way, and today’s problem was ideal for that. If you have your puzzle input to hand, check out this visualizer.

Vote on HN