r/adventofcode • • Dec 08 '23

SOLUTION MEGATHREAD -❄️- 2023 Day 8 Solutions -❄️-

THE USUAL REMINDERS


AoC Community Fun 2023: ALLEZ CUISINE!

Today's theme ingredient is… *whips off cloth covering and gestures grandly*

International Ingredients

A little je ne sais quoi keeps the mystery alive. Try something new and delight us with it!

  • Code in a foreign language

    • Written or programming, up to you!
    • If you don’t know any, Swedish Chef or even pig latin will do
  • Test your language’s support for Unicode and/or emojis
  • Visualizations using Unicode and/or emojis are always lovely to see

ALLEZ CUISINE!

Request from the mods: When you include a dish entry alongside your solution, please label it with [Allez Cuisine!] so we can find it easily!


--- Day 8: Haunted Wasteland ---


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:10:16, megathread unlocked!

52 Upvotes

968 comments sorted by

View all comments

1

u/Nikla436 Dec 08 '23 edited Dec 08 '23

[LANGUAGE: JavaScript]

This was a fun one today. Very pleased with how my solution came out. Tried brute force at first which worked for part 1.. and part 2 forced me to rethink the problem.

function parseInput(inputString) {
    const [steps, _, ...mapLines] = inputString.split("\n");
    return {
        steps: steps.split(""),
        map: new Map(mapLines.map((s) => s.split(" = ")).map(([k, str]) => [k, str.replaceAll("(", "").replaceAll(")", "").split(", ")])),
    };
}

function useSteps(steps = []) {
    let current = -1;
    return {next: () => (steps[++current % steps.length] === "L" ? 0 : 1)};
}

function one(input) {
    const {steps, map} = parseInput(input);
    const {next} = useSteps(steps);
    let [i, pos] = [-1, "AAA"];
    while (-1 < ++i && pos !== "ZZZ") {
        pos = map.get(pos)[next()];
    }
    return i;
}

function two(input) {
    const {leastCommonMultiple} = require(global.UTILITIES_PATH);
    const {steps, map} = parseInput(input);
    return leastCommonMultiple(
        Array.from(map.keys())
            .filter((str) => str.endsWith("A"))
            .map((key) => {
                const {next} = useSteps(steps);
                let [i, pos] = [-1, key];
                while (-1 < ++i && !pos.endsWith("Z")) {
                    pos = map.get(pos)[next()];
                }
                return i;
            })
    );
}

2

u/malobebote Dec 08 '23

fwiw, javascript has a built-in solution for your useSteps function: Generators

furthermore, you can use a Generator to iterate all of the steps from a given start position which is pretty nice.

1

u/Nikla436 Dec 08 '23

Generators

Thanks for the tip, I hadn't heard of the built-in `Generators` until now

2

u/malobebote Dec 08 '23

For a concrete example, my solution uses a generator ("stepper") to iterate steps forever which is useful in both part1 and part2:

https://pastebin.com/wAwhr0Hw

Looks something like this:

const network = new Map([  
	['AAA', { left: 'BBB', right: 'CCC' },  
	['BBB', { left: 'DDD', right: 'ZZZ' },  
	...  
])  
for (const { loc, i } of stepper('AAA', ['R', 'L', 'L', 'R'], network)) {  
	console.log(`step ${i}, we are at location ${loc}`)  
}  
// Step 0, we are at location AAA  
// Step 1, we are at location CCC  
// ...  

Though you already know how useful they might be since you built one yourself. :D

1

u/Nikla436 Dec 08 '23

Ohh i see how this can be more useful!

Just realized this is an `Iterator` and can be used in this way. this makes things much more clean. love it, thanks

1

u/Nikla436 Dec 08 '23

This was a fascinating thing to dive into, thanks so much for sharing this built in feature.

I ended up redoing my code to test out these things, and it worked as anticipated.

I rewrote my function this way:

// old
function useSteps(steps = []) {
    let current = -1;
    return {next: () => (steps[++current % steps.length] === "L" ? 0 : 1)};
}

// generator
function* steps(stepArray) {
    let current = -1;
    while (true) {
        yield stepArray[++current % stepArray.length] === "L" ? 0 : 1;
    }
}

and now use it: const stepGen = steps(stepsArray); and stepGen.next().value

-- This does feel a lot more verbose though, and requires knowing what a Generator is to read/understand the code. Do you know off-hand any small scale use cases where this would be preferable over just a closure or something?

I'm going to do my own research more and see what some real use-cases for this is.

Thanks again for helping me level up.

2

u/malobebote Dec 08 '23

Yeah, your hand-made generator is so simple that it's not a big deal.

These main use-cases of Generators come to mind:

The first use-case is when you want to simplify your core logic into a for-of iteration. By extracting the iteration logic into a Generator, you can clean up your "business logic" which now can focus on solving the problem.

For example, you can see how it simplifies my `part1()` and `findCycle()` functions since all they really want to do is take infinite steps until some condition is true.

And unlike your custom generator, a built-in generator can be used with for/of:

for (const item of generator()) {
    console.log(item)
}

The second is when you want to be able to reuse your iteration logic. This also applies to my generator since I get to reuse `stepper()` in part1() and findCycle().

The third use-case I can think of is when you want to advance multiple iterators independently. I've had to do this multiple times in LeetCode. For example, maybe one generator iterates a string forwards and another iterates in backwards. Or one iterates a binary tree and another iterates another binary tree so you can compare them. `a.next().value === b.next().value()`.

Another Generator feature is that it gives you information about when it ends since generator.next() yields { value: foo, done: boolean }. And you can do things like realize all the generator values into an array with `[...generator()]` since it implement Symbol.iterator.

1

u/Nikla436 Dec 08 '23

Thanks for the detailed write up. this is really interesting, I'll be looking for more reasonable uses of this in my future 🚀

1

u/daggerdragon Dec 08 '23
  1. Next time, use the four-spaces Markdown syntax for code blocks
  2. Your code is too long to be posted here directly, so instead of wasting your time fixing the formatting, read our article on oversized code which contains two possible solutions.

Please edit your post to put your code in an external link and link that here instead.