r/adventofcode • u/daggerdragon • Dec 03 '23
SOLUTION MEGATHREAD -❄️- 2023 Day 3 Solutions -❄️-
THE USUAL REMINDERS
- All of our rules, FAQs, resources, etc. are in our community wiki.
Outstanding moderator challenges:
Community fun event 2023: ALLEZ CUISINE!
- 3 DAYS remaining until unlock!
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!"
- There really is an XKCD for everything, isn't there?
- All ingredients must come from a CAN (bus), box, package, container, etc.
- Unnecessarily declare variables for everything and don't re-use variables
- Why use few word when many word do trick?
- Go back to traditional culinary roots with Javadocs
- Lobster thermidor
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.
Read the full posting rules in our community wiki before you post!
- State which language(s) your solution uses with
[LANGUAGE: xyz] - Format code blocks using the four-spaces Markdown syntax!
- State which language(s) your solution uses with
- Quick link to Topaz's
pasteif you need it for longer code blocks
5
u/xe3to Dec 15 '23
[Language: Python]
It's not super Pythonic, though. I really need to work on that.
https://git.32bit.cafe/kaylee/AoC2023/src/branch/main/day3
8
u/WilkoTom Dec 03 '23 edited Dec 03 '23
[LANGUAGE: Rust] [Allez Cuisine!]
Lovely Spam! Wonderful Spam! Lovely Spam! Wonderful Spam Spa-a-a-a-a-a-a-am Spa-a-a-a-a-a-a-am Spa-a-a-a-a-a-a-am Spa-a-a-a-a-a-a-am Lovely Spam! (Lovely Spam!) Lovely Spam! (Lovely Spam!) Lovely Spam! Spam, Spam, Spam, Spam!
I don't understand why anyone would want less spam in their food, but if they do, the restaurant across the street serves a decent crab linguini instead.
11
u/ImpossibleSav Dec 03 '23
[Language: Python]
Another day solved in a single line of code! I'm keeping this up for as long as I can. Feel free to follow along on my GitHub! Below is for both parts, with
q[3]containing the input data.(I feel personally offended by the Allez Cuisine ingredient notes today...)
3
u/penguinencounter Dec 04 '23
[LANGUAGE: Minecraft mcfunction datapack]
Is this spam? Not sure...
sources
image gallery and video
3
u/thousandsongs Dec 05 '23
[LANGUAGE: shell] [LANGUAGE: awk] [Allez Cuisine!]
After already having done my regular solution in Haskell, I turned to the chef's challenge.
To solve it, I wrote a script that spams facts about the problem, until we have enough facts to solve it.
It just goes through the input line by line, drafting a spam email with anything it notices. It makes several such passes, each time finding more and more relevant facts, until eventually it hits on the solutions.
Here is the (snipped) trace from the run on the example input
Here is the link to the full source code for the script. As you can see, I didn't care for efficiency or minimizing the number of passes, and even printed some lines that are not essential. I spammed my way to success, really 🦍
Even notwithstanding all that spam and inefficiency, the script runs quite okay-ish on the full input – it takes ~15 seconds and produces a 2MB log before printing the correct results.
I also wrote a blog post to delve a bit deeper on the philosophy behind this style of coding - https://mrmr.io/prolog-is-a-vibe.
All in all, I spent way more time than you'd imagine and I'd care to admit on this, but I had loads of fun. Allez Cuisine!
49
u/4HbQ Dec 03 '23 edited Dec 03 '23
[LANGUAGE: Python] Code (12 lines)
Turns out that the solutions to both parts are nearly identical:
Edit: Updated the code using /u/masklinn's clever insight. Thanks!
25
u/Smylers Dec 03 '23 edited Dec 03 '23
[LANGUAGE: Vim Keystrokes]
Load your puzzle input, type this in (or copy-and-paste for the long
:%s///commands), and your part 1 answer will appear:The main
@aloop† on line 3 finds every symbol, visually selects the 9 characters centred on it, and makes any digits in that block upper-case, to mark them as being adjacent to a symbol.Wait ... upper-case digits?
Flipping the case of a character is a handy way of marking it as having been ‘found’ while retaining its value. Unfortunately‡ digits don't have case. So
0-9is first transformed intoa-j, by that substitution that adds49to its character value. Then we can make the ‘digits’ upper-case.And to avoid having to handle the literal edge-cases of symbols near edges — which would mess up drawing the visual block, because some of the 8 characters surrounding them wouldn't exist — first add extra padding of a
.to all 4 sides of the input. That's what the top line does: adds dots down the left, copies them to the right, then duplicates the top line, makes the new top all dots, and copies that to the bottom.Once the loop ends (because the
/can't find any more symbols; each matched symbol is also turned into a.so it only gets processed once), any number adjacent to a symbol will have at least one upper-case digit in it./\v<\l+>/will match each ‘word’ still composed only of lower-case digits, and replacing each of those with an innocuous.means all remaining numbers are indeed part numbers.So reverse the character-value transformation, by making all the remaining digits lower-case again and subtracting
49, to turn the letters back into more conventional-looking digits. Then replace each bit between the numbers (any string of one or more.or line-break characters) with a+sign to create a sum of them, and use the expression-evaluation design pattern from earlier days to get the answer. The only variation is appending an extra0to the expression because substitution will have left a final+at the end of the line, which would be a syntax error; turning it into+0makes it valid without changing the result.Update: Somehow I've made this work for part 2 as well — see this separate post.
† What do you mean it doesn't make sense for a bunch of keystrokes to have such a program-centric concept as a main loop?
‡ Citation needed.
19
u/jonathan_paulson Dec 03 '23 edited Dec 03 '23
[LANGUAGE: Python]. 546/223. Solution. Video.
Oof. Very rough day for me; I submitted 4 wrong answers to part 1. I initially forgot to check for numbers at the end of a line, but then I thought the issue was that I hadn't handled negative numbers correctly, so it took me a while to realize negative numbers were not a thing, and then go back and fix the original bug.
I wish the problem statement had clarified cases like "-932" (which counts as "932" next to the symbol "-"). It seems plausible to me that it could have counted as either "-932 not next to a symbol" or "-932 next to the symbol '-'")
13
u/voidhawk42 Dec 03 '23 edited Dec 03 '23
[LANGUAGE: Dyalog APL]
Video walkthrough
10
u/delventhalz Dec 03 '23
[LANGUAGE: JavaScript]
1503/928
Feeling good about all the matrix utilities I have been building up over the years. Top 1000 is a rare feat for me and being able to quickly grab a
eachSurroundinghelped a ton.Other than that it was just a matter of walking backwards until I found the start of the number, then walking forward until I found the end, and marking the number so I didn't accidentally double count it.
10
u/[deleted] Dec 03 '23
[LANGUAGE: Google Sheets]
Assuming the input is in A1
Part 1
18
u/8bitTrebuchet Dec 03 '23 edited Dec 03 '23
[LANGUAGE: TypeScript]
Did part 1 using almost entirely a single Regex
8
u/CCC_037 Dec 03 '23
[Language: Rockstar]
There are so, so many ways that this could have gone better.
Nonetheless. Done. Eventually.
Now let's see about Part 2...
7
u/Smylers Dec 03 '23
[LANGUAGE: Vim keystrokes]
Much to my surprise, I seem to have solved part 2 as well:
The set-up in the first 2 lines is the same as for part 1: avoid the literal edge cases and make all the digits lower-case. Then we have some nested loops.
@bis defined similarly to@ain part 1: it finds a*, turns it into a., draws a visual block of the adjacent characters, and makes them upper-case. Then it adds an empty line at the bottom of the buffer, and runs the nested macro@c. It does this with:norm @cto suppress nested errors: the loop inside@c(which hasn't actually been defined yet, but don't worry about that) will terminate with an error (because that's the way that Vim keyboard macro loops terminate at all). To avoid that error also terminating the outer loop in@b, we need it not to be an error outside of@c, and handily:normprovides that sort of protection.Once
@bhas been recorded, including invoking the empty placeholder@cbefore looping itself with@b, record@c: find an upper-case digit, which indicates a number adjacent to the current*. Make the entire number lower-case, then copy it. Append a space and the copied number to the bottom line, then loop to do this with any other numbers adjacent to this*.Once all the
*have been processed there will be new lines at the bottom of the schematic listing the numbers around each*. For the sample input it will be:(Hard to see here, but there's a space at the beginning of each line.) A gear's rows will have exactly 2 numbers in it, so use
:v/\v^( \a+){2}$/dto delete all the rows that don't have exactly 2 numbers. This also usefully gets rid of the schematic, which isn't required any more either. Then convert the letters back to conventional digits, the same as in part 1, and also turn the first space on each line into a+and the second one into a*. For the sample input, that'll be:Join the lines together, evaluate the expression in the usual way, and that's the gear ratio sum.
7
u/xPaw Dec 03 '23 edited Dec 03 '23
[LANGUAGE: C#]
I don't parse the input into a grid, and I don't keep any hash maps, I just scan for symbols, check for any digits in 3x3, and then find beginning of these numbers to then parse them.
Benchmark.NET reports 0.0295 ms.
EDIT: I changed it to use
SearchValuesandIndexOfAnyExceptinstead of checking for characters in a loop, that made it 0.0146 ms.https://github.com/xPaw/adventofcode-solutions/blob/master/2023/Answers/Solutions/Day3.cs
7
u/blueg3 Dec 03 '23
[LANGUAGE: Python]
Part 1 is four lines:
Part 2 is five lines:
6
u/Radiadorineitor Dec 03 '23
[Language: Dyalog APL]
5
u/JustinHuPrime Dec 03 '23
[LANGUAGE: x86_64 assembly with Linux syscalls]
Today, the "Linux syscalls" part became relevant (beyond actually getting the input) since I had to dynamically allocate some memory - it's quite interesting to figure out how
mallocor your language's equivalent works, down to how it asks the operating system for more memory.In part 1, I first found the size of the schematic (assuming it was square), and then allocated a 2-d array to store info about the grid. I decided that I would use a variant of pointer tagging - I allocated a word (16 bits) for each input character, and if the first bit was on, it was a non-number, otherwise, it was a number. The allocated space also had padding such that for any actual input values, it always had eight neighbours. I then read the input, and when I encountered a number, I stored its numeric value in the spaces of each of its digits. Blank spaces were left as zero, since that's the additive identity.
Next, I traversed the array, and for each symbol I added the contents of each adjacent cell, except if the top or the bottom cell were a number, I would ignore the cells to the left or right of that top or bottom cell - this avoids the issue where the top three cells had two or three occupied by the same number. This doesn't quite work if parts could be adjacent to each other or to the same number, but that didn't happen in my input.
Part 2 was somewhat more involved. The parsing changed slightly to mark blanks as symbols (whose character was NUL). The actual traversal was a bit more involved. For each star symbol, I counted the number of adjacent numbers whilst storing all of them (there could be up to six to store), treating blanks as one, since that's the multiplicative identity. If there were exactly two, I multiplied all of the stored numbers together, and added that to the accumulator.
Part 1 and 2 both run in 1 ms. Part 1 is 11392 bytes long and part 2 is 11776 bytes long.
5
u/iskypitts Dec 03 '23
[LANGUAGE: Zig]
Part 1 and Part 2
5
u/vkasra Dec 03 '23
[LANGUAGE: Rust]
with #![no_std]
https://github.com/dhconnelly/advent-of-code-2023/blob/master/src/day3.rs
5
u/squareman2357 Dec 03 '23 edited Dec 03 '23
[LANGUAGE: Zig]
I found that pre-processing the input by adding an extra line with '.'s to the top and bottom and an extra column to both ends ameliorated the need to deal with the (literal) edge cases.
GitHub
5
u/presidentpanic Dec 03 '23 edited Dec 03 '23
[LANGUAGE: GDScript]
This one was surprisingly game dev like, the sort of stuff you might do if you're making a 2D tile based game.
Maybe there's a fun way to do it using Godot's built in tile map system.
5
u/[deleted] Dec 03 '23 edited Dec 05 '23
[LANGUAGE: Rust]
My Day 03 on GitHub
My original implementation used HashMap and HashSet, but I have removed them and replaced with a Vec and an array respectively, to bring the runtime for each part down below 400µs. (Last year I got the whole month to run in <1 second total on my machine, and I'm hoping to do similar this year.)
5
u/frabjous156 Dec 03 '23
[LANGUAGE: C#]
Code
Not so efficient but pretty eerhm readable? Any advice appreciated :-)
5
u/Zweedeend Dec 03 '23
[LANGUAGE: Python]
[Allez Cuisine!]
Solution is copied from u/4HbQ
5
u/errop_ Dec 04 '23 edited Dec 04 '23
[Language: Python 3]
Used re.Match objects to get numbers endpoints on the horizontal axis. Everything then boils down to find which symbols are in a rectangular neighborhood of each number.
Paste
5
u/xHyroM Dec 12 '23
[LANGUAGE: Python]
part 1
part 2
4
u/Abomm Dec 03 '23
[LANGUAGE: Python] 289/299
paste
My code was pretty straightforward, I stored 'gear numbers' into a dictionary keyed by the location of the adjacent asterisks. When a second number was added to the same key I added the product of the two numbers. I tried integrating some new strategies like the [-1, 0, 1] array for checking neighbors and the try/except to handle boundaries more easily.
Overall happy with my time, I wrote a few bugs and made some small reading comprehension errors that cost me a minute or two at most, it's nothing that would get me into the top 100 so I feel like there's still something I'm missing to get to that level.
4
u/knl_ Dec 03 '23
[LANGUAGE: Hy]
Fairly mechanical solution today; sadly had to restart my laptop midway which slowed me down :(. Walked through the graph capturing number positions, part positions and gear positions. Then iterated over parts/gears and added adjacent numbers.
https://github.com/kunalb/AoC2023/blob/main/aoc/day03.hy
4
u/[deleted] Dec 03 '23 edited Dec 03 '23
[LANGUAGE: Rust]
I actually did not build a grid for this one.
For Part 1, I used a regex to scan each line for numbers, and stored the number and start position in a vector. I then scanned each line for symbols (anything not a digit or a '.' ) and then stored the symbol and its position in another vector. Then I iterated over the numbers, and for each number, I iterated over the symbols to check if any of the symbols touched that number. If it did, then I stored that number in a table of part numbers. After checking all the numbers, I then summed up all the part numbers.
Part 2 was mostly the same, except that I simplified the symbol check to only check for '*' (gear) symbols. I then checked every number to see if it touched a gear, and if so, I recorded that gear and the number it touched in a table (HashMap). I then iterated over all the entries in the gear table to only get the entries that had two numbers. I multiplied those two together to get the gear ratio, and then stored the result in a vector of gear ratios. I then summed up all the gear ratios.
It's probably not the most elegant solution, but it works.
EDIT - refactored my solutions today to be much cleaner, eliminated the HashMap for Part 2. Now I scan each gear for neighboring numbers and then build the vector of gear ratios as I go.
Part 1
Part 2
4
u/TheZigerionScammer Dec 03 '23
[LANGUAGE: Python]
Well, you can chalk this one up to the "Would have taken me 20 minutes if I didn't have a massive bug I couldn't find" column.
My program was pretty simple. First it goes through the input and finds the locations of all the symbols and puts them in a set. Then it goes through the input again character by character, constructs each number, then places each number as well as it's location data in a list. Then it loops over that list, puts all of the points on the border of the number into a set, intersects that set with the locations of all the symbols, and if there are any intersections then it adds the value to the answer. The problem that cost me over an hour was that I didn't realize that my code wasn't handling the number's location data properly if the number was at the end of a line, and since the example didn't have any I couldn't detect that bug that way either. But I figured it out, added that awkward extra if statement in the number parsing section of the code to handle the cases where numbers were at the end of the line and it worked.
Part 2 was easy comparatively once I had all that groundwork laid out. I just added another if statement to the first loop to check for gears as its checking for symbols, then I just looped over the location of every gear and did a border point set intersection with the list of all the numbers. If it found 2 neighboring numbers and exactly 2 (I don't know if any gears bordered more than 2, but it says EXACTLY 2 so that's what the code does) if multiplied them and added them to the answer.
Code
4
u/stribor14 Dec 03 '23 edited Dec 06 '23
[Language: c++] [Allez Cuisine!]
SPAM is a SPAM because it commes in a CAN. Best served with SPAM, or a SPAM, in a CAN.
(this is a solution to part 2, data is received on can0 frame 0x181 and terminated with 'X')
good luck brave reader:
SPAMness of SPAM, the answer to SPAM, received from CAN
4
u/fatfingers23 Dec 03 '23
[LANGUAGE: Rust]
Code
Reading everyone else’s rust solutions I have decided I know nothing about rust.
4
u/mnocenti Dec 03 '23
[LANGUAGE: Rust]
Day 3 Solution using a simple 2D Grid implementation
Part 2 could be faster, right now I'm iterating over all numbers for each gear.
Today I'm mostly proud of how I restructured my code to make the day-to-day setup easier: now I just need to provide a
parsefunction to parse the input into some struct, and thenpart1andpart2functions to compute each result from the struct. Themain!macro hides all the boilerplate and generate tests for the given example.4
u/sikief Dec 03 '23
[LANGUAGE: C++]
[PLATFORM: Nintendo DS (Lite)]
Solution - Part 1 and Part 2
4
u/plant_magnet Dec 03 '23
[LANGUAGE: R]
https://github.com/ddavis3739/advent_of_code/blob/main/2023/03/code/03.r
The "force everything to be a data table" approach never fails.
4
u/chicagocode Dec 03 '23
[LANGUAGE: kotlin]
I really, really liked today's puzzle. I went with a solution that involves mostly sets of points. For the symbols, I have a set of points representing where they are. For numbers, a set of points for each number representing all of their neighboring spaces (which should overlap with symbols where required).
My code can be found on GitHub, I've written this up on my blog, and here are my 2023 Solutions so far.
4
u/js5n Dec 03 '23 edited Dec 03 '23
[LANGUAGE: Python]
https://github.com/jaysoffian/Advent2023/blob/4994866a783910a1462e8ac21478800ad823074a/day03/day03.py
Coordclass (anamedtuple) is x, y coordinates.Partclass (anothernamedtuple) stores the part number, y coordinate, and x span. It implements abordermethod that return an iterator over the part's border. It returns coordinates outside the graph because it wasn't worth special casing. ThePartclass also implements a hit method that takes a set of coordinates and returns true if any border coordinate intersects with the set of coordinates.Graphclass 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 singleparse()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
4
u/Fit_Ad_1890 Dec 03 '23
[LANGUAGE: Java]
I only did part 1 because it took longer than I thought but I'm happy with the solution.
GitHub
4
u/Desthiny Dec 03 '23
[LANGUAGE: Rust]
https://github.com/AloizioMacedo/aoc2023/blob/master/Rust/day3/src/main.rs
Bad theoretical time complexity, but negligible runtime given the inputs and avoids storing a full matrix.
I am registering my thoughts in the mdbook in my repo.
In general I'm OK with the solution, but I'd like to find an idiomatic way to remove the unreachable that is left, possibly using some pattern matching.
4
u/LetrixZ Dec 03 '23
[LANGUAGE: Rust]
https://github.com/LetrixZ/advent/blob/main/src/bin/day3.rs
I found this alognside the same difficulty as day 2.
4
u/dylan_mojo Dec 03 '23
[LANGUAGE: awk + sed + grep]
Day 3
4
u/jotac13 Dec 03 '23
[LANGUAGE: Rust]
Comments about solution or better rusty-ways are welcome
https://github.com/joao-conde/advents-of-code/blob/master/2023/src/bin/day03.rs
4
u/ObjectWizard Dec 03 '23
[LANGUAGE: C#]
I've made an effort to make my solutions as readable and intuitive as possible. Feedback welcome for readability improvements I could make over the coming days:
https://github.com/objectwizard/AdventOfCode2023/blob/master/Day3.cs
4
u/jaccarmac Dec 04 '23 edited Dec 04 '23
[LANGUAGE: LFE]
code
Took me embarrassingly long and is probably overengineered compared to the non-spawning approach, but this idea jumped into mind when I read the description last night so I had to get it working today.
If there are any LFE (or other Lisp) wizards out there, I'm very confused about how to shorten the pattern in my match-lambda case. It's possible to quasiquote the inner list, but there doesn't seem to be a way to bind the variables inside it when I use LFE's literal syntax for the outside tuple (with or without backquote).LFE requires you to unquote underscores in literals.
4
u/doodlebug80085 Dec 04 '23
[LANGUAGE: Swift]
I feel like each day has been an exercise in different features of this language. Yesterday taught me a lot about regexes in Swift, today taught me more about NSRanges and dictionaries
Code
4
u/basically_alive Dec 04 '23
[LANGUAGE:Javascript]
Is this solution hot garbage? Yes. Did it work on the first try? Surprisingly, also yes
4
u/tsenart Dec 04 '23
[LANGUAGE: Zig]
https://github.com/tsenart/advent/tree/master/2023/3
4
u/zatoichi49 Dec 04 '23 edited Dec 04 '23
[LANGUAGE: Python]
4
u/masterdesky Dec 05 '23
[Language: Standard Python 3.9]
Phew, I tried really hard to compactify this as much as possible. So many things to improve, probably. Also, no 2D arrays. All my homies hate 2D arrays. Tried to combat against weird and edge cases too.
4
u/supercowoz Dec 06 '23
[LANGUAGE: C++]
link to code
Total overengineering: This day is asking us to do a nearest-neighbor search, so why not use a true spatial data structure? I stored the numbers and their expanded boxes in a R-Tree, and then queried the R-Tree with the symbol locations. Stuffed the results in a set (to prevent duplicates), then summed the results.
Part 2 was a piece of cake after all that investment. Query the R-Tree for the gear symbols, check if we get 2 results, and if we do, multiply them and sum them.
I'm so glad all that spatial data structure knowledge is finally coming in handy!
4
u/kip_13 Dec 11 '23
[Language: zig]
Trying to learn zig.
https://github.com/kip-13/aoc23/blob/master/d3/src/main.zig
4
u/mgtezak Dec 12 '23
[LANGUAGE: Python]
github part 1&2
Check out my little AoC-Fanpage:
https://aoc-puzzle-solver.streamlit.app/
:-)
1
u/Lower_Ambition_2147 Dec 15 '23 edited Dec 15 '23
[LANGUAGE: Ruby] Learning refactoring with this year's Advent of Code. Check commits to see the steps!
Main class snippet: paste
Whole solution with history of refactorings as commits: https://github.com/takiarek/advent_of_code_2023_day_3/tree/day_3
1
u/jeis93 Dec 03 '23
[LANGUAGE: TypeScript]
Took me a while to wrap my head around everything, and part 2 stumped me because of some pretty obvious oversights for far too long. Let me know what you think! Happy hacking!
TypeScript x Bun Solutions for Day 3 (Parts 1 & 2)
Edit: Removed the heading, as the AutoModerator didn't like that.
1
u/levital Dec 03 '23
[Language: Haskell]
Don't judge me. :D Not pretty, but worked in the end. Had some issues with first under- and then overcounting, so I ended up with a bit of a mess. At least part 2 was fairly simple after I finally got it right for part 1.
Anyone else feels this is harder than usual? Can't really remember ever reading something as early as day 3 going "ughhh".
1
u/st3fan Dec 03 '23
[LANGUAGE: Python]
https://github.com/st3fan/aoc/blob/master/2023/py/day3.py
I'm again really enjoying using Python for #AdventOfCode.
Like last year my approach is to convert the puzzle input to a high level model using modern #Python features like Data Classes, Enums and strict typing.
It is a bit more work that one-liners but I am not doing this for speed. Instead I want to be better at writing modern robust #Python code.
(Why is it so damn hard to paste a code block to Reddit? Markdown is not allowed and the new "Fancypants" editor completely messes up a code block that looks fine in edit mode. Sigh.)
1
u/CainKellye Dec 03 '23 edited Dec 04 '23
[LANGUAGE: Rust]
https://github.com/cainkellye/advent_of_code/blob/main/src/y2023/day03.rs
1
u/audiocodec Dec 04 '23 edited Dec 04 '23
[Language: C]
This was fun! My code is available here.
1
u/UrbanSuburbaKnight Dec 05 '23 edited Dec 05 '23
[Language: Python]
I used PyTorch for ... reasons.
3
u/goldenlion5648 Dec 03 '23
[LANGUAGE: Python 3]
763 / 357 Github
The problems so far this year have required especially unique algorithms from what it feels (I suspect to fight LLMs). Bring it on! That makes them more fun!
I wrote an "expand" function to make sure a number got completely captured, and added the coordinates used by that number to a "used" set to make sure it wasn't reused later
3
u/seligman99 Dec 03 '23
[LANGUAGE: Python] 32 / 757
github
Today I learned I suck at finding a stupid typo in a short variable name. Ugh.
3
u/NigraOvis Dec 03 '23 edited Dec 05 '23
I feel everyone decided to find the numbers, and then check for surrounding symbols, where I checked for symbols, then found surrounding numbers (and over wrote them as blank once added) part two was a much easier transition for part 2.
When I do
gearcount +=andgearMult *=I realized I didn't check if the symbol was an asterisk. It's a simple line of code. But for some reason I still got the right answer.... I only mention this in case the code doesn't work for you.To be honest. It needs you to check for an asterisk. And with my code. You'd need cloned boards of the original to validate gearMult. Since I clear old numbers. An asterisk could be next to a blank number from a previous find. This means my code doesn't solve the problem. And I think it's pure luck I got this right.
[language: Python]
3
u/CodingAP Dec 03 '23
[LANGUAGE: JavaScript]
Source Code
Part 1: 2053, Part 2: 1318
I keep hitting too many edge cases these past 3 days and it is hard to handle them with no examples. Day 3 wasn't too bad, but I think 2023 overall is going to be a harder year.
3
u/lanerdofchristian Dec 03 '23
[LANGUAGE: PowerShell]
Continuing my habit so far of treating everything as a parsing problem, followed by a single pipeline of actually solving:
3
u/p88h Dec 03 '23 edited Dec 19 '23
[LANGUAGE: Mojo] vs [LANGUAGE: Python]
https://github.com/p88h/aoc2023/blob/main/day03.mojo
https://github.com/p88h/aoc2023/blob/main/day03.py
Mojo pulls out _significantly_ ahead of Python this time.
Also discovered that it doesn't necessarily know how to optimize what should be compile-time constants like
ord('0')- removing these in Part1 helped that pull ahead of Python as well.Overall this language feels much more like C than Python.
Parallelization requires synchronous collections here so skipping, benchmarks below:
3
u/Annual-Management613 Dec 03 '23 edited Dec 03 '23
[LANGUAGE: Ruby]
3
u/Pyr0Byt3 Dec 03 '23
[LANGUAGE: Go] [LANGUAGE: Golang]
https://github.com/mnml/aoc/blob/main/2023/03/1.go
Not particularly proud of this one, but it does showcase my favorite trick for these grid problems: using a
map[image.Point]rune.3
u/CreativeScreenname1 Dec 03 '23 edited Dec 03 '23
[LANGUAGE: Python]
Thought my solution for today was actually kinda neat: this is for part 2
Probably could cut down on some of those manipulations but I was happy with the logic
3
u/SpaceHonk Dec 03 '23
[Language: Swift] (repo)
Luckily my idea for parsing in part 1 turned out to be sufficient for part 2...
3
u/jann3s Dec 03 '23
[Language: TypeScript]
3
u/azzal07 Dec 03 '23
[LANGUAGE: Awk] They're mafic gears.
I made a few simplifying assumptions, but those seem to hold for my input and the example:
3
u/[deleted] Dec 03 '23
[LANGUAGE: Python]
Q1 Q2
I'm quite happy with how today turned out, especially since the way I implemented a solution to part 1 led beautifully into a solution for part 2 with only a few lines of changes.
3
u/greycat70 Dec 03 '23
[LANGUAGE: tcl]
Part 1, part 2.
In my first submission of part 1, I was too high, so I thought that perhaps I would need to remove duplicate part numbers -- the problem statement wasn't clear on this part. When I did some cleanup and removed duplicates, I was too low. Someone clarified in another thread that we are not supposed to remove duplicates, as long as the part numbers occur in different locations. Back to not removing duplicates... and it turns out my cleanup had fixed whatever bug I had originally.
My approach was to scan the grid row by row, from left to right, and identify the numbers, and then see whether each number is adjacent to a "symbol". This works great for part 1 (once I fixed corner cases). For part 2, this isn't enough by itself, but I could tweak it easily enough. I changed the check for "is this a part" to "is this a part that borders a star, and if so, what are the coords of that star". Then I stored all the star-adjacent parts in an array indexed by coords, and iterated over that, only looking at the ones with exactly 2 parts. That tweak took far less time than debugging part 1 did.
3
u/biggy-smith Dec 03 '23
[LANGUAGE: C++]
They ain't messing around when it comes to parsing this year! Finding the positions of all the parts, then doing distance checks worked out for me:
https://github.com/biggysmith/advent_of_code_2023/blob/master/src/day03/day3.cpp
3
u/bdmatatu Dec 03 '23
[Language: Raku]
Part 1
Part 2
3
u/amrutha_nair Dec 03 '23 edited Dec 03 '23
[LANGUAGE: Python]
Day 3 - Part 1 and 2
3
u/TheN00bBuilder Dec 03 '23
[Language: Golang]
Not too bad! Only took like 2.5 hours this time... lol.
Said I'd use maps, but still reverted back to my ways of C and made some 2D arrays. I used some map later in P2 for the asterisk count (make a map based off asterisk position relative to the first byte of the file), but still used the 2D array.
My IsSurrounded() function could be a lot better but in all honesty, I just wanted to be done so I made it relatively slow and meticulous on its checks. I could have skipped a LOT of the checks because if [row-1][col-1] exists, [row-1][col] and [row][col-1] exist too, but it is what it is.
Day 3 Part 1
Day 3 Part 2
3
u/CachooCoo Dec 03 '23
[LANGUAGE: C++]
https://pastebin.com/2CgB8EEH
Much more challenging day for me, mostly because I really wanted to reuse code from part 1. Also, the first day where the performance is almost a concern. Debug mode ran in ~1700ms but Release was "only" ~7ms. A lot of the inefficiency was because I wanted to reuse code but I also could not think of a much better way to calculate part 2.
3
u/babeheim Dec 03 '23
[language: R]
https://github.com/babeheim/advent-of-code-2023/blob/main/day03/solution.R
Solved by transforming the input into a matirix. Part 1 makes a data frame of part numbers and checks adjacent positions in the matrix; part 2 just adds another data frame of the gears and says which numbers are connected by which gears.
3
u/Tipa16384 Dec 03 '23
[LANGUAGE: Python]
Spent way too much time trying to solve this in Haskell. Just doing it in Python and moving on with my day.
3
u/mrvoid15 Dec 03 '23
[LANGUAGE: JavaScript]
Beginner Friendly solution with code and algorithm explanation as comments.
https://github.com/akashdeepnandi/advent-of-code/blob/main/day3/index.js
3
u/atgreen Dec 03 '23
[LANGUAGE: Common Lisp]
Short and sweet: https://github.com/atgreen/advent-of-code-2023/blob/main/03.lisp
3
u/Psychological-Pay806 Dec 03 '23
[LANGUAGE: Rust]
Definitely could be improved but did my best. Happy to have solved.
GitHub Repo
3
u/NotTreeFiddy Dec 03 '23 edited Dec 03 '23
Edit: Updated with part 2.
[LANGUAGE: Rust]
Day 03, Part 01 in Rust 🦀
(Intentionally trying to solve without loading entire input to memory)
3
u/DGL_247 Dec 03 '23
[LANGUAGE: Python]
Code Link
Don't feel great today an it shows in the code. Took a long time to figure out the first one because I kept finding special characters I didn't see. Why I didn't just check if it was a period or number...because I'm sick. I also realized I created a three dimensional array and navigated it with brute force instead of creating an array the normal way. Than again I usually write in Java so this is all new to me. The code works by sending three lines to the function and only the middle line is actually processed for numbers or asterisks. The function than adds up the valid data and ignores the rest.
3
u/Sam_Ch_7 Dec 03 '23
[LANGUAGE: Golang]
It takes me 3 hr for part 1 and 5 minutes for part 2.
Previously I was using box method but failed as one edge case which idk. So after alot of try error,
I used different method where first I find symbol and get number from its neighbour and it works and for part 2 I just need to do very few changes to get it right.
Finally solve it.
Solution below:
https://github.com/xSaCh/advent_golang_2023/tree/main/Day3
3
u/SleepingInsomniac Dec 03 '23
[LANGUAGE: Ruby]
Part 1:
Part 2:
3
u/SurplusSix Dec 03 '23
[Language: Kotlin]
https://github.com/alsm/aoc2023/blob/main/src/Day03.kt
I’ve just started using Kotlin in the last couple of weeks specifically to do AoC in it this year, I write Kotlin like I’m wiring Crystal atm; lots of filter, map, fold etc So far it’s working out pretty well although I’ve got no idea how idiomatic my Kotlin is.
3
u/pavel1269 Dec 03 '23
[LANGUAGE: rust]
https://github.com/pavel1269/advent-of-code/blob/main/2023/day03/src/main.rs
It works, not much to talk about early days :)
3
u/TomQuinn8 Dec 03 '23
[LANGUAGE: Python]
https://github.com/tomquinn8/AdventOfCode/blob/main/2023/Day3.py
Took me a while to get going, stared at it for a bit, considered splitting on '.' for a while, glad I went with regex in the end. I'm sure it could be better but it works.
3
u/Imaginary_Age_4072 Dec 03 '23
[LANGUAGE: Common Lisp]
Day 3
I wrote some parser combinators in an earlier year that kept track of the row / column as it parsed, I think it was for one of the map problems where the location was necessary. Ended up using that to parse the numbers and symbols into two separate lists.
I got slightly held up because I forgot my number parser would also consume a +/- sign if it occurred at the beginning of a number. My input had one of those, which should have been a symbol, so my answer was too low.
After fixing that it wasn't too difficult - just a function to test whether a number and symbol were near to one another and some util functions.
3
u/Redalpha4444 Dec 03 '23
[LANGUAGE: Python]
It's- so slow- but also I'm not entirely sure how to speed it up so?
3
u/kwenti Dec 03 '23
[LANGUAGE: Python]
I viewed the input as a flat array and computed the vicinity of a number by translating the match span. Today's problem was an opportunity to review all the information Python
re.Matchobjects retain.3
u/Own-Appointment8000 Dec 03 '23
[LANGUAGE: JavaScript]
Day 3 Part 2
The idea came to me while thinking about the problem and I knew it was too dumb not to try.
3
u/ray10k Dec 03 '23
[LANGUAGE: Rust]
Re-solved it, flipping my earlier logic upside down. day 3
3
u/Admiral_DJ Dec 03 '23
[LANGUAGE: Python]
Anyone felt as stupid as I did and went overkill? This could use soo so much optimisation......
paste
3
u/timvisee Dec 03 '23
[Language: Rust]
Fast, short and concise:
3
u/Robin_270 Dec 03 '23
[LANGUAGE: Python]
Yet another fun-to-solve puzzle today. So I did my best and found in my eyes a pretty good solution.
As always available in my GitHub repository here.
3
u/tuijnman Dec 03 '23
[Language: Rust]
Feels like an inelegant solution but couldn't find a ton of time to work on it today -.- might refactor it a bit later on
GH Repo
3
u/Krryl Dec 03 '23
[LANGUAGE: Python]
3
u/Kazcandra Dec 03 '23
[LANGUAGE: Rust]
Not a fan of either parts tbh, but I got through the day and that's eventually all that matters.
3
u/lscddit Dec 03 '23 edited Dec 03 '23
[LANGUAGE: Python]
Part 1:
Part 2:
3
u/anatedu86 Dec 03 '23 edited Dec 03 '23
[LANGUAGE: Awk]
Idea:
n-1(middle line).0123456789., iterate over neighbors. (indicesi-1,i,i+1of linesn-2,n-1,n)..in input data.*char.*where discovered.Sol. Part 1:
Sol. Part 2:
3
u/aexl Dec 03 '23
[LANGUAGE: Julia]
Not particularly proud of my today's solution, because I did not find a clever way to combine the ideas from part 1 with part 2. But at least everything worked on the first try...
Solution on GitHub: https://github.com/goggle/AdventOfCode2023.jl/blob/main/src/day03.jl
Repository: https://github.com/goggle/AdventOfCode2023.jl
3
u/mantelisz Dec 03 '23
[LANGUAGE: Java]
Took a bit more effort than the previous puzzles, but got it to look quite neat after some refactoring.
Both parts: https://github.com/MantasVis/AdventOfCode/blob/master/src/advent/of/code/days/day3/Day3.java
3
u/Chib Dec 03 '23 edited Dec 03 '23
[LANGUAGE: R] data.table made quick work of Part 2. I struggled a lot with how messy everything ended up being when I was trying to get good column names directly out of melting a list, or worse yet, trying to condense indexing an array with
%in%.Part 1:
Part 2:
3
u/DeSnorroVanZorro Dec 03 '23 edited Dec 03 '23
[LANGUAGE: R]
3
u/codertee Dec 03 '23 edited Dec 04 '23
[LANGUAGE: Python 3.12]
I read through Match and dictview example docs for this one.
Match.startandMatch.endmade it easy to create a set of coordinates around numbers which can be used to check symbols. github3
u/Handsomefoxhf Dec 04 '23
[LANGUAGE: Go]
The second part was trivial when I got the first one, but I did run into some funny problems with the first one.
GitHub
3
u/mvorber Dec 04 '23
[LANGUAGE: F#] https://github.com/vorber/AOC2023/blob/main/src/day3/Program.fs
Can probably clean it up more. 3rd day of using F#
3
u/madSimonJ Dec 04 '23
[LANGUAGE: c#]
Pretty tough today. I always find the 2-d grid ones a challenge. I got there in the end. Luckily it was a snow day, and not much to do besides this and watch a Christmas film.
https://github.com/madSimonJ/FunctionalProgrammingWithCSharp/blob/main/AdventOfCode/AdventOfCode/2023/Day03.cs
3
u/jdarnold33 Dec 04 '23
[LANGUAGE: c#]
Not too tough. I change my approach about halfway thru and it took me a while to catch all the errors though. Like it when my part 1 approach is general enough to use for part 2.
https://github.com/jdarnold/AdventOfCode2023/tree/main/Day3
3
u/sr66 Dec 04 '23
[LANGUAGE: Mathematica]
Part 1:
Part 2:
3
u/CelestialDestroyer Dec 04 '23
[LANGUAGE: Chicken Scheme]
A bit on the late side from me, and a very verbose solution: https://gitea.lyrion.ch/zilti/Advent-of-Code-2023#headline-22
3
u/InfamousClyde Dec 04 '23
[Language: Rust]
Code for Part 1. Part 2 was a fast modification, I can post it if there's interest.
I don't think it's the most efficient solution, because it makes quite liberal use of a few different data structures. But I think it's quite readable, and easy to parse. Converting the input data into a collection of enums is a rusty superpower.
Basically, iterate over symbol neighbours, "capture" neighbouring numbers with a double-ended queue, which let me append left or right to the number, while marking as visited. It was great once it clicked!
Happy for feedback. Would definitely love to move towards a more functional style-- couldn't really figure out how to iterate over the grid and mutate it in place. Didn't want to reach for RefCells or anything, but I'd be interested in trying again.
3
u/skinman55 Dec 04 '23 edited Dec 04 '23
[LANGUAGE: C#]
https://github.com/skinman55/AOC2023/blob/master/Day3/Day3.cs
3
u/tamale Dec 04 '23
[LANGUAGE: Python]
https://pastebin.com/v2b1AbCd
I found the key is to create small tests that verify all the various placements first and then let it rip on the real thing.
3
u/YPFL Dec 04 '23
[LANGUAGE: C#]
3
u/s3aker Dec 04 '23
[LANGUAGE: Raku]
solution
3
u/Ok-yea-sure Dec 04 '23
[LANGUAGE: JavaScript]
Part 1
Part 2
3
u/bozdoz Dec 04 '23
[LANGUAGE: Rust] First time doing rust. Feels like I’m nesting too much with if let Some…
https://github.com/bozdoz/advent-of-code-2023/blob/master/day-03/src/main.rs
3
u/MagiMas Dec 04 '23 edited Dec 04 '23
[Language: python]
I tried to use only 2d array operations and numpy array indexing but in the end had to resort to a dict for part b
3
u/Potential-Series-105 Dec 04 '23 edited Dec 04 '23
[LANGUAGE: Ruby]
part 1. 195 bytes.
part 2. 224 bytes.
3
u/sinsworth Dec 04 '23
[LANGUAGE: Python]
Was quite fun to solve as an image processing problem. Curious if others also approached it this way.
3
u/[deleted] Dec 04 '23 edited Dec 04 '23
[Language: R 4.3.0]
3
u/chubbc Dec 04 '23
[LANGUAGE: Uiua]
Jesus doing 2D stuff was tricky... but managed to vectorise everything in the end :)
3
u/TiltSword Dec 04 '23
[LANGUAGE: Java] Part 1-
Part 2-
3
u/aviral-goel Dec 05 '23 edited Dec 05 '23
[LANGUAGE: F#]
https://github.com/aviralg/advent-of-code/blob/main/2023/03/solution.fsx
3
u/psaikido Dec 05 '23 edited Dec 05 '23
[Language: c]
day 3 part 1
day 3 part 2
3
u/masasin Dec 05 '23
Python with numpy
3
u/bamless Dec 06 '23 edited Dec 06 '23
[LANGUAGE: J*]
Slowly catching up... :)
Part 1
Part 2
3
u/Best_Pirate_69 Dec 06 '23 edited Dec 06 '23
[LANGUAGE: Ruby]
Regex and Ruby rock!
Part 1
Part 2
3
u/Pseudo_Idol Dec 06 '23
[LANGUAGE: PowerShell]
Day 03 Part 1
3
u/Alex_Hovhannisyan Dec 08 '23 edited Dec 09 '23
[Language: C++]
Part 1
Currently stuck on part 2... seems brutal since my solution won't translate over well.Edit: Part 2. Eventually figured it out after scrapping some other naive solutions. I did have to rewrite my program because of how I chose to solve part 1. The trick was to keep track of all the gear locations (row, col) in a vector, as well as the starting locations of all numbers in a separate vector (along with the string representation of the number as I built it up). Then, for each gear location, loop over all possible number locations and check that:
Keep track of all those adjacent numbers for the gear; if you have exactly
Nsuch numbers (in this case 2), convert them to ints, multiply them, and add to the running sum.3
u/orbby Dec 08 '23
[Language: R] I don't even know how I did this anymore but it worked.
3
u/arthurno1 Dec 08 '23 edited Dec 08 '23
[LANGUAGE: EmacsLisp]
3
u/bofstein Dec 09 '23
[LANGUAGE: Google Sheets]
This was a real challenge for me, took multiple days to figure out, and had to use 9 separate sheets. Initially did Part 1 by hand searching, though later when I solved part 2, that solution would have solved Part 1 too. Very satisfying to finally get it though
https://docs.google.com/spreadsheets/d/1X1dXpfhWa5IQpcO_Bhllj8zdXLe1g4nUbKbBq0JCiwg/edit#gid=844575306
7(G-AE3)7(G-AE3)5(G-AE3)G-AE3:775. Get that list into one column, sort it, separate the gear number from the part number. Make a gear numbers that have exactly 2 part numbers (this is why I was able to account for any that I incorrectly included earlier), and then find (by doing an XLOOKUP from the bottom and then from the top) and multiple those numbers.I'm SURE there are easier ways to do it but I'm just glad I could finish!
3
u/xXMacMillanXx Dec 09 '23
[LANGUAGE: V]
Github day 03
3
u/errorseven Dec 09 '23 edited Dec 10 '23
[LANGUAGE: AutoHotkey v1.1]
Solution 1
Solution 2
3
u/floflo455 Dec 10 '23
[LANGUAGE: Python]
Both parts in TDD
3
u/minikomi Dec 11 '23 edited Dec 11 '23
[LANGUAGE: janet]
paste
I was quite happy with the parser for this answer
It turns a "field of instructions" into:
Sets of
[type [line column] entry], which makes building a useful data structure very easy.3
u/lsloan0000 Dec 12 '23
[Language: Python]
It took me much longer to get the solution than I expected, but I also started on it well after 03 December. After I had the solution, I decided I could "simplify" it by treating the input as a one-dimensional array. I think it is a bit simpler.
3
u/linnaea___borealis Dec 14 '23
[LANGUAGE: R]
I never see R solutions on here. So I'll start posting mine.
https://github.com/lauraschild/AOC2023/blob/main/day3_A.R
part 1 checks for symbols in the vicinity of each number to count as part numbers
https://github.com/lauraschild/AOC2023/blob/main/day3_B.R
part 2 collects the gears and their position that are adjacent to a number. Only those that are collected twice are summed up.
3
u/andreiz Dec 17 '23
[LANGUAGE: Swift]
Been using it as an excuse to learn Swift. Which, as a language, is... quite nice.
https://github.com/andreiz/advent-of-code-2023-swift/blob/main/day-03/engine.swift
https://github.com/andreiz/advent-of-code-2023-swift/blob/main/day-03/engine-gear.swift
3
u/mgtezak Jan 13 '24 edited Jan 13 '24
[LANGUAGE: Python]
I created a video for this one:)
Or you can view my solution on Github
If you like, check out my interactive AoC puzzle solving fanpage
1
u/dwijyPiggy Dec 04 '23 edited Dec 04 '23
[LANGUAGE: Python 3]
Part 1
Part 2
idk why everyones code is so long
4
u/pred Dec 03 '23
[LANGUAGE: Python] GitHub
Lots of fiddling to get the boundaries just right, but at least
re.finditermakes it easy to determine when numbers start and end.2
u/morgoth1145 Dec 03 '23 edited Dec 03 '23
[LANGUAGE: Python 3] 312/177 Refactored code
I have a grid parsing library which made parsing the grid into coordinates trivial, but that did leave finding the numbers and their borders. Given my rankings I suspect I missed a trick that may have made that easier/quicker as I didn't really feel slow, but oh well. At least the part 2 twist was pretty simple with
collections.defaultdict(to accumulate the numbers next to a candidate gear and come back later to handle candidates neighboring exactly two numbers).(I'm also glad I tested against the sample input today, I had a bug in part 1 that it caught without me needing to suffer a timeout like I did day 1)
I guess I need to step up my game if I'm going to make the top 100!
Edit: After seeing some other parsing code I realized I could simplify my schematic parsing (specifically the border determination) and save code, so I did just that.
2
u/schveiguy Dec 03 '23
[LANGUAGE: D]
https://github.com/schveiguy/adventofcode/blob/master/2023/day3/engine.d
Not in love with how I did the detection of which numbers were in range of a gear. This would not work if there were any numbers that were touching 2 gears. But, it worked, and I don't feel like making it prettier...
2
u/Ununoctium117 Dec 03 '23 edited Dec 03 '23
[LANGUAGE: Rust]
https://github.com/Ununoctium117/aoc2023/blob/main/day3/src/main.rs
std::iter::Iterator::take_whiletakes one more than I expected it to, I thought it would somehow peek at the next element instead of consuming it. Oh well.edit: also I hate regex and refuse to use them >:)
2
u/mendelmunkis Dec 03 '23
[LANGUAGE: C]
Loops within Loops
0.785/1.3 ms
2
u/vanveenfromardis Dec 03 '23 edited Dec 03 '23
[LANGUAGE: C#] 1207 / 2324
GitHub
I really enjoyed this problem, definitely the best one so far. I kept track of the numbers (and the positions the digits occupied), as well as a map of the non '.' symbols, then was able to leverage some of my geometry utils to compute the relevant adjacency checks:
2
u/AllanTaylor314 Dec 03 '23
[LANGUAGE: Python] 319/1046
Code: main (8ba5ec7)
Part 1: Got it wrong 3 times (testing might have been a good idea). Forgot that numbers had lengths when searching around them for parts, then forgot that I started the search just after the number so I didn't need to search two columns to the right, then didn't handle numbers at line ends (so I added a dot to every line)
Part 2: Sat in confusion for a few minutes, false start looking at where gears were before settling on storing the numbers from part 1 in a dictionary of gear locations. First I was storing products, but the number was a bit big (41853281867024288383369428352) so I started storing lists to find out why. Turns out I missed the line about exactly two (I misread that as all the *s are gears, and they have two numbers next to them). Filter the lists with a comprehension and an answer appears (and it's even correct this time). I need to test, and I need to read!
Future improvements:
Search only the spaces around the number, not the spaces in the number itself (i.e. only the hashes in the diagram below, not the whole rectangle).
Combine parts 1 & 2 by building up the dictionary in part 1.
Make handling line endings less hacky
Break it into functions (there's a line nested 6 levels deep!)
2
u/bskceuk Dec 03 '23
[LANGUAGE: Rust]
Solution
I first parsed the numbers into triples of (number, start-end range, included? (false to start)) then went through to find the punctuation and mark the proper numbers as included if their range included the current point. Part 2 was pretty straightforward, seems like my part1 set me up well for it - 1497/760
2
u/Gprinziv Dec 03 '23
[LANGUAGE: Python 3]
I thought that maybe there's a really elegant regex for this, but it's beyond me, so instead I used a loop to just identify numbers quite crudely. As I iterated the list, if I found an engine part (something that wasn't
[0-9] or \.for part 1 and*for part 2), I could just snag all those numbers and add them to the total:This felt good and robust for part 1 and I'm glad I did it this way, since part 2 required almost no changes. Since the generator yielded all values for a given gear, I could discard them if there weren't exactly two values.
2
u/trevdak2 Dec 03 '23 edited Dec 03 '23
[LANGUAGE: Javascript Golf]
Part 1 155 chars, still a bit of a work in progress. Huge amount of convolution just to shave off a few chars here and there.
Part 2 246 Characters.
My part 2 solution isn't great, I spent a lot of time trying to make it work with this regex:
Which would make it easy to find all asterisks adjacent to two numbers, but actually GETTING those numbers was still awful and didn't seem doable in a golf-friendly way.
2
u/x_bit Dec 03 '23
[LANGUAGE: Golang] - 4710/2630
Part 1/Part 2
I wanted to make a grid so I can localize adjacency checks but that can be a tomorrow morning problem for me :)
2
u/JelloRough Dec 03 '23
[Language: Ruby]
I did two different approaches on each part. I missed to see how to adapt part 1 to get part 2 as most of the solutions I have seen. Adding a map when a * was found.
I am learning ruby so suggestions are welcome!
day3.rb
2
u/ivanjermakov Dec 03 '23
[LANGUAGE: TypeScript] github
I think this was the roughest first-10-days day for me.
I initially read the goal inverted (sum of non-part numbers), then it took 10 minutes to trace down end of line edge-case that was not reproducible in example.
Part two meant that none of the part one code can be reused and it took a while to pick the approach. I didn't want to waste time expanding numbers around gears, but I didn't find a better way...
1hr solve for day 3, unbelievable!
2
u/christianqchung Dec 03 '23 edited Dec 04 '23
[LANGUAGE: C++]
Part 1:
I chose the most tedious, error prone way to do check if a symbol exists around a number, but otherwise the problem wasn't too bad.
Part 2:
Same solution logic as above, I just swapped the symbol existing function for one that optionally returns a pair of coordinates if the symbol is a gear. Instead of adding each number to a running sum, if I have a pair of coordinates, I mapped the coordinates to a vector of numbers. At the end I looped through my table and added the multiplied values of vectors which had exactly 2 numbers.
Edit: Video upload
2
u/MechoLupan Dec 03 '23
[LANGUAGE: Nim]
See my comment history for definitions of
dayandpart.New import:
sets2
u/dmart914 Dec 03 '23
[LANGUAGE: Kotlin]
https://github.com/mrdave-dev/AoC-2023/blob/main/src/day03/Day03.kt
I iterated over the string and checked around each symbol, which required me to dedupe each number. I did this by hash mapping the starting digit's position.
My friend finished way before me and later explained that it was much easier to just find every number and check around it... Sigh.
2
u/wheresmylart Dec 03 '23
[LANGUAGE: Python]
I hit this with the regex hammer and let that do all the heavy lifting.
The rest is just bookkeeping.
day3.py
2
u/HAEC_EST_SPARTA Dec 03 '23
[LANGUAGE: Ruby]
Solution on sourcehut
This was a pretty neat problem: I certainly wasn't expecting to be reaching for the
Matrixmodule already on Day 3, but it ended up working quite well to model the grid. I unfortunately lost quite a bit of time to some faulty deduplication logic on Part 1 (the uniqueness constraint should be value, column, and row!), but Part 2 was trivial thereafter.2
u/Comfortable_Key_7654 Dec 03 '23
[Language: Go]
Part 1
Part 2
Used a bunch of
forloops and glued them together with utility functions to solve the problem. Will be trying the same in a more functional/iterative approach with Rust soon.2
u/sim642 Dec 03 '23
[LANGUAGE: Scala]
On GitHub.
Didn't get to use my
Gridlibrary to its full extent because I kept rows asStringss such that I could iterate over all regex matches in them. The regex match gives indices (x-coordinates), so it's easy to look around those for symbols.2
u/brunocborges Dec 03 '23 edited Dec 04 '23
[LANGUAGE: Java]
https://github.com/brunoborges/adventofcode2023/blob/main/src/AoC_03.java
2
u/how_to_not_reddit Dec 03 '23
[LANGUAGE: JAVA]
adventOfCode2023/Day_3.java at main · shavet-akiya/adventOfCode2023 (github.com)
I challenge you to find a worse solution than this :)
2
u/9_11_did_bush Dec 03 '23
[Language: OCaml]
https://github.com/chenson2018/advent-of-code/blob/main/2023/03/ocaml/03.ml
Pretty happy with this. Certain things are pretty slick in OCaml, for instance doing a filter_map and pattern match lets you pretty succinctly express the idea of "symbol that is adjacent to exactly two part numbers".
2
u/duckyluuk Dec 03 '23 edited Dec 03 '23
[LANGUAGE: Python Golf]
Input Parsing:
Part 1:
Part 2:
Stats:
Input Parsing: 11 bytes
Part 1: 244 bytes | 0.152 seconds
Part 2: 271 bytes | 0.005 seconds
Total: 526 bytes
Today was pretty tough to golf down, but in the end I managed to keep both parts a one-liner.
The way I'm looking for numbers in part 1 is very slow (see how much longer it takes than part 2) but it works and it's somewhat small so that's good enough. Might try to improve more later but I'm pretty happy with the sizes for now!
2
u/hextree Dec 03 '23 edited Dec 04 '23
[LANGUAGE: Python]
Code: https://gist.github.com/HexTree/860c98300e79592887191255cd77c890
Video: https://youtu.be/d7NU8YJkXCQ
Go through the grid row by row, find the first and last digit of each contiguous number. Use a helper method to collect all the valid neighbours of all the digits, into a set.
For part 1, straightforward to check the set for symbols. For part 2; for each asterisk found in the above process I update a hashmap which maps the asterisk's coordinates to a list of numbers adjacent to it. After that hashmap is fully built, I can then pick out the gear ratios.
2
u/glebm Dec 03 '23 edited Dec 03 '23
[LANGUAGE: Ruby]
Part 1:
Part 2: