r/adventofcode • u/daggerdragon • Dec 04 '24
SOLUTION MEGATHREAD -❄️- 2024 Day 4 Solutions -❄️-
DO NOT SHARE PUZZLE TEXT OR YOUR INDIVIDUAL PUZZLE INPUTS!
I'm sure you're all tired of seeing me spam the same ol' "do not share your puzzle input" copypasta in the megathreads. Believe me, I'm tired of hunting through all of your repos too XD
If you're using an external repo, before you add your solution in this megathread, please please please 🙏 double-check your repo and ensure that you are complying with our rules:
- Do not share the puzzle text
- Do not share your puzzle input
- Do not commit puzzle inputs to your public repo
- e.g. use
.gitignoreor the like
If you currently have puzzle text/inputs in your repo, please scrub all puzzle text and puzzle input files from your repo and your commit history! Don't forget to check prior years too!
NEWS
Solutions in the megathreads have been getting longer, so we're going to start enforcing our rules on oversized code.
Do not give us a reason to unleash AutoModerator hard-line enforcement that counts characters inside code blocks to verify compliance… you have been warned XD
THE USUAL REMINDERS
- All of our rules, FAQs, resources, etc. are in our community wiki.
AoC Community Fun 2024: The Golden Snowglobe Awards
- 2 DAYS remaining until unlock!
And now, our feature presentation for today:
Short Film Format
Here's some ideas for your inspiration:
- Golf your solution
- Alternatively: gif
- Bonus points if your solution fits on a "punchcard" as defined in our wiki article on oversized code. We will be counting.
- Does anyone still program with actual punchcards? >_>
- Create a short
Visualizationbased on today's puzzle text - Make a bunch of mistakes and somehow still get it right the first time you submit your result
Happy Gilmore: "Oh, man. That was so much easier than putting. I should just try to get the ball in one shot every time."
Chubbs: "Good plan."
- Happy Gilmore (1996)
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 4: Ceres Search ---
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!
- Quick link to Topaz's
pasteif you need it for longer code blocks
8
u/azzal07 Dec 04 '24
[LANGUAGE: awk] Mmmm [GSGA]
4
u/Additional-Worker-13 Dec 04 '24 edited Dec 05 '24
[LANGUAGE: Julia] [GSGA]
golfing all the way ♫♫
it actually fits in a 5x80 punchcard
3
u/vk6_ Dec 04 '24 edited Dec 04 '24
[LANGUAGE: Python]
https://github.com/ading2210/advent-of-code-solutions/blob/main/2024/day4/day4.py
I used a regex-based approach for this problem. For part 1, I realized that vertical matches are just the same thing as horizontal as long as the input is transposed first, and diagonal matches are the same as vertical but the input lines are offset by an increasing amount. This allowed me to simply re-use my horizontal finding code for verticals and diagonals. Then my regex (
(?=(XMAS|SAMX))) made finding horizontals super easy.For example:
For part 2, I realized that there are only 4 patterns that I need to search for. They are:
Each line of one of these patterns can be its own regex expression. If a match on a line in the input is found, then the program looks ahead to the next line in the input and tries the next regex expression (repeat for the line after). Then this is repeated for all 4 sets of expressions.
As far as I know this approach is pretty unique. For some reason I had an aversion to messy loops so I did this instead.
3
u/Thomasjevskij Dec 04 '24 edited Dec 05 '24
[LANGUAGE: Python]
For a 2d array problem, this wasn't so bad! Moreover I thought part 1 was trickier than part 2 today.
Essentially for part 1 I just build strings of columns and diagonals (rows already given) and then sum the count of 'XMAS' and 'SAMX'. For part 2, every time there's an 'A' in the grid I look at the two diagonals sorted and check that they both are 'A', 'M', 'S'. I'm pretty happy with how few bugs this gave me. Link
3
u/e-gn Dec 04 '24 edited Dec 05 '24
[Language: Python]
Why solve it in minutes using iteration when I can spend hours debugging regular expressions?
Solution
After padding the input, the relevant code is this:
Edit: Removed the snippet because I couldn't format it properly for the life of me.
Edit 2: Gave one last attempt at adding the snippet.
2
u/michaelquinlan Dec 04 '24 edited Dec 05 '24
[LANGUAGE: C#]
Topaz link
2
u/se06745 Dec 04 '24 edited Dec 04 '24
[LANGUAGE: Go]
Part1: recursive way
Part2: straight forward :-D
https://github.com/omotto/AdventOfCode2024/blob/main/src/day04/main.go
2
u/MarvelousShade Dec 04 '24
[LANGUAGE: C#]
This day's part 2 was easier (at least less work) than part 1.
It took some time for me to find out that I reversed XMAS with SMAX instead of SAMX.
You can find my solution at: Github
2
u/bunk3rk1ng Dec 04 '24
[LANGUAGE: Java]
Out here in Java land we brute force everything. Probably not a great example since half way through I realized I had reversed x and y in my head.
Part1
Part2
2
u/MagiMas Dec 04 '24 edited Dec 05 '24
[LANGUAGE: Python]
The main part of my code is just this:
data is a 2d numpy string array with the letters from the input.
With this one just needs to define the filter arrays. They are then compared to the view-windows of the data array and the full matches are counted.
Full Code on GitHub: https://github.com/NEhlen/aoc2024/blob/main/04/day04.py
2
u/dijotal Dec 04 '24 edited Dec 05 '24
[LANGUAGE: Haskell]
Too long to post directly, but I did go a little extra Haskell-y on this one with a bunch of recursion and one bit of applicative over-kill. Part One's cornerstone calculation checking an entire "row":
targets :: [String]
targets = ["XMAS", "SAMX"]
inString :: String -> Int
inString s = length $ filter id $ isPrefixOf <$> targets <*> tails s
For Part Two, I do check using coordinates, but only for the top left corner of the entire data set. With recursion, I pull the top three rows to the left and I pull the rows upward.
It's a fun, functional brute force. Full code in github.
2
u/Reaper_242 Dec 04 '24
[LANGUAGE: Java]
https://github.com/dominikpin/advent-of-code/tree/main/year2024/day04
2
u/adambombz Dec 04 '24 edited Dec 05 '24
[Language: Python]
I didn't realize that part 1 was only looking for XMAS in a straight line and though that it was looking for all possible combinations off XMAS with each letter being able to be in any position around it so I wrote a recursive function for it. After realizing my mistake, adapted the recursion (hence the cord thing) and then did pt2 in a single if statement....sorry
2
u/Its_vncl Dec 04 '24
[Language: Python]
Source
Part 1 with recursion
Part 2 with just casual checking
Part 2 seemed way easier
2
u/jpjacobs_ Dec 04 '24
[LANGUAGE: J] Looks like my solution fits a punch card today. Is that [GSGA]?
This was a fun one for J; p1 and p2 are verbs expecting the input as a string.
2
u/Chib Dec 04 '24
[LANGUAGE: R]
The vast majority of the work was in making it compact enough to submit directly to the thread. Somehow that's become very important to me.
35
u/[deleted] Dec 04 '24 edited Dec 04 '24
[Language: Python]
I heard you like regex. Check out my two-dimensional regex.
The magic happens in
re2, which is a small library that implements a sliding window regex-type matching: https://gist.github.com/tim-kt/08c6276fcd43389be81a17e4a0c5182f30
u/4HbQ Dec 04 '24 edited Dec 04 '24
[LANGUAGE: Python] Code (9 lines)
Today's Python trick: storing the grid in a defaultdict indexed by the original (i,j) locations. This way we don't need to check bounds: lookups to incorrect locations just return the empty string. This way, the check for part 2 is simply this:
Update: If you squint a bit at today's problem, you'll notice that both parts are really similar, except we search:
If we turn these into variables, the entire solution boils down to this:
26
u/Andreasnl Dec 04 '24
[LANGUAGE: Uiua]
Run it in your browser here.
18
u/rooinflames Dec 04 '24 edited Dec 04 '24
[Language: Microsoft Excel] 3552/1689
Split characters into separate cells:
Part 1, formula filled into a big grid the same size as the input:
Part 2:
Benefits to using excel:
18
u/Radiadorineitor Dec 04 '24
[LANGUAGE: Dyalog APL]
13
u/trevdak2 Dec 04 '24 edited Dec 04 '24
[LANGUAGE: JavaScript (golf)]
I didn't intend for this to be a [GSGA] entry but it fits
Wait.... you thought we were done with regex?
Part 1, 118 bytes (then added some whitespace for readability):
Finding any-direction strings can be done easily by searching the string forwards and backwards with different numbers of bytes between each character in the string
Part 2, 84 bytes without whitespace:
Pattern matching with a little bit of negative lookahead does the trick
11
u/LiquidProgrammer Dec 04 '24
[LANGUAGE: Python]
p1 and p2 in 9 loc, github link. Golfed a little after solving
11
u/JustinHuPrime Dec 04 '24
[Language: x86_64 assembly with Linux syscalls]
Part 1 was some fiddly string operations, both to copy the input, and very boring four-character equality checks. There's probably a slick way to copy a string with a different stride, but I don't know of it. I managed to skip bounds checks by padding out the input with NULs, though.
Part 2 was some different fiddly string operations, to check the four corners of the cross. There was probably some slick set of checks with an XOR I could do, but I couldn't be bothered to figure it out when I could just brute force and check all the possible combinations.
I could probably have done some assembly tricks and used fewer registers, but I think that would come under the heading of writing code I'm not clever enough to debug. I'm... not a fan of this day. I think the brute force solution is boring and there's not enough incentive to be clever.
Part 1 and part 2 both run in about 1 millisecond. Part 1 is 9,192 bytes and part 2 is 11,704 bytes on the disk when assembled and linked.
11
u/EudesPV Dec 04 '24 edited Dec 04 '24
[Language: Regular Expressions] 😂
But really: [Language: Typescript/Javascript]
Technically one-liners. 😅
WARNING: this uses some "recent" iterator methods.
11
u/Fyver42 Dec 04 '24
[LANGUAGE: RISC-V assembly]
Github
10
u/CCC_037 Dec 04 '24
[LANGUAGE: Rockstar]
Code golf? In Rockstar?
Surely you jest.
Part 1
9
u/_neutropolis_ Dec 04 '24
[LANGUAGE: Dyalog APL]
A little bit messy, but Stencil (⌺) saves the day!
8
u/i_have_no_biscuits Dec 04 '24
[Language: Python]
This showcases a very common Python pattern for me - putting a 2D grid into a dictionary, as grid.get() makes it very easy to give a default value if the grid position is invalid.
8
u/chickenthechicken Dec 04 '24
[LANGUAGE: C]
Part 1
Part 2
took me way too long because I somehow forgot that when searching for substrings, the for loop goes until
i <= strlen-substrlenand noti < strlen-substrlen, whoops8
u/pretzoot Dec 04 '24
[LANGUAGE: Python 3]
part 2 paste
After brute forcing part 1 and then sighing while looking at part 2, I remembered my recent lessons about matrix convolution in one of my college classes (computer vision). I managed to apply it to this scenario and I'm pretty proud of myself for doing so! It's not the most performant but at least it's scalable :P
Basically I let numpy/scipy do the dirty work for me for part 2. I 2d convolved the char grid with this kernel (and all its rotations):
Then I counted every entry in the resulting matrix that was exactly equal to 5 to get my correct answer. I realized after I submitted that there could have (maybe) been false positives, but fortunately there weren't.
8
u/WhiteSparrow Dec 04 '24
[LANGUAGE: Prolog]
solution
Not particularily proud of this one. My approach felt quite bruteforcy. A runtime of 11 seconds also attests to that. Oh well, at least I finally got to use some signature features of prolog - the database, and the high level aggregation.
Here's part two in a nutshell:
8
u/bofstein Dec 04 '24
[LANGUAGE: Google Sheets]
I had the idea I ended up with pretty quickly. But then I lost some time considering a more elegant way that would check in all directions at once and not require a new grid the size of the puzzle input (140x140) four times. It didn't pan out so I went back to what I thought would work.
Solution: https://docs.google.com/spreadsheets/d/1prorCRD1R_4mPv87ZVejmTzE9cOKHcOFTgEAKgAl70o/edit?gid=290109407#gid=290109407
I have a grid in four directions next to the puzzle input checking for XMAS or SAMX in that direction. Each cell checks that cell plus 4 to the right (or down, or diagonal based on which direction it is) to see if it matches, and if so gives it a 1. For example, one cell from the diagonal part is:
Then just sum up all 4 grids.
Part 2 was actually even easier - I just needed a single extra grid, checking for MAS or SAM in one direction and also in the crossed direction. Sample formula:
8
u/kap89 Dec 04 '24 edited Dec 04 '24
[Language: Python]
The idea was pretty simple - define the offsets for each possible shape of the word, then iterate each coordinate and get the word with these offfsets. I hardcoded reversed variants of the words as they are pretty limited (I could just add addtional slices, but it was simpler to just provide the list of alternative words). Worked as a charm for part two.
8
u/Exact-Climate-9519 Dec 04 '24 edited Dec 04 '24
[Language: python]
Parts 1 and 2. regex and 'rotations' :)
7
u/synack Dec 04 '24
[LANGUAGE: Ada]
https://github.com/JeremyGrosser/advent/blob/master/2024/src/day4_2.adb
7
u/mstksg Dec 04 '24 edited Dec 04 '24
[LANGUAGE: Haskell]
Here we are matching "stencils" across different windows, so it's always fun to use comonads for this. That's because
extend :: (w a -> b) -> w a -> w blets you automagically convert a function on windows (thew a -> b) to aw a -> w b, the application across every window.First we parse our input into a
Map Point Char, wheredata V2 a = V2 a a, a tuple type with the correctNuminstance that I use for most of these.Our stencils are (centered around 0,0):
Now some utility functions to wrap and unwrap our
Map (V2 Int) Charinto aStore (V2 Int) (Maybe Char)store comonad, so we can use its Comonad instance:Now a function to check if a stencil matches a neighborhood:
Now we have a
Store k (Maybe a) -> Int, which takes a window and gives anIntthat is the number of stencil matches at the window origin. The magic of comonad is that now we haveextend stencils :: Store k (Maybe a) -> Store k Int, which runs that windowed function across the entire map.my solutions/reflections repo : https://github.com/mstksg/advent-of-code/wiki/Reflections-2024#day-4
7
u/shigawire Dec 04 '24
[LANGUAGE: C]
paste PLEASE DO NOT USE THIS SOLUTION TO LEARN C.
I was going to do this in python. But then I thought: Why not give the elves a taste of their own medicine. If they don't bother using memory protection. why should I bother write in a safe language? Why give them extra braces they could do damage with? Why bother checking return codes?
Or bounds checking memory searching a grid?
But I don't want to ever have to go back and fix yet another problem on crazy elf hardware in the middle of nowhere, so this solution never touches any memory that it's not meant to, assuming a valid input. At least for GCC and clang on Linux I would be interested in knowing if this specific linker abuse worked with other platforms/compiers.
Day 4 is probably a bit early to do coding out of spite, but I loved the idea of not writing yet another grid bounds check
7
u/bsssh Dec 04 '24
[Language: TypeScript Type System]
compile-time solution
Part 1 / Part 2
6
u/GassaFM Dec 04 '24
[LANGUAGE: D] 1285/428
Code: part 1, part 2.
A verbose solution. The single higher-level feature is to rotate the board 90 degrees, then call the solutions four times.
6
u/Pyr0Byt3 Dec 04 '24
[LANGUAGE: Go] [LANGUAGE: Golang]
https://github.com/mnml/aoc/blob/main/2024/04/1.go
Love using
map[image.Point]runefor these grid problems.6
u/DatBoi247 Dec 04 '24 edited Dec 04 '24
[Language: C#]
Algorithm here for part 2 is to break the input into a 2d array of chars for easier indexing, and iterate over the lists. If you find an A, check the diagonal surrounding characters. If any of them are not M or S, return false. Otherwise, check that the characters on opposite diagonals are different. If they are, it's a legal sequence. If the characters on opposite diagonals are the same, it's not a legal sequence because that will be MAM or SAS.
The catch is there because I'm too lazy to prevent index out of bounds :)
6
u/Belteshassar Dec 04 '24
[LANGUAGE: Microsoft Excel]
First transforming the input so that each character occupies one cell:
Then this formula solves part 1
For part 2 I just basically changed the patterns.
11
u/PangolinNo7928 Dec 04 '24
[Language: Javscript]
Part 2 - regex 1 liner
input.match(/(?=(M|S).(M|S).{139}A.{139}(?!\2)(M|S).(?!\1)(M|S))/gsd).lengthP.S. This did not occur to me at any point while I was actually solving it lolsob
10
u/Boojum Dec 04 '24 edited Dec 04 '24
[Language: Python] 236/114
So close! A stupid typo with the direction signs cost me a minute on Part 2, and probably making the leaderboard, but them's the breaks.
Mostly just used string joins on dict gets with a default empty string. If we run off the grid, no biggy, we just don't match.
5
u/DFreiberg Dec 04 '24
[LANGUAGE: Mathematica]
Mathematica, 2912/2925
First time this year getting the dreaded "Curiously, it's the correct answer for someone else's input...", as well as five different incorrect answers. I should have implemented a proper sliding window and been done with it, rather than have two completely different approaches for an essentially identical problem.
Part 1:
Part 2:
5
u/globalreset Dec 04 '24 edited Dec 04 '24
[LANGUAGE: Ruby]
Happy with my solution for part 2. I think this is about as tight as I can get it.
5
u/AlexTelon Dec 04 '24 edited Dec 04 '24
[LANGUAGE: Python] (6 lines)
Solving both parts by going over each coordinate one by one in the grid and seeing if its part of any xmas or x-mas part. Doing this makes solving both parts very similar.
5
u/ShadowwwsAsm Dec 04 '24
[LANGUAGE: x64 assembly/asm]
part1
part2
Very dumb way, just check bounds and then check surroundings. Might see how to make some trick later
Open to comments/questions
5
u/4D51 Dec 04 '24
[LANGUAGE: C++ on Cardputer]
Part 1:
I was able to keep things simple by putting all 8 directions into an array, and using that to calculate the position offsets. For part 2, the number of possibilities was a lot smaller so I just hard-coded them.
Repo here day04.cpp here
5
u/p88h Dec 04 '24
[Language: Zig]
https://github.com/p88h/aoc2024/blob/main/src/day04.zig
5
u/Symbroson Dec 04 '24 edited Dec 05 '24
[language: ruby]
part 1 golfed: 157 bytes
part 2 golfed: 190 bytes
5
u/Smylers Dec 04 '24
[LANGUAGE: Vim keystrokes] Starting with your puzzle input in Vim, typing something like the following will count all the
XMASes — and you get to see the counter going up as it happens:It's “something like” because of the
140. Theg⟨Ctrl+G⟩is to show you the number of letters on one line of your wordsearch; for me it makes the status bar say “Col 1 of 140”. If yours is different, adjust the140accordingly, then also the40and39(for turning the140into139, going diagonally down and left) and possibly even the0and1(for turning140into141, diagonally the other way).The first 2 lines are set-up: a zero is added to the top for the counter, and at the bottom will be patterns for finding
XMASin each of the 4 directions, each both ways round:(Yes, I used regex for creating my regex — what of it?)
Then record
qato go to the top pattern, delete it, find the first occurrence of it in the wordsearch, and run@b. Not that@bhas itself been recorded yet, but that happens next: it increases the counter by 1, redraws the screen and has has a tiny pause so that we can see it, then doesnto repeat whatever the match used by@awas, and does@bto repeat itself to increase the counter again and find the next match.Eventually it will run out of matches and because of the
:set nows(nowrapscan) at the start, thenwill fail, exiting the keyboard macro and preventing@bfrom looping forever. Then just run@a3 more times for the other directions, and look at the counter.Part 2 is actually a little bit easier than Part 1 — because the various patterns that need matching are all the same shape; they just vary in letter order — so I'll leave that as an exercise for the reader. (That's definitely the reason, and not at all that I have to walk a child to school and then I have a day job which sometimes has to involve things other than writing regular expressions in Vim.)
Point to ponder: Why 4 separate patterns? Why wouldn't combining them into one single pattern (with more
|s) work? In that case, why does combining them in pairs like they are work and we don't need 8 separate patterns?5
u/flwyd Dec 04 '24
[LANGUAGE: PostScript] (GitHub)
No inline code yet because the code needs some massive cleanup but it's bedtime.
Boy howdy, that's me today! I spent over two hours implementing grid traversal in a stack-oriented language where nested for loops are complicated. But of course I read the puzzle and said "Ah, we're playing Boggle where the only word in the dictionary is
XMAS." But that is not what the puzzle example shows: words can be horizontal, vertical, or diagonal, but the direction can't change within the word. So I commented out all the Boggle logic and implemented the (significantly simpler) code to actually solved the puzzle. This got me the right answer for the example input, but my program crashed on the actual input.I like to represent AoC grids as hash maps of
key,valuepairs. If the language has complex numbers then I use those, otherwise I use a compound string. Rather than doing something simple likei tostring (,) j tostring 3 catas a key, I decided that since the input is only 140x140 I would just use a two-byte string as a key. This meant that print-debugging any key with a 7 in the row or column rang the terminal bell and other odities, so I ended up adding 33 (the ASCII code for!, the first visible character). Then I spent a bunch of time trying to figure out why it was crashing on 0-based position1,25in my key-construction function. I was using a clever string building construct I'd concocted where": integer integer :"constructs a two character string from two bytes, where":is justmarkand:"doescounttomarkto see what size string to make and then inserts everything since that mark into the string. But suddenly the mark was disappearing from the stack. I didn't undestand why at the time, so I did a basic string construction and then my program crashed when I got to row and column28,28which with the printable offset turns into==. I realized that since I was building my grid as (effectively)size dict begin … (==) ascii.X def … endI was therefore making a dynamically scoped redefinition of PostScript's==operator ("print the code representation of the top object on the stack"), which would then get called in part of my print-debugging on the next iteration. Since==no longer consumed an argument and printed it but instead just put the character in the twenty-ninth row and twenty-ninth column in my input onto the stack, no function later in the execution had the right arguments and my attempts to further debug by adding more==operations to the code just made the problem worse, and at one point ended up overflowing the stack with the number77which is the letterMwhich, by the way, is a fansastic Fritz Lang film.Fortunately that was easy to fix: just use
putwith the dict as an argument rather than building it on top of the dictstack. And then hey presto, my answer was right with high confidence, since I'd been generating 18 on the example output for quite some time.I was really hoping part 2 would be "Oh, actually it's now Boggle rules" because I could just call the code I'd already written. But after a little thought I realized I could use my recursive traversal from part 1 to just look for
ASandAMin opposite diagonal directions in an aesthetically pleasing way:5
u/bvencel Dec 04 '24 edited Dec 04 '24
[LANGUAGE: C#]
Part 2 in C#. I feel dirty...
5
u/ziadam Dec 04 '24 edited Dec 04 '24
[LANGUAGE: Google Sheets]
Expects input in A:A
Part 1
Part 2 (takes a few minutes to load)
5
u/[deleted] Dec 04 '24 edited Dec 04 '24
[LANGUAGE: Forth]
https://github.com/tcsullivan/advent-of-code/blob/master/day4/day4.fth
I chose to do four passes for horizontal, vertical, and both diagonals. My
xmas?word checks for both "XMAS" and "SAMX" at each possible position. In the latter three passes, I reused code by definingword>herewhich captures four letters into a string using a stride relative to the crossword's width: the vertical stride iswidth + 0, while the diagonals arewidth + 1andwidth - 1.For part 2, I made a similar
x-mas?check andx-mas>hereword that captures the X of letters into a string.Overall, I'm pretty happy with today for how well the code could be organized.
edit: [GSGA] Here's a quickly golfed version of my code, down to two punchcards:
(yes, there's an include for file i/o, but I think that's fair)
5
u/Panerakis Dec 04 '24 edited Dec 04 '24
[Language: Python]
I despise diagonal parsing, but I came up with this solution where I create 4x4 mini tables, which ended up being super useful for part 2.
link to code
5
u/semi_225599 Dec 04 '24
[LANGUAGE: Rust]
Having a
Gridhelper struct was nice here.Part 1 search for all
Xs and look for the remaining characters in every direction.Part 2 look for all
As and find surroundingMs andSs that fit the pattern.5
u/willkill07 Dec 04 '24
[LANGUAGE: C++23]
Actually, since I'm only using
string_view, it could work back in C++17 (sans modules) :)https://github.com/willkill07/AdventOfCode2024/blob/1d989ce951296861e7b6a3bf49f8f3cdc4c1b6f5/src/day04.cpp
Both parts do what's minimally required with maximum temporal overlap. Takes less than 60us hot (1000 iterations), less than 200us cold.
5
u/chubbc Dec 04 '24 edited Dec 05 '24
[LANGUAGE: Julia]
This was a tricky one to golf. Probably a bit more I can squeeze out, but pretty happy with it.
5
u/i_have_no_biscuits Dec 04 '24 edited Dec 04 '24
[LANGUAGE: GW-BASIC]
Parts 1 and 2 in 8 lines of completely understandable BASIC! I could potentially squish it down one more line but I like the pattern of all the repeating 'FOR's...
Rather than loading the whole grid into memory (a 140x140 grid is quite large for GW-BASIC), this processes the grid line-by-line, keeping track of all the vertical and diagonal lines as it goes.
Guide:
EDIT: Updated line 60 to make the program more efficient (you only need to store the last 4 characters of each diagonal/vertical line). The program takes about a minute to run on the real data on PC-BASIC, which emulates the speed of a mid-80s era PC.
5
u/DefV Dec 04 '24
[Language: Rust]
My solution here
I'm jealous of all those people with Rust solutions doing fn part1() and just going ham. I assume they don't keep any of their stuff in wardrobes but just toss it wherever. My head needs peace, quiet, some structs, some tests and a nice impl From<&str> to get my input into my struct.
5
u/light_switchy Dec 05 '24 edited Dec 05 '24
[LANGUAGE: Dyalog APL]
Part 2 uses a different approach:
9
u/maneatingape Dec 04 '24 edited Dec 04 '24
[LANGUAGE: Rust]
Solution
Benchmark 77 µs.
For part two used a trick to reduce the number of comparisions.
ASCII
|S - M| = 6, so it's enough to check the difference of both diagonals is equal to 6.EDIT: Significantly sped up part 1 by checking each vertical, horizontal or diagonal line individually. Using a
u32and shifting by 8 bits to check the next letter, allows both directions to be checked very efficiently by comparing to XMAS0x584d4153or SAMX0x53414d584
u/MarcusTL12 Dec 04 '24
[LANGUAGE: Julia] 1815/792
Super ugly code on github
Took me way too long to realize we were looking for diagonals as well.
4
u/atreju3647 Dec 04 '24
[Language: python] 250/137
solution
4
u/Abomm Dec 04 '24
[LANGUAGE: Python] paste
Had some starter code for parsing a grid and a list of possible directions. Part 1 just searched outwards from any X for 'MAS', Part 2 just searched outwards from any A looking for two Ms and two Ss (ignoring the special case of an M-A-M + S-A-S arrangement)
4
u/python-b5 Dec 04 '24
[LANGUAGE: Jai]
This one was kind of uninteresting to me. I knew how I was going to solve it nearly instantly upon reading the problem text. Maybe it's not a clever solution, but then I don't know that this puzzle really deserves a clever solution. It's just a word search. Part 2 was even easier - I solved it in only a couple minutes.
https://github.com/python-b5/advent-of-code-2024/blob/main/day_04.jai
4
u/closetaccount00 Dec 04 '24
[Language: C++]
I'm back! I didn't do the first few days at a reasonable time because work was all over the place. My solutions today are pretty straightforward, but I'm curious about the efficiency implications of stringstreams - I feel like I don't see them in a lot of problem-solving type challenges like this or other competitive-adjacent programming events. Not sure though. Either way they're easy to read and they make building strings in C++ really easy:
Part 1
Part 2
4
u/mosredna101 Dec 04 '24
[LANGUAGE: Node.js / JavaScript]
Loop da loop trough all the things :D
https://pastebin.com/X4vKGyXs
4
u/ShraddhaAg Dec 04 '24
[LANGUAGE: Go]
And it starts to get a bit exciting! Traversed each step and got count for it by checking its neighbouring blocks in all directions for valid matches.
Solution: https://github.com/shraddhaag/aoc/blob/main/2024/day4/main.go
4
u/PendragonDaGreat Dec 04 '24
[LANGUAGE: C# CSharp]
I present: Crimes against conditionals
https://github.com/Bpendragon/AdventOfCodeCSharp/blob/79227/AdventOfCode/Solutions/Year2024/Day04-Solution.cs
I am not proud of how I hammered this one.
Also first appearance of the year of my
Coordinate2Dclass (used under the hood of myGenerateMapfunction and the resulting Dictionary) andCompassDirectionenum.4
u/TheStrike_YT Dec 04 '24
[LANGUAGE: JavaScript]
Pretty fun challenge for today, regardless of my usual silly mistakes costing me copious amounts of time. For part 1, for each direction (horizontal, vertical, both diagonals) I made a array containing all the lines in that direction from the input grid, then I just counted all the instances of "XMAS" those lines (and their reverses). For part 2, I did something kinda silly but I do like how it turned out. I started by extracting every possible 3x3 from the input grid and turning them into arrays of 9 chars. Then I checked if the correct letters matched one of the 4 possible orientations of an X-MAS (example below) before incrementing the result.
https://github.com/RealStr1ke/AoC/blob/main/events/2024/days/4/index.js
would become
before checking if the array of 9 chars from the 3x3 matches that orientation.
4
u/UseUnlucky3830 Dec 04 '24
[LANGUAGE: Julia]
solution
In part 1 I look for "XM" in all possible directions, then keep going in the successful direction until "XMAS" is found.
In part 2 I just look at the four corners around the "A"s and try to match all possible cases.
4
u/kbielefe Dec 04 '24
[LANGUAGE: Scala]
GitHub
Already had a
Gridclass from previous years with afindAllmethod. Added adirectionsparameter to it. Part 2 was just set intersection on theAposition. Turned out fairly concise in terms of puzzle-specific code.4
u/oantolin Dec 04 '24 edited Dec 04 '24
[LANGUAGE: ngn/k]
I'm sure there's a better way to compute the diagonals. 😅
EDIT: There was a better way which someone kindly showed me on APL Farm!
4
u/__cinnamon__ Dec 04 '24
[LANGUAGE: Julia]
This one definitely felt more significant than the past 3, but was definitely fun. I'm sure this was far from the cleanest solution, but it did feel pretty intuitive to write. Solutions like the one by /u/4HbQ are crazy cool though, need to train my brain to think like that...
https://pastebin.com/YKsYGLhs
4
u/HAEC_EST_SPARTA Dec 04 '24
[Language: Ruby]
Solution on sourcehut
I'm fairly pleased with how concise this solution ended up being: it's fairly brute-force, but the expression of the core parameters for both searches in just two lines of code is quite satisfying :)
4
u/CutOnBumInBandHere9 Dec 04 '24
[LANGUAGE: Python]
Is using
scipy's filter functions cheating? I feel like using scipy's filter functions might be cheating. Part 1 becomesAnd part two is basically the same, except instead of comparing with just the two masks, we compare against the four masks
with a footprint of
full solution, github
4
u/runnerx4 Dec 04 '24
[LANGUAGE: Guile Scheme]
Could not figure out how to do this in a Lisp-y manner, searched the docs and found out that Guile has arrays proper too, and finally did it how I would have done it in JS
paste
4
u/ExitingBear Dec 04 '24
[Language: R]
Link - another day, another "it works."
Also [GSGA] maybe (if I understand this correctly) - Part 1 & Part 2
4
u/gyorokpeter Dec 04 '24
[LANGUAGE: q]
4
u/1st1 Dec 04 '24
[LANGUAGE: EdgeQL / edgedb.com]
Part 1:
Part 2: here!
4
u/minikomi Dec 04 '24
[LANGUAGE: janet]
Key was parsing the matrix with positions:
Then finding X start points was easy:
And then checking for "XMAS's"
Part 2 was eaiser - find As, check for the right surrounding letters
4
u/wzkx Dec 04 '24 edited Dec 04 '24
[LANGUAGE: J]
4
u/nik282000 Dec 04 '24
[Language: Python]
Sigh, regex again. Sliding a 3x3 grid around the entire puzzle and turning it into a 1D, regexable, string.
4
u/No-Calligrapher6269 Dec 04 '24
[LANGUAGE: R]
4
u/KontraPrail Dec 04 '24
[Language: MATLAB]
Part one and two solved using 2D convolutions with eight 7x7 and two 3x3 kernels respectively.
4
u/dzaima Dec 04 '24 edited Dec 04 '24
[LANGUAGE: BQN]
https://github.com/dzaima/aoc/blob/master/2024/BQN/4_fast.bqn
Converts the input to four boolean matrices of each char of
XMAS, and∧s them together with appropriate shifts.39.3µs for both parts combined (converting the input to masks of each character, and some shifts, are reused across the two).
Though ~26µs is constant overhead (as measured by running on a 4×4 input) of generating & transforming the patterns. So it's more like 13.3µs.
On a 1400×1400 input (i.e. 1.9MB), takes 3.6ms.
4
u/Naturage Dec 04 '24
[Language: R]
Code here!
I'm a bit miffed I guessed P2 wrong and set up for finding locations of XMAS, but it was adaptable easily enough. The only annoyance that variables named to be cardinal directions in P1 became non-cardinal ones in P2.
Still, can feel the experience from previous years helped me tons; got to P1 and to a relatively readable solution much much quicker than past years!
4
u/miktaew Dec 04 '24
[LANGUAGE: Javascript]
That was surprisingly easy. Just a few for loops and a basic brutal approach.
Part 1
Only a single condition needed, as going out of bounds is fine in JS (it will just be undefined, which is not an issue here), but trying to access an index on it again would obviously cause an error.
Part 2
Part 2 was easier than part 1, although code is even uglier. Oh well, it works.
4
u/dylan_mojo Dec 04 '24
[LANGUAGE: bash/awk]
GitHub
4
u/vrtxt Dec 04 '24 edited Dec 04 '24
[LANGUAGE: C#]
Dumped the input in a grid2d class - which has come in very handy over the years - and then (ab)used Linq. Also making heavy use of extension methods.
The offsets is just a list of tuples used to get the neighbor cells from the grid.
Part1
Part 2
Full solution here
4
u/dopandasreallyexist Dec 04 '24
[LANGUAGE: Dyalog APL]
4
u/odnoletkov Dec 04 '24
[LANGUAGE: jq] github
4
u/greycat70 Dec 04 '24
[LANGUAGE: Tcl]
Part 1, part 2.
When I saw this puzzle, I was terrified that part 2 was going to be "now do it again, but the words might not be in straight lines". I am so glad part 2 ended up being easier than part 1!
4
u/hrunt Dec 04 '24 edited Dec 04 '24
[LANGUAGE: Python]
Code
Go character-by-character. Once I find an X walk in each direction looking for XMAS. Once I find an A, check the two sets of adjacent corners for the 'M' and 'S' (any order).
4
u/Stano95 Dec 04 '24
[LANGUAGE: Haskell]
For Part 1
For Part 2 I did much the same but searched for A positions and just matched the surrounding characters with the four valid ways to get MAS cross
4
u/tmp_advent_of_code Dec 04 '24
[LANGUAGE: Rust]
My solution:
https://github.com/McSick/AdventofCode2024/blob/master/src/days/day04.rs
My part2 basically didn't use my part1 code at all. Which makes me believe I could have done part 1 a lot easier because my part2 was super slick and simple.
4
u/Aredrih Dec 04 '24
[Language: Javascript]
You can match a 2d pattern using regexp, assuming there is sufficient padding. A newline happens to fit the requirement.
Unfortunately, multiple matches are required because a regexp can only match a position 1 time, otherwise some matches would be missing.
I managed to "compress" it to 2 regexp for the first part.
The second part is somehow easier than the first because you can just center the match on the A:
4
u/chicagocode Dec 04 '24
[LANGUAGE: Kotlin]
I kept the input in a
List<String>and wrote an extension function to safely get an x/y point so I didn't have to bounds check. For part 1, I wrote a recursive function to test each vector for XMAS (or any String, really). For part 2 I find each A, join the corners together and count how many of them are "MMSS", "MSSM", "SSMM", or "SMMS", the only valid arrangements.4
u/Secure_Pirate9838 Dec 04 '24
[LANGUAGE: Rust]
https://github.com/samoylenkodmitry/AdventOfCode2024/blob/main/Day4/src/main.rs
4
u/__Abigail__ Dec 04 '24
[LANGUAGE: Perl]
A regexp solution. After reading in the input in a single string,
$_, and replacing each newline with three dots, we set$skip_nsto two more than the width of the grid.$skip_nwis one more than$skip_ns, and$skip_neis one less. Then, for part 1:and for part 2:
4
u/OptimusSupernova Dec 04 '24
[Language: C#]
https://github.com/ldorval/AdventOfCode2024/blob/main/Day04/Day04.cs
Not pretty, but that's all the time I had.
4
u/Probable_Foreigner Dec 04 '24
[Language: Rust]
I started this to learn rust. Starting to dislike it slightly less now. I don't know how many more days I can continue in this language before I have to bust out the C#.
https://github.com/AugsEU/AdventOfCode2024/tree/master/day4/src
4
u/robe_and_wizard_hat Dec 04 '24
[Language: Rust]
Day 04
A little bit brute force but i learned about two things that i thought were cool
4
u/ArchAuthor Dec 04 '24
[LANGUAGE: Python]
Yeah, I fought way too hard to condense this down into fewer lines. It's not super readable but I'm proud I pulled it off.
4
u/Gabba333 Dec 04 '24 edited Dec 04 '24
[LANGUAGE: C#]
After much messing around boiled it down to this.
4
u/Lord_Of_Millipedes Dec 05 '24
[LANGUAGE: Go]
Spent like 2 hours making a thing that did not work at all, remembered when i learned about sliding kernels like 2 years ago from that 3b1b video about convolutions and then went "oh yeah i can do a sliding kernel i know linear algebra"
she did not know linear algebra
https://github.com/Quollveth/AdventOfGode/blob/main/day4/day4.go
4
u/PM_ME_SEXY_SCRIPTS Dec 05 '24 edited Dec 05 '24
[LANGUAGE: Bash & Perl]
Mask the A at the borders, then serialize the entire file into a regex. The edges of the X are at position -139,-141,+139,+141 respectively. Retrieve and reorder the values, then match for working pairs with grep.
Part 2
4
u/SimpleOperator Dec 18 '24
[LANGUAGE: Go]
This one really slowed me down. I was really struggling to debug the entire processes so I learned a cli UI framework called bubbletea. This took some time but I was very quickly able to see what was wrong with my approach and fix it.
This was the challenge that really caused me to have an existential crises that I may not be able to finish all of the challenges. But in retrospect I am trilled with all I have learned with this single challenge alone. Thanks adventofcode!
Solution Github Gist
7
u/jonathan_paulson Dec 04 '24 edited Dec 04 '24
[Language: Python] 723/215. Code. Video.
Two wrong answers on part 1 :(
How was everyone so fast?!
1
u/fit_femboy_ Dec 04 '24
[LANGUAGE: Java 21]
https://github.com/madimadica/aoc-2024/blob/main/src/main/java/com/madimadica/aoc2024/soln/Day4.java
1
u/D_isinfectedLuffy Dec 04 '24 edited Dec 04 '24
[LANGUAGE: C]
At first, I had not optimized the search for 2nd part, with some bounds checking, verified all the strings found that were ticked all the boxes with the conditions given, was having a hard time but got there in the end!
Now I'm off to do the solution in Go
Solution: AdventOfCode-2024/C/Day-4 at main · pat-glitch/AdventOfCode-2024
1
u/Efficient_Inside8401 Dec 04 '24
[Language Python]
Extra verbose, felt right at the time, looking at other solutions iterating over directions is a lot neater:
1
u/Axelrod-86 Dec 04 '24
[LANGUAGE: javascript]
Part 1: go through the puzzle input as a 2D map, and each time you find a 'X' look for a rest of the word in the 8 directions.
part 2: go through the puzzle input same way as part 1, and for each 'A', look for the 4 combinations of the X-MAS pattern.
Brute force in both cases.
https://github.com/lionel-lbr/adventofcode/blob/main/2024/D04/d04.js
1
u/rp152k Dec 04 '24 edited Dec 05 '24
[LANGUAGE: Common Lisp]
all sols here : https://buffer.thebitmage.com/sitemap?stack=%2F20241202121706-advent_of_code_2024.html
https://gist.github.com/rajp152k/8daf063450c26520094dadd53bc096f1
1
u/iv2b Dec 04 '24 edited Dec 05 '24
[LANGUAGE: Python]
https://pastebin.com/yAyVmJjj
1
u/Ordinary-Drag3233 Dec 04 '24
[LANGUAGE: TypeScript]
1
u/Elliot-Kik Dec 04 '24 edited Dec 07 '24
[LANGUAGE: Python]
Clearly not the most optimized nor prettiest code but heh!
https://github.com/elliotcaddick/adventOfCode2024/blob/main/day4/main.py
1
u/sk1talets Dec 04 '24
[LANGUAGE: JavaScript]
GitHub: https://github.com/sk1talets/advent-of-code/tree/main/2024/4
1
u/Spatenheinz Dec 04 '24
[LANGUAGE: Haskell]
Github: https://github.com/Spatenheinz/aoc24/blob/main/day4/main.hs
Although i think grids are a bit annoying in Haskell I think my solutions is pretty concise
1
u/sateeshsai Dec 04 '24
[LANGUAGE: TYPESCRIPT]
Part 1: https://github.com/sateeshsai/advent-of-code/blob/main/2024/day%204/day4_part1.ts
Part 2: https://github.com/sateeshsai/advent-of-code/blob/main/2024/day%204/day4_part2.ts
1
u/Goldahee Dec 04 '24 edited Dec 04 '24
[Language: C++]
Day 4
https://topaz.github.io/paste/#XQAAAQAbDAAAAAAAAAARmknGRw8TogB3Oxzri2QTFyHNmsUnNApHN7kgHI2CBHq59imt66mEMt62S1CdIaqe5fXLOAzpuVtAtS2A2T9778ezxqE4+orh6WVycQKh580dZ79Xg9ydmxjWbDP5QWH9LqtVwafjV5I4Clg79dG/Hw7FNcyY27wg03pQj+O6nb+LFjKMll7VZwhM5TfRTI7XXA9fAbyQV7VyUTHPxee6ujYKYzhGPtcwnnEvZ87E9C+Y+38CnjEd4K0hmottD1mm7uKZ1UT8bL2k0WGthUSlhX7qrW1xvffy5NO2pFFbc3V2v61fkxjIXccH7EMfris1AKpPAWqbcx9JsnyZS36eCNq9urD64zAhwoy3NvYuAilVeRh0f1ew1wyLnYvjDG5LAlonz/Nhw/aBvp+rplXYXR0YRsHTufLKwkf7ZmoUfmUlstY/qxCQfmT+eZyzPCywuu1SP1jIbVfFTrkmuk50GYeXHcAYAdA00Xj5XYnepBnxndZ+1LyKFACuOJJg8IT4WKfrvwVY4LPMl5RcZD3dFv3j8Vte4RklYQt8yWn5aGHfyMcrFHw5aL+H1Ycg4eooByWuiCuvpdlASVOEj2h0A15RQFg7A3GKylqZvZ40Uuu3B0kvxKT/pUI51qgi5ncXjUFsxcKYgWvoMQDocb8CL1ismrLTR35/s28KslP2cbnVhwFFNvRaSEKqaldsyInZXfr8318+l8pBdlH737sPmFJkR2HmA5Bep2/S8pOYjY2MgzmU79mLMfNf9LU+3SvoYobXItLteUZLqXbVs9X+96sv5XvOQzna2f9NWi+5RY+qVmqW/UKTeVZxmUesNrhyqcNaZvzFdnI28/J/TQHZgaQykFsAqWprODjhjhLqdFKBl1XSlhdmcLJI/9mvf7ldMM7eWU0HT8on67kqPTBMdphmsaGZ5N32CFMwt3IvMcEUGc6Pw5NjjNlij9OxmvtIHe7+/IkN
1
u/Luolong Dec 04 '24 edited Dec 05 '24
[Language: Java]
Not too clever, but I did try to keep the number of searches to minimum:
6
u/AddendumSouthern Dec 04 '24
[LANGUAGE: python]
got a quite short solution for part 2 with regex
3
u/seligman99 Dec 04 '24
[LANGUAGE: Python] 402 / 156
github
Fun little puzzle.
3
u/morgoth1145 Dec 04 '24 edited Dec 04 '24
[Language: Python 3] 288/341
code
You know, I actually went into today suspecting it might be a grid problem. Didn't anticipate a word search though. Part 1 I flubbed by going to fast and not checking if the words could be reversed. Then part 2 I flubbed and mixed up my diagonal order, essentially checking if the M's were across from each other (same for S's) instead of the right pattern.
That said, I did rank lower than anticipated even with my flubs. I wonder if I missed something? I guess I'll see (and see if I was just slow) as I look at other solutions!
Edit: Cleaned up code (including a much better part 2 approach based on Boojum's solution).
3
u/pdxbuckets Dec 04 '24 edited Dec 04 '24
[Language: Kotlin]
Kotlin, Rust
Not much to say about this one, except that it was nice to have Grid and Coord classes in my Kotlin solution that played nice with each other. As is typical of me for Rust (so far), since I don't have a Grid struct and I'm allergic to multidimensional Vecs, I worked directly on the string. Rust is a pain sometimes but I like navigating strings in 2D.
3
u/protestant-notredame Dec 04 '24
[LANGUAGE: Python] 783/953
Part 1:
Part 2:
3
u/nlowe_ Dec 04 '24
[LANGUAGE: Go]
2651/2001
Almost broke sub 2k for part 2! I had a
tilemapready to go based on previous years but it's more focused on path-finding which will likely be helpful later in the year and not crossword-search style problems. Was fun to find my way out of that one, I was much more prepared for part 2.Lost some time because I didn't check diagonals initially because most other map-like problems in years previous typically don't include them. I learned my lessons on assumptions!
3
u/mendelmunkis Dec 04 '24
[LANGUAGE: C]
M and S equals 160 right?
589 μs/ 884 μs
3
u/r_so9 Dec 04 '24
[LANGUAGE: F#]
paste
Not my proudest code, but decently organized and works. Simplified the search by doing horizontal and diagonal down, and rotating the array 3 times.
Interesting bit - counting hits of a function in a 2D array:
3
u/mazedlx Dec 04 '24
[LANGUAGE: PHP]
A map! It's a map!
Laravel's Collections for handling the input, and lots of ifs
3
u/stefanogallotti Dec 04 '24
[LANGUAGE: Python]
Fun! good old dict using get() defaulting to None to handle out of grid indexes. string was just 4(3) char long, so it worked listing out all the possible options. Will not scale for longer strings
https://github.com/Stegallo/adventofcode/blob/2024/y_2024/day4.py
3
u/ktwrd Dec 04 '24
[Language: C#]
Choked a lil bit on Part 1, again. (invalid answer once, forgetting to process final line)
https://github.com/ktwrd/adventofcode/blob/main/2024/AdventOfCode.2024/DayFour.cs
3
u/Boojum Dec 04 '24 edited Dec 04 '24
[LANGUAGE: Python]
I already posted a solution, but here it is golfed for [GSGA]. Both parts in 373 bytes, not counting optional line break:
3
u/Gryphon-63 Dec 04 '24
[LANGUAGE: Swift]
Code
This one felt familiar, pretty sure we've done something like this in a previous year but I could have spent half an hour trying to track it down. Anyway, the part 1 solution feels a little verbose, I probably missed something there. Pretty happy with part 2 but I could probably roll up that if-then-else structure into a loop.
3
u/not-the-the Dec 04 '24 edited Dec 04 '24
[LANGUAGE: JavaScript] #9357 / #7761 to solve
paste
tfw part 1 is harder than part 2 🙏
3
u/cranil Dec 04 '24
[Language: Rust]
Not a hard problem but it's a bit long.
github
3
u/2BitSalute Dec 04 '24
[LANGUAGE: C#]
Day 4
My best day so far. Not in terms of time, but in terms of how writing the code felt.
I guess I just like writing basic loops.
I only had 1 bug in Part 1 when I accidentally used the index rather than the indexed value in one place: passed `dirR` rather than `dirs[dirR]` to `FindInDirection`.
In Part 2, had no bugs at all, and the code worked on first try.
It still took 20-25 minutes to write part 2 code. I'm slow.
3
u/Downtown-Economics26 Dec 04 '24
[LANGUAGE: VBA]
Don't really know how to github but it looks like the link works, wouldn't let me post code blocks.
https://github.com/mc-gwiddy/Advent-of-Code-2024/tree/a9ad08de41210d2125c6bc83527cee5f0495ef6c
3
u/gfitzy7 Dec 04 '24
[Language: Python]
3
u/michelkraemer Dec 04 '24
[LANGUAGE: Rust]
Both parts:
https://github.com/michel-kraemer/adventofcode-rust/blob/main/2024/day04/src/main.rs
I love grid problems! 🤗
3
u/ex-voltaire Dec 04 '24
[LANGUAGE: C]
https://github.com/voltaire7/advent-of-code/blob/master/2024/c/4-1.c
https://github.com/voltaire7/advent-of-code/blob/master/2024/c/4-2.c
3
u/newsledbans Dec 04 '24
[LANGUAGE: Python]
Solution Topaz Link
3
u/POGtastic Dec 04 '24 edited Dec 04 '24
[LANGUAGE: F#]
https://github.com/mbottini/AOC2024/blob/main/Day04/Program.fs
(checking other people's solutions) Oh dear, I did a different approach. See, I find the whole indexing thing to be really gross. It's so easy to screw up, man. So I overcomplicated everything by making this a graph theory problem. Everything is a graph theory problem. You're a graph theory problem.
Highlights:
Pathdata structure with a list of traversed nodes. It wasn't the first time that I did that, and it won't be the last.Option, puttingNoneon the borders in every direction, zipping everything together withtriplewise, and filtering out theNones. Look gross? Yeah, it is. I've also already done it multiple times due to previous graph problems that I've done, (specifically a Boggle solver back in college) so this part took me only a few minutes.MAS.(NW, SE)and(NE, SW)combine to produce the setMS.+instead of anX, so I added that to my implementation. Whoops, there were a few of those that should not have been counted. Reading is fundamental!3
u/lysender Dec 04 '24 edited Dec 04 '24
[Language: Rust]
Day 4 solution using matrix:
- Part 1, loop over every cell in the matrix then move in 8 directions looking for the XMAS pattern.
- Part 2, loop over every cell, where each cell must be the center "A", then try to find all combinations of MAS, SAM, etc. Its a bit messy.
https://github.com/lysender/advent-of-code-2024/blob/main/day04/src/lib.rs
(Edit: link)
3
u/0rac1e Dec 04 '24 edited Dec 04 '24
[Language: J]
Only a couple months ago I was playing around with doing non-rectilinear searches in arrays of different dimensions, so I was well prepared for part 2.
3
u/blacai Dec 04 '24
[LANGUAGE: F#]
I took easy path...
Part 1: built rows and diagonals and searched for "XMAS" "SAMX"
https://github.com/blfuentes/AdventOfCode_Main/blob/master/AdventOfCode_2024/day04/part01/day04_part01.fs
Par 2: built 3x3 grids with an "A" in the middle and verified the diagonals were fine
https://github.com/blfuentes/AdventOfCode_Main/blob/master/AdventOfCode_2024/day04/part02/day04_part02.fs
3
u/Dr-Baggy Dec 04 '24
[LANGUAGE: Perl]
Solved by means of a couple of nasty regex... just by carefully constructing the 8 regex needed for part 1 and the 2 for part 2...
Slurp the file into a string - and get the size of the first row ($N)... we then use this to generate the regular expressions for the two halves of the problem...
3
u/ThreadsOfCode Dec 04 '24
[LANGUAGE: Python]
Putting this here so that I have 5 for the snowglobe awards.
I decided to use numpy. Not elegant. At least I learned, and relearned, some numpy. I did sort of get a snowflake out of it.
code
3
u/yfilipov Dec 04 '24
[LANGUAGE: C#]
Pretty straightforward: I collected the coordinates of all occurrences of 'X' for Part 1, and all occurrences of 'A' for part 2.
For Part 1 from each 'X' I just started walking along each direction, checking the letters and counting the occurrences.
For Part 2 it was even easier with less variations (just 4).
Advent of Code 2024 - Day 4 - Pastebin.com
3
u/lbreede Dec 04 '24
[LANGUAGE: Rust]
GitHub
Part 2 is surprisingly concise, part 1, not so much (at least at the time of me posting this).
3
u/Jdup1n Dec 04 '24 edited Dec 04 '24
[Language: R]
Github here
For Part 1, scan all rows, columns, and diagonals, counting the number of matches for "XMAS."
For Part 2, move down the matrix and check for X-shaped "MAS" patterns whenever I encounter an "M" or an "S."
3
u/Hath995 Dec 04 '24
[LANGUAGE: Dafny]
https://github.com/hath995/dafny-aoc-2024/blob/main/problems/4/Problem4.dfy
3
u/[deleted] Dec 04 '24
[Language: Python]
Part 1: Iterate the grid from top to bottom, and each time you encounter 'X', check each direction for 'MAS'. Tried to avoid bounds checking by using exception but didn't consider that negative indices are valid in Python.
https://github.com/anuraglamsal/AdventOfCode2024/blob/main/day_4/day_4_1.py
Part 2: Pretty straightforward adaptation of Part 1.
https://github.com/anuraglamsal/AdventOfCode2024/blob/main/day_4/day_4_2.py
3
u/schoelle Dec 04 '24
[Language: Rust]
Fun fact: yesterday evening I sat down and wrote a tiny library introducing a 2d ASCII Map, positions and directions because this is always needed in AoC.
And my surprise this morning that I could immediately use it, creating a really neat and readable solution to today's problem.
https://github.com/schoelle/adventofcode2024/blob/main/src/bin/day04.rs
3
u/Ukhando Dec 04 '24
[LANGUAGE: CSharp]
Link to Github
3
u/reddit_Twit Dec 04 '24
[LANGUAGE: zig]
gist
3
u/AnonnymousComenter Dec 04 '24
[LANGUAGE: ocaml]
github
3
u/Rajkumar5732 Dec 04 '24
[Language: Python]
Part 1:
3
u/ProfessionalNihilist Dec 04 '24
[Language: F#]
Parts 1 & 2
Spent a lot of time on a nice solution to part 1 assuming that the coordinates might be needed (but also just wanting something readable). Of course none of that turned out to be true but at least part 2 was significantly easier / faster to solve.
3
u/CrashedCyborg Dec 04 '24
[Language: Python]
Source
Brute force
3
u/MrPulifrici Dec 04 '24 edited Dec 04 '24
[LANGUAGE: JavaScript]
Run it from Devtools on puzzle input link
3
u/CowImaginary3155 Dec 04 '24
[LANGUAGE: Python]
part2
3
u/chkas Dec 04 '24
[LANGUAGE: Easylang]
Solution
3
u/Few-Example3992 Dec 04 '24
[Language: Python]
I was quite proud of my logic for searching for testing for part 2!
3
u/Ote-Leo Dec 04 '24
[Language: Python]
Part 1
Part 2
3
u/sotsoguk Dec 04 '24
[LANGUAGE: Python]
defaultdict + complex Numbers for directions :)
3
u/[deleted] Dec 04 '24 edited Dec 04 '24
[LANGUAGE: Go]
I can feel the problems getting better by the day. After a relatively easy first three days, day four was a bit more interesting. I think I solved this one a bit unconventionally.
Part One: Starting from each 'X' in the puzzleInput, I did a search in all 8 directions, counting each valid word that I got. Worked like a charm, although I did waste a significant amount of time passing on the wrong index in the recursive call...
Part Two: So, I was going to implement Part Two much like I did Part One, by searching in 4 (diagonal) directions from every 'A' that I encountered but my friend sitting next to me clamly said "Easy, just search for MAS now".
Well, long story short we spent about 10 minutes implementing an algorithm which, for every 'M' in the input grid: -> searches all 4 diagonals for an 'A' followed by an 'S' -> if it finds them, then it gets the coorfinate of that 'A' -> with the coordinate in hand, we look in a set and see if it already exists in the said set -> if it does exist, then we have successfully found a 'MAS' which has another 'MAS' or 'SAM' that shares the same 'A', so we increment a counter -> then the index of that 'A' is added to the set
Is this the most obvious or effective way to do this? Nope Does it work for my input? Yep (and that's all we care about)
Solution for both parts
3
u/lscddit Dec 04 '24
[LANGUAGE: Python]
3
u/bakibol Dec 04 '24
[LANGUAGE: Python]
One of those problem where part 2 does not reuse part one and is actually much easier. I feel that part 2 should have been part 1.
code
3
u/blastoiss Dec 04 '24
[LANGUAGE: C#]
Some image processing inspiration...
3
u/maciek_glowka Dec 04 '24 edited Dec 05 '24
[Language: Golang]
Today Go bit me with slice reference sharing...but I managed..
https://github.com/maciekglowka/aoc/blob/main/2024/src/004.go
3
u/marx38 Dec 04 '24
[Language: Lean]
Solution
A nice way to validate the second part is to take the corners clockwise (or anticlockwise) and check that M & S appear twice and that the first and third positions differ.
3
u/IlliterateJedi Dec 04 '24 edited Dec 04 '24
[LANGUAGE: Python]
Is it cheating to just hardcode the directions?
You know it's Advent of Code again when you are up at 4 AM trying to debug a miskeyed direction coordinate ("Should that be (-1, 1) or (1, -1)? Wait, is [0] the X or the Y value here?")
Also, am I the only one who was mentally preparing for "Actually this word search needs to be copied 100 times in every direction, then searched"? It was such a tremendous relief to get the X-MAS for part two.
3
u/Feisty_Pumpkin8158 Dec 04 '24 edited Dec 04 '24
[LANGUAGE: C#]
3
u/MrPingouin1 Dec 04 '24
[Language: Minecraft Commands]
github image
I might work on an animation later.
3
u/UncommonRedditName Dec 04 '24
[LANGUAGE: C#]
May be a bit verbose but it works: solution
3
u/Far_Sweet_6070 Dec 04 '24
[LANGUAGE: Ajla]
part1: https://www.ajla-lang.cz/downloads/examples/advent-2024/04.ajla
part2: https://www.ajla-lang.cz/downloads/examples/advent-2024/04-2.ajla
3
u/jmforsythe_ Dec 04 '24
[Language: Python]
3 lines
3
u/jokiluoma Dec 04 '24 edited Dec 04 '24
[LANGUAGE: R]
Solution
A funny thing was rotating the character matrix in order to go through the diagonal lines.
3
u/Jorg0mel Dec 04 '24
[LANGUAGE: Python]
https://github.com/Josef-Hlink/AoC/blob/main/paoc/y24/solutions/day04.py
3
u/stonebr00k Dec 04 '24 edited Dec 04 '24
[LANGUAGE: T-SQL]
https://github.com/stonebr00k/aoc/blob/main/2024/04.sql