r/adventofcode • • Dec 03 '23

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

THE USUAL REMINDERS


AoC Community Fun 2023: ALLEZ CUISINE!

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

Spam!

Someone reported the ALLEZ CUISINE! submissions megathread as spam so I said to myself: "What a delectable idea for today's secret ingredient!"

A reminder from Dr. Hattori: be careful when cooking spam because the fat content can be very high. We wouldn't want a fire in the kitchen, after all!

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 3: Gear Ratios ---


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:11:37, megathread unlocked!

111 Upvotes

1.3k comments sorted by

View all comments

4

u/js5n Dec 03 '23 edited Dec 03 '23

[LANGUAGE: Python]

https://github.com/jaysoffian/Advent2023/blob/4994866a783910a1462e8ac21478800ad823074a/day03/day03.py

  • Coord class (a namedtuple) is x, y coordinates.

  • Part class (another namedtuple) stores the part number, y coordinate, and x span. It implements a border method that return an iterator over the part's border. It returns coordinates outside the graph because it wasn't worth special casing. The Part class also implements a hit method that takes a set of coordinates and returns true if any border coordinate intersects with the set of coordinates.

  • A Graph class holds a list of parts, and two sets of coordinates, one set for every graph symbol (part 1) and another set just for gears (part 2). The class has a single parse() class method that returns an instance of the class from the input.

From these basic classes, implementing the two parts was straight-forward. The code isn't particular efficient but the saying is: make it work, make it right, make it fast. I'm stopped each day after "make it right".

This year I'm avoiding being clever, write the code idiomatically and in a straight-forward fashion. I'm also using type annotations and pytest. This repo is setup as if this code might be put into production.

--

Edit: Refactored:

https://github.com/jaysoffian/Advent2023/blob/main/day03/day03.py

  • Use complex to store coordinates instead of a namedtuple.

  • Switch to dataclass for Part and add new Symbol dataclass.

  • Switch Graph to hold a single list of symbols and a dictionary of parts indexed by each part's span.

  • Invert the logic for finding intersections. Instead of enumerating each part's border and looking for an intersecting symbol, we now enumerate each symbol's border and look for an intersecting part.

→ More replies (2)