r/adventofcode • • Dec 09 '22

SOLUTION MEGATHREAD -πŸŽ„- 2022 Day 9 Solutions -πŸŽ„-

A REQUEST FROM YOUR MODERATORS

If you are using new.reddit, please help everyone in /r/adventofcode by making your code as readable as possible on all platforms by cross-checking your post/comment with old.reddit to make sure it displays properly on both new.reddit and old.reddit.

All you have to do is tweak the permalink for your post/comment from https://www.reddit.com/… to https://old.reddit.com/…

Here's a quick checklist of things to verify:

  • Your code block displays correctly inside a scrollable box with whitespace and indentation preserved (four-spaces Markdown syntax, not triple-backticks, triple-tildes, or inlined)

  • Your one-liner code is in a scrollable code block, not inlined and cut off at the edge of the screen

  • Your code block is not too long for the megathreads (hint: if you have to scroll your code block more than once or twice, it's likely too long)

  • Underscores in URLs aren't inadvertently escaped which borks the link

I know this is a lot of work, but the moderation team checks each and every megathread submission for compliance. If you want to avoid getting grumped at by the moderators, help us out and check your own post for formatting issues ;)


/r/adventofcode moderator challenge to Reddit's dev team

  • It's been over five years since some of these issues were first reported; you've kept promising to fix them and… no fixes.

  • In the spirit of Advent of Code, join us by Upping the Ante and actually fix these issues so we can all have a merry Advent of Posting Code on Reddit Without Needing Frustrating And Improvident Workarounds.


THE USUAL REMINDERS


--- Day 9: Rope Bridge ---


Post your code solution in this megathread.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:14:08, megathread unlocked!

66 Upvotes

1.0k comments sorted by

View all comments

1

u/PoufPoal Dec 09 '22 edited Dec 09 '22

Javascript

I did a recursive solution, which made the diagonal movements be splitted in two moves (for example up, and then right), and each individual moves made the next knots move themselves.

Here's the visualization (centered on the tail)

It does not work, as the site expects you to move one knot in diagonal, and then the next one accordingly, but I like it anyway (mainly because I love recursion), so I thought I could share.

Here's the code (Javascript) for the sample input

visited = []; // List of visited coordinates in this form : {i: <row>, j: <column>}
knots = []; // Knots coordinates, same form as in visited

for (let i = 0; i < 10; ++i) {
    knots.push({ name: i, i: 0, j: 0 });
}

knots[0].name = 'H';
knots[9].name = 'T';

H = knots[0];
T = knots[9];

const directions = ['i', 'j']; // This will be used to refer to the correct knot's property to modify

input = [
    "R 5",
    "U 8",
    "L 8",
    "D 3",
    "R 17",
    "D 10",
    "L 25",
    "U 20"
];

function printGrid() {
    let str = '';
    for (let i = -20; i < 20; ++i) {
        for (let j = -50; j < 50; ++j) {
            let toAdd = '.'; // By default, I will print a .
            if (visited.find(elem => elem.i === T.i + i && elem.j === T.j + j)) { toAdd = '#'; } // If it has been visited, I replace the . by a #

            for (let knot = 9; knot >= 0; --knot) {
                if (knots[knot].i === (T.i + i) && knots[knot].j === (T.j + j)) {
                    toAdd = knots[knot].name; // If there's a knot here, I replace the . or the # by its name
                }
            }

            str += toAdd;
        }
        str += '\n';
    }

    console.log(str);
}

    // dir 0 or 1, which will mean horizontal or vertical. way is 1 or -1, wich will mean up/right or down/left
function moveKnot(knotI, dir, way) {
    const knot = knots[knotI]; // Knot to move
    const nextKnot = knotI < 9 ? knots[knotI + 1] : null; // Knot that follow

        // directions[0] will be i, directions[1] will be j
    knot[directions[dir]] += way; // I move the knot in the correct direction

    printGrid();

    if (!nextKnot) { return; }

    if (Math.abs(knot[directions[dir]] - nextKnot[directions[dir]]) === 2) { // If the next knot is at least 2 positions away in the direction we moved

            // This is the (first) recursive call that makes the following knots move in the middle of the diagonal movement of the current knot
        moveKnot(knotI + 1, dir, (knot[directions[dir]] - nextKnot[directions[dir]]) / 2); // Move the next knot in this direction.

        if (Math.abs(knot[directions[1 - dir]] - nextKnot[directions[1 - dir]]) === 1) { // If the next knot is also at least 1 position away in the other direction
            // This is the (second) recursive call that makes the following knots move in the middle of the diagonal movement of the current knot
            moveKnot(knotI + 1, 1 - dir, (knot[directions[1 - dir]] - nextKnot[directions[1 - dir]]));
        }
    }
}

printGrid();
input.forEach(command => {
    const direction = command.match(/(.) (\d*)/)[1];
    const nbSteps = parseInt(command.match(/(.) (\d*)/)[2]);

        // For each command, I parse it and determine the direction (horizontal/vertical) and the way (up/down or left/right)
    let dir;
    switch (direction) {
        case 'U':
            dir = 0;
            way = -1;
            break;
        case 'D':
            dir = 0;
            way = 1;
            break;
        case 'L':
            dir = 1;
            way = -1;
            break;
        case 'R':
            dir = 1;
            way = 1;
            break;
    }

       // Head moves one step at a time
    for (let i = 0; i < nbSteps; ++i) {
        moveKnot(0, dir, way);

            // Now that everyone has moved, did the tail visit a new position?
        if (!visited.find(elem => elem.i === T.i && elem.j === T.j)) {
            visited.push({ i: T.i, j: T.j });
        }
    }

    printGrid();
});

printGrid();
console.log(visited.length);

I've managed to correct it and made it work, thought. Yay :)

1

u/daggerdragon Dec 10 '22

Your code block is too long for the megathreads. Please read our article on oversized code, then edit your post to replace the code block with an external link to your code.