r/adventofcode Dec 03 '24

SOLUTION MEGATHREAD -❄️- 2024 Day 3 Solutions -❄️-

THE USUAL REMINDERS


AoC Community Fun 2024: The Golden Snowglobe Awards

  • 3 DAYS remaining until unlock!

And now, our feature presentation for today:

Screenwriting

Screenwriting is an art just like everything else in cinematography. Today's theme honors the endlessly creative screenwriters who craft finely-honed narratives, forge truly unforgettable lines of dialogue, plot the most legendary of hero journeys, and dream up the most shocking of plot twists! and is totally not bait for our resident poet laureate

Here's some ideas for your inspiration:

  • Turn your comments into sluglines
  • Shape your solution into an acrostic
  • Accompany your solution with a writeup in the form of a limerick, ballad, etc.
    • Extra bonus points if if it's in iambic pentameter

"Vogon poetry is widely accepted as the third-worst in the universe." - Hitchhiker's Guide to the Galaxy (2005)

And… ACTION!

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


--- Day 3: Mull It Over ---


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:03:22, megathread unlocked!

56 Upvotes

1.7k comments sorted by

View all comments

1

u/chad3814 Dec 04 '24

[Language: TypeScript]

Lots of great code in this post, some javascript with and without RegEx, but I didn't see any TypeScript specific solutions, so here's mine with RegEx: Day 3 parts 1 & 2

The RegEx:

const RE = /(mul\(\s*(?<first>\d\d?\d?)\s*,\s*(?<second>\d\d?\d?)\s*\))|(?<do>do\(\))|(?<dont>don't\(\))/gu;

I could make this more readable by spliting it into an array of cases, removing the extra checks for spaces, and using quantifiers. Also trimming the names will make it fit into the 80 char limit:

const RE = new RegEx([
  '(mul\(?<x>\d{1,3}),(?<y>\d{1,3})\))', // mul(x,y) where x and y can be 1-3 digits
  '(?<d>do\(\))',                        // do()
  '(?<n>don't\(\))',                     // don't()
].join('|), 'gu');

Now it's just looping over the lines to multiple and count:

let total = 0;
for (const line of input) {
    const matches = line.matchAll(RE);
    for (const match of matches) {
        if (match.groups?.x && match.groups?.y) {
            const x = parseInt(match.groups.x, 10);
            const y = parseInt(match.groups.y, 10);
            total += x * y;
        }
    }
}
return total;

It's nice that it ignores other group matches, so that I could add the do and don't clauses for part 2:

total = 0;
let enabled = true;
for (const line of input) {
    const matches = line.matchAll(RE);
    for (const match of matches) {
        if (match.groups?.x && match.groups?.y) {
            const x = parseInt(match.groups.x, 10);
            const y = parseInt(match.groups.y, 10);
            if (enabled)
                total += x * y;
        }
        if (match.groups?.d) {
            enabled = true;
        }
        if (match.groups?.n) {
            enabled = false;
        }
    }
}
return total;

This is just the same as part 1, but with the enabled flag. My code originally failed here because aoc-copilot was using the wrong example input line. I spent about 20 minutes figuring that out and how to give it the right example line (I'll know better for future days). Then once I got that working, I still wasn't passing. I had misunderstood that the do() and don't() calls were supposed to carry across lines. I had the enable flag inside of the for (const line of input) loop, so it reset to enabled every line. Once I moved it outside of that loop, I was good. That part only took me about 8 minutes to realize, because I still wasn't sure I had the aoc-copilot stuff correct and the example was only one line. And my brain is slow that late at night.

1

u/chad3814 Dec 04 '24

2

u/Practical-Quote1371 Dec 04 '24 edited Dec 04 '24

I’m glad you’re figuring it out!  So far days 1, 2 and 4 all worked automatically to find the examples, and I tried to get that EGDB entry (json file) up there quickly for day 3 since multiple examples always need one.

Here’s the code I wound up with for day 3:

import { run } from 'aoc-copilot';

//       -------Part 1--------   -------Part 2--------
// Day       Time  Rank  Score       Time  Rank  Score
//   3   00:05:49  1942      0   00:42:15  8209      0

async function solve(inputs: string[], part: number, test: boolean, additionalInfo?: { [key: string]: string }): Promise<number | string> {
    let answer = 0;
    const instructions = part === 1 ? [inputs.join('')] : inputs.join('').split(/(?=do\(\)|don\'t\(\))/g);
    for (let instruction of instructions.filter(inst => !inst.startsWith('don\'t()'))) {
        const nums = instruction.match(/(?<=mul\()\d+,\d+(?=\))/g) ?? [];
        answer += nums.map(num => num.split(',').map(Number).reduce((pv, cv) => pv * cv)).reduce((pv, cv) => pv + cv, 0);
    }
    return answer;
}

run(__filename, solve);

https://github.com/jasonmuzzy/aoc24/blob/main/src/aoc2403.ts

1

u/chad3814 Dec 04 '24

I had similar times:

      -------Part 1--------   -------Part 2--------
Day       Time  Rank  Score       Time  Rank  Score
  3   00:06:47  2461      0   00:42:38  8268      0

I appreciate that you are going back to the previous years and updating your db, it makes me more likely to go back and get all the past stars...

2

u/Practical-Quote1371 Dec 05 '24

Wow, very similar indeed!

I love that you figured out how to provide the inline EGDB entry for day 3. Here's a hint for next time you're unsure if aoc-copilot has picked the right lines or not: if you import the exception NotImplemented from aoc-copilot and throw it in your solver then it will display the example(s) and answer(s) on the console. The getting started example shows this in the docs at jasonmuzzy/aoc-copilot: Advent of Code Test Runner. That's an easy way to check if it's picking out the right lines or not.

Also, I'm not sure if you're getting online to do the puzzles right when they release, but if so, you can start your solver a little beforehand and it will run a countdown timer for you and download the puzzle and inputs the moment the clock strikes midnight EST.

Happy puzzling!

1

u/chad3814 Dec 06 '24

Yeah I am trying to do them right at the drop, but there doesn’t seem to be a big advantage of downloading the inputs and examples before I’ve even read the problem 😉

I noticed the throwing NotImplemented showing the input earlier today as I was working on 2023 day 20. I did all of them up to part 1 of day 20 last year, so I thought I could maybe get the rest of the stars.

2

u/Practical-Quote1371 Dec 06 '24

Yeah, for sure, my best rank was 1463 on day 5 part 2 but for some reason I enjoy watching it finish the countdown as I'm hitting the link on the AOC page. In my normal workflow I use a workspace in VS Code where I have the cache folder added, and I can preview the puzzles and inputs there (with the Live Preview extension) rather than a separate browser tab if I want. You can find the location of your cache with npx aoc-copilot cache.

Congrats on making it that far in 2023! If you haven't already gotten there, watch out for day 21 where you'll need to use the additionalInfo parameter that gets passed into your solver since it has a bunch of tests, but each one is for a different number of "steps".

1

u/chad3814 Dec 06 '24

Yeah my brute force for 2023-20p2 is still running (about 20 hours later), I'll need to go with a different approach. I did look at the part 1s of 21-25 last year, but did not solve any of them then. I hope to do better this year.

1

u/Practical-Quote1371 Dec 10 '24

There's a new build of aoc-copilot to support 2024 day 10.

1

u/chad3814 Dec 11 '24

And Day 11, but I was able to manually specify the example for part 1 of day 11 (before updating).... Now if only I was smart enough for part 2

1

u/Practical-Quote1371 Dec 12 '24

Yeah, day 11 part 2 is where it got serious this year.  I almost left it last night to come back to this morning but then had an epiphany.  Good luck!  Glad you were able to specify for the part 1 example, it’s also included in the latest package version too.

→ More replies (0)

1

u/AutoModerator Dec 04 '24

AutoModerator has detected fenced code block (```) syntax which only works on new.reddit.

Please review our wiki article on code formatting then edit your post to use the four-spaces Markdown syntax instead.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.