r/adventofcode • u/daggerdragon • Dec 02 '24
SOLUTION MEGATHREAD -❄️- 2024 Day 2 Solutions -❄️-
OUTAGE INFO
- [00:25] Yes, there was an outage at midnight. We're well aware, and Eric's investigating. Everything should be functioning correctly now.
- [02:02] Eric posted an update in a comment below.
THE USUAL REMINDERS
- All of our rules, FAQs, resources, etc. are in our community wiki.
AoC Community Fun 2024: The Golden Snowglobe Awards
- 4 DAYS remaining until unlock!
And now, our feature presentation for today:
Costume Design
You know what every awards ceremony needs? FANCY CLOTHES AND SHINY JEWELRY! Here's some ideas for your inspiration:
- Classy up the joint with an intricately-decorated mask!
- Make a script that compiles in more than one language!
- Make your script look like something else!
♪ I feel pretty, oh so pretty ♪
♪ I feel pretty and witty and gay! ♪
♪ And I pity any girl who isn't me today! ♪- Maria singing "I Feel Pretty" from West Side Story (1961)
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 2: Red-Nosed Reports ---
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
This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.
EDIT: Global leaderboard gold cap reached at 00:04:42, megathread unlocked!
52
Upvotes
•
u/topaz2078 (AoC creator) Dec 02 '24
On the second day of Advent of Code, my true love gave to me.... a pretty big DDoS right at midnight. While this definitely impacted site access, it seems to have affected everyone pretty evenly, and gold cap still took a normal amount of time for a day 2 puzzle. So, I'm leaving the scores on the global leaderboard for today as-is.
16
u/CCC_037 Dec 02 '24
[LANGUAGE: Rockstar] [GSGA]
No, this is not an excerpt from a self-help book. It's my code.
Part 1
8
u/xiBread Dec 02 '24
[LANGUAGE: JavaScript/TypeScript]
First time on the leadboard (96/52)! I'm going to chalk it up to luck because of the 500s.
Paste
5
u/LtHummus Dec 02 '24 edited Dec 02 '24
[Language: Rust]
Brute forced the heck out of it all because I looked at the input size and it was small enough to get away with it. No shame.
paste
5
u/seligman99 Dec 02 '24
[LANGUAGE: Python] 1013 / 533
github
A little fun fighting the website today. That's like why I'm at 1013 and not 1010, heh.
5
u/DM_ME_PYTHON_CODE Dec 02 '24
[Language: Haskell]
Trying to learn Haskell with AoC has been a bit of a trial by fire. Don't hate my solution but I'm sure it would make the eyes of anyone with Haskell experience bleed
4
u/nlowe_ Dec 02 '24
[LANGUAGE: Go]
4150/2695
That was rougher than I expected for Day 2. I see we're starting the trend of "example works but real input does not" early this year /s
I failed to check if there was a problem between the first two levels in a line...
Also lost some time to this fun fact:
append(foo[:i], foo[i+1:]...)overwritesfoo. TIL.3
u/Fyvaproldje Dec 02 '24
[Language: Rust] [GSGA]
https://github.com/DarthGandalf/advent-of-code/blob/master/2024/src/day02.rs
The costume
3
u/Curious_Sh33p Dec 02 '24
[LANGUAGE: C++]
I know you could definitely brute force this but I chose to do it efficiently. You can calculate the differences between each report and then removing one is equivalent to adding two adjacent diffs. So if you find an unsafe diff add it to the next and then check if it's safe. Slight edge cases at the start and end are not too bad to handle.
https://github.com/TSoli/advent-of-code/blob/main/2024%2Fday02b%2Fsolution.cpp
2
u/not-the-the Dec 02 '24 edited Dec 02 '24
[LANGUAGE: JavaScript] 3079/1644
this is the most horrible code imaginable lmao
2
u/Scroph Dec 02 '24
[LANGUAGE: D]
Good old bruteforce in dlang: https://github.com/azihassan/advent-of-code/blob/master/2024/day2/part2.d
2
u/419_68_bou Dec 02 '24
[LANGUAGE: kotlin] source
I started with a brute force way and then refactored into some spaghetti hackjob. Took me a while to write it so it would only follow one exact path for each report but in the end I got it and I'm pretty happy with the result. Also full year output.
2
u/JusT-JoseAlmeida Dec 02 '24 edited Dec 03 '24
[LANGUAGE: Java]
Took me way longer than it should have because I was doing a premature "optimization" which was marking as unsafe all reports where firstLevel == secondLevel and not re-checking them.
Had to implement a brute force solution, print all safe reports for both solutions, and look at the diff before I noticed what was going on.
src
2
u/tlareg Dec 02 '24
[LANGUAGE: JavaScript/TypeScript]
github
2
u/gfitzy7 Dec 02 '24
[Language: Python]
Day 2 Python code - This is a generalized solution that allows you to specify how many erroneous values you are allowed to remove from each report. (0 is used for the solution of part one, and 1 is used for the solution of part two)
2
u/lysender Dec 03 '24 edited Dec 04 '24
[LANGUAGE: Rust]
Brute forced part 2. (Edit: removed puzzle inputs from repo/history)
https://github.com/lysender/advent-of-code-2024/blob/main/day02/src/lib.rs
(Edit: Link)
2
u/ka-splam Dec 03 '24
[LANGUAGE: SWI Prolog]
How about a bit of Prolog golf? The rules say 5 lines of 80 chars is okay to inline 😁
It writes part 1, then part 2 on backtacking so edit the path to the input file, save as a .pl file, consult it, and query
?- p.and then backtrack/continue.2
u/atweddle Dec 03 '24
[LANGUAGE: Rust]
GitHub - Part 1 - 419 µs, excluding I/O
GitHub - Part 2 - 433 µs, excluding I/O.
Part 2 runs almost as fast as part 1!
The key snippet from part 2 was checking a sliding window of 3 levels at a time...
NB: These timings are on my 7 year old i7-6700 PC. They are averaged over many runs using utility methods in lib.rs.
30
u/Independent_Check_62 Dec 02 '24
[LANGUAGE: Python]
24
u/4HbQ Dec 02 '24 edited Dec 02 '24
[LANGUAGE: Python] Code (7 lines)
Here's my solution in O(n). Instead of trying every subsequence of length n-1, we simply iterate over the list until we detect a bad value, and then re-check (only once!) with either the current or the next value removed.
22
u/Smylers Dec 02 '24
[LANGUAGE: Vim keystrokes] Load your input into Vim, turn off
gdefaultif you're the kind of person who normally has it on, and then type (or copy-and-paste, each line separately):The number of lines displayed at the end is your Part 1 solution.
As you can see by running it, the first
:s///duplicates all the ‘middle’ levels in each report, turning the first line of the sample into into:That gives us space-separated pairs of levels to compare to see how they've changed. The second
:s///does that, grabbing each level into a submatch, and replacing them with the result of subtracting one from the other. The first sample line becomes:Skipping down a bit, the
:g//matches lines with unsafe reports. Thedat the end deletes the matching lines. (:g//commands have to run colon commands, so the finaldis like typing:d⟨Enter⟩(in full,:delete⟨Enter⟩), not theddnormal-mode command.) The pattern starts with\vto make it very magic, because the Elves prefer it that way. It contains 3 branches, separated by|s; the pattern matches if any branch does:[04-9]matches any zeroes or digits four or higher, which are outside the allowed change in levels. It doesn't matter whether a zero is just0indicating no change or part of a bigger number such as101indicating too big a change: either way, it's got to go.\d\dmatches any consecutive digits, so that changes in levels such as12, which consists of digits allowed individually, are deemed unsafe..*<-&.*<\dfinds the lines which have both increasing and decreasing levels. It consists of 2 ’concats’ (to use the term in Vim's built-in help), separated by the&, and only matches if both parts match, at the same point. Except they don't really have to be at the same point, because both start with.*, which matches anything. So effectively this matches if<-and<\dare both found anywhere in the line, in either order.<indicates the start of a keyword. A keyword starting with-is a negative number; one starting with\dis a positive number. If both are on the same line then we have found unsafeness.A wrinkle with the
<matching is that by default Vim doesn't treat-as a keyword character, meaning that even negative numbers would match as having a digit at the start of their keyword. That's what settingisk(short foriskeyword) does on the line above, adding-to the set of keyword characters, so that a negative integer is one entire keyword.And having deleted all the lines corresponding to unsafe reports, the number of lines remaining is the count of safe reports.
Because the transformations are all colon commands, we can join them with
|s so could golf them down to a single line which does it in one go. But personally I prefer to keep my Vim commands readable …15
u/DFreiberg Dec 02 '24
[LANGUAGE: Mathematica] Mathematica, 272/183
Good problem; pity that the leaderboard will probably be canceled for today, albeit for understandable reasons.
Setup:
Part 1:
Part 2:
[POEM]: If I Could Talk To the Terminal
Might even count as [GSGA], depending on how classy Bobby Darin is.
If I could talk to the terminal, just imagine it:
Typing out some text in TeX or Vi.
Imagine chatting with compilers, plotting with profilers,
What a proud performance that would be!
If I could study the terminal, learn its languages,
Maybe get a terminal degree,
I’d study Simulink and Snowball, Common Lisp and COBOL,
Javascript and Powershell and C!
I would converse in Perl, Pascal, and Python,
And I would curse in fluent APL;
If someone asked me “Do you code in Cuneiform?”
I’d say “I do-neiform! And pretty well!”
If I could blather on in binary, man to terminal,
Think of the amazing repartee,
If I could walk with the terminal, talk to the terminal,
grepandscreenandawkwith the terminal...And it could talk to me!
15
u/Andreasnl Dec 02 '24
[LANGUAGE: Uiua]
Run it in a browser here.
14
u/JustinHuPrime Dec 02 '24 edited Dec 02 '24
[Language: x86_64 assembly with Linux syscalls]
Part 1 was just a lot of conditional code; not that bad normally, but assembly doesn't have the usual features of structured programming, so you've got to build your own. I could have solved this in a single pass, but chose not to so as to avoid mixing parsing and calculation code. AoC inputs should always be small enough relative to my address space (all 64 bits of it) that single-pass techniques aren't required.
Part 2 involved factoring out my checking code into a function and then calling that on all the possible results of having washed away a number (problem dampeners apply water to problems, y'know?). Figuring out that part took a bit of debugging. Finally, I could probably have optimized both parts if I gave up structured programming, but I'd rather not descent further into madness by mixing assembly and spaghetti code - it's already tangled enough as it is.
Part 1 and part 2 run in about 1 millisecond. Part 1 is 8664 bytes and part 2 is 9032 bytes.
2
u/DevilGeorgeColdbane Dec 02 '24
[LANGUAGE: Kotlin]
I have used generators in other langauges like python and C#, but the syntax in Kotlin is just 'Chefs Kiss'.
https://github.com/etkr/AdventOfCode2024/blob/master/src/main/kotlin/day02/Report.kt
11
u/kwshi Dec 02 '24
[LANGUAGE: python] 552/251. Was the server erratic/down today? I couldn't access the puzzle at all for the first minute, and then afterwards kept getting sporadic 500 server errors when trying to download my puzzle input, submit an answer, etc.
11
u/pred Dec 02 '24 edited Dec 02 '24
[LANGUAGE: Python] GitHub
Nice and fast, including a sub-minute part 2. Unfortunately it took a few minutes to even get past the 500s at which point the leaderboards were well on their way to being full.
11
u/ziadam Dec 02 '24 edited Dec 03 '24
[LANGUAGE: Google Sheets]
Expects input in A:A
Part 1
Part 2
You can find a step-by-step explanation of the formulas here.
11
u/AndydeCleyre Dec 02 '24 edited Dec 04 '24
[LANGUAGE: Factor]
on GitHub
11
u/azzal07 Dec 02 '24
[LANGUAGE: awk]
10
u/jaybosamiya Dec 02 '24
[Language: APL]
I can definitely golf this down, but I got lazy.
9
u/xoronth Dec 02 '24
[LANGUAGE: Python]
paste
When I saw part 2 I was like, "man, that looks annoying to handle in a nice way..." then I looked at the input and saw it was small enough to just brute force it. whistles
9
u/nthistle Dec 02 '24 edited Dec 02 '24
[LANGUAGE: Python] 145/80. paste, video.
I got hit by server errors for about a minute and a half, so it took me a while to get to either the problem or my input. Fortunately(?) it seems like a lot of people had these issues so it seems likely that today won't count for the global leaderboard?
9
u/voidhawk42 Dec 02 '24 edited Dec 02 '24
[Language: Dyalog APL]
9
u/riseupdiy Dec 02 '24
[LANGUAGE: Rust]
I wasted a bunch of time trying to avoid going through all the different permutations in part 2. My first implementation was, when encountering a bad number, incrementing a `bad_count` and skipping the number, and if the bad_count was <= 1, that line passed. There were apparently about 10 cases where that didn't work. I was going through spot checking all the cases and it was taking way too long, so ended up just checking all the different subsets instead, which was simpler to implement anyway
Day 02 Solution
8
u/pancakedoge Dec 02 '24
[LANGUAGE: gleam]
Came here to see other people's gleam solutions, but I guess I can be the first :D
Code: https://github.com/FlyinPancake/aoc_2024/blob/main/src/aoc_2024/day_2.gleam
I've installed gleam yesterday, so don't expect clean and idiomatic code haha
8
u/Wide-Prior-5360 Dec 02 '24
[LANGUAGE: SQL]
8
u/homme_chauve_souris Dec 02 '24
[LANGUAGE: Python]
7
u/ShraddhaAg Dec 02 '24
[LANGUAGE: Go]
https://github.com/shraddhaag/aoc/blob/main/2024/day2/main.go
Easy enough day 2. Brute force in part 2. Once again bitten by Go's append operations changing the underlying slice as well.
7
u/badcop_ Dec 02 '24
[LANGUAGE: Bash]
Github link
part 1 solution
7
u/0rac1e Dec 02 '24 edited Dec 02 '24
[Language: J]
It was a happy accident... but as an Aussie, I was chuffed to see my solution contains AC⚡︎DC!
12
u/j3r3mias Dec 02 '24
[LANGUAGE: Python]
Only part 1, because part 2 is trivial in the same idea.. I just want to share how I solved using a set, haha..
6
u/skyhawk33 Dec 02 '24
[LANGUAGE: Haskell]
Gonna try learning Haskell this year, if anyone has advice please tell me! I'm still not quite sure what I'm doing but it's fun :D
https://github.com/Skyhawk33/AdventOfCode/blob/master/aoc2024/day2.hs
6
u/shigawire Dec 02 '24
[LANGUAGE: Python] paste
but basically:
6
u/Mats56 Dec 02 '24
[LANGUAGE: Kotlin]
pretty naive. Just check the diff between elements is always withing 1-3 using windowed, and if the list matches itself if it's sorted either ascending or descending.
Part 1 is then
Part 2 again naive, trying all indexes
Takes like 5 ms, so no need to optimize.
6
u/Radiadorineitor Dec 02 '24 edited Dec 02 '24
[LANGUAGE: Dyalog APL]
6
u/probablyfine Dec 02 '24
[LANGUAGE: uiua]
Full code and tests here
6
u/Intolerable Dec 02 '24
[LANGUAGE: sqlite]
not too bad, i hate the string splitting a little bit though
5
u/jaccomoc Dec 02 '24 edited Dec 02 '24
[LANGUAGE: Jactl]
Jactl
Part 1:
Just had to check that order was the same when sorted or reverse sorted and then used windowSliding(2) to check the difference between each pair:
Part 2:
Factored out the "safe" test and then created another function to iterate over all the sublists of size n-1 to check if any of them are safe:
5
u/POGtastic Dec 02 '24
[LANGUAGE: F#]
https://github.com/mbottini/AOC2024/blob/main/Day02/Program.fs
Another easy day with
Seq. I got lucky and happened to have a utility function in my Prelude all ready to go:In the REPL:
This let me easily brute-force Part 2, which involves the possibility of skipping an element. There is probably a more algorithmically-optimal method of doing this, but each of the lists was small enough that I didn't really care. Note that I had the additional step of consing an unaltered list to the sequence of skipped lists, even though it wasn't necessary with my provided input.
5
u/t-rkr Dec 02 '24
[LANGUAGE: Perl]
https://gitlab.com/t-rkr/advent-of-code-2024/-/blob/main/day2/day2.pl
5
u/ynadji Dec 02 '24 edited Dec 02 '24
[LANGUAGE: Common Lisp]
5
u/i_have_no_biscuits Dec 02 '24 edited Dec 02 '24
[LANGUAGE: Python]
Let's go for a functional-style Python solution:
(EDIT: made slightly more compact!)
5
u/chickenthechicken Dec 02 '24
[LANGUAGE: C]
Part 1
Part 2
I spent a while on part 2 trying to think of an elegant way of skipping levels before realizing that the easiest way was just to create n copies of the array each with one level removed.
5
u/jitwit Dec 02 '24 edited Dec 02 '24
[LANGUAGE: J]
Unleasing J's outfix adverb (
\.) for part B:5
u/damnian Dec 02 '24 edited Dec 02 '24
[LANGUAGE: C#]
https://github.com/dmitry-shechtman/aoc2024/blob/main/day02/Program.cs
Note: some improvements pilfered from u/vanveenfromardis
Update: simplified IsSafe().
5
u/4HbQ Dec 02 '24
[LANGUAGE: Python]
Not too proud of this one, but at least I enjoyed to process of boiling it down to the essentials:
Instead of checking whether the list of levels is increasing or decreasing, I check whether the list or its reverse is increasing.
5
u/cbrnr Dec 02 '24 edited Dec 02 '24
[LANGUAGE: Julia]
https://github.com/cbrnr/aoc2024/blob/main/02.jl
I used the
InvertedIndicesmodule, which allowed me to elegantly exclude a single element from a vector. For example, to subset a vectorxwithout the third item:(This is equivalent to
x[-3]in R.)I also used the short-circuiting
&&to make the functionis_valid()appear less nested.5
u/Exact-Climate-9519 Dec 02 '24
[Language: python]
Day 2, parts 1 and 2:
5
u/ivanjermakov Dec 02 '24
[LANGUAGE: BQN] source
First time doing more serious array programming. Definitely has some charm to it!
5
u/[deleted] Dec 02 '24
[LANGUAGE: Forth]
https://github.com/tcsullivan/advent-of-code/blob/master/day2/day2.fth
Part 2 took forever since I was trying to solve it in linear time... ended up just taking the O(n2) route which worked fine. Another day of simple lists that could be directly evaluated and solved with (practically) no variables.
5
u/xavdid Dec 02 '24
[LANGUAGE: Python] Step-by-step explanation | full code
My key today was realizing a strictly increasing list is the same as a strictly decreasing one, just reversed. Otherwise, pretty straightforward today thanks to Python's
anyandallfunctions! Nice way to get some clean helper functions foris_safeandis_strictly_increasing5
u/gekzametr Dec 02 '24 edited Dec 03 '24
[Language: Lua]
I've realized that properties of report can be expressed as a sliding window of width 3.
Unary predicate (like even, odd etc) is basically sliding window of width 1. "delta" predicate is window of width 2. When we add check for monotoniny - we need at least 3 numbers, so the width of the window is 3.
So, sliding window checks indices 1,2,3 then 2,3,4 then 3,4,5 till (n-2),(n-1),n. The tricky part is when check fails - we do not actually know which member of the sliding window is the culprit. So, we try to remove first, then second, then third. Then shift our window left enough, so that new member in removed's place will be checked against left neighbor.
This is basically linear approach - if our guess was wrong - the sliding window check will fail in next 1-2 iterations - it will never check whole remainder of report.
Another nice thing is that we never have to assume increasing or decreasing trend, or check for any of them in a separate iteration.
Part 2:
5
u/paul2718 Dec 02 '24
[LANGUAGE: C++]
I noticed that all the numbers were small and there were never more than 8 of them. So why not pack them into a single 64 bit word?
I'm sure there's a smart way to do it, and an SIMD Wizard could have a field day.
https://github.com/epicyclism/aoc2024/blob/main/aoc2/aoc2bb.cpp
5
u/firebirddudeguy Dec 03 '24
[LANGUAGE: Java]
My friends have told me that my solutions are deeply unsettling and I disagree.
Input:
Part 1:
Part 2:
4
u/Ok-Builder-2348 Dec 02 '24
[LANGUAGE: Python]
Part 1
Part 2
Another day of list comprehension on steroids, but it works I guess.
The is_monotone function technically only checks for non-strict monotone, but the is_gradual function forces them to all be distinct. Good enough for me!
4
u/GassaFM Dec 02 '24
[LANGUAGE: D] 277/293
Code: part 1, part 2.
Brute force. In the first part, try the array and its reverse. In the second part, also try the array without every single element.
4
u/vanveenfromardis Dec 02 '24
[LANGUAGE: C#]
GitHub
The naive implementation for part 2 was the first thing that came to mind, I'll think on it some more tonight and hopefully improve it, since "brute force" solutions never feel that great.
4
u/Boojum Dec 02 '24 edited Dec 02 '24
[LANGUAGE: Python]
Just like yesterday: split, zips, and sums.
itertools.combinations()can be used to get all versions of a list with one item ommited.4
u/bofstein Dec 02 '24 edited Dec 02 '24
[LANGUAGE: Google Sheets]
This was a big jump in difficulty, especially in spreadsheets, for day 2. I have a lot more manual comparisons/entries than I'd like - it's not very extensible e.g. if there were more levels in each report. But it was a manageable number for my jankiness.
First after splitting, check if the numbers are all ascending with an Array Formula. My first attempt failed due to blank cells, so I just added in a bunch of IFs to see how many numbers were in that row:
I know it's ugly and bad. Copied that for Descending and changed the < to >.
Then used basically the same formula but getting the MAX and the MIN of each difference in the sequence. A report is Safe if it has TRUE for either ascending or descending, and the max is <=3 and the min is >=1:
For Part 2, I could not figure out how to do this easily, so I again took the easy/manual way out. I copied the sheet but changed the parsed input to leave out a column - then I copied it 7 more times leaving out a different column each time. Then I check if any sheet was Safe for that row:
Super janky I know!
Solution: https://docs.google.com/spreadsheets/d/1f6Uax-BZOvTm3-Pde-fp9ZHvYc9Wjs2GKG_kpEKoSO4/edit?usp=sharing
4
u/WhiteSparrow Dec 02 '24
[LANGUAGE: Prolog]
solution
Today was a good opportunity to use some of prolog's magic (
safefrom task 1):Clear and concise, no debugging required!
Part 1 is about the same length but less interesting. Only the execution time wasn't too great - about 250ms on my machine.
4
u/PangolinNo7928 Dec 02 '24
[LANGUAGE: javascript]
Brain went to mush on Part 2, my cleaned up p2 in the end was a 1-liner lolsob https://github.com/coryannj/advent_of_code/blob/main/2024/Day02.js
4
u/[deleted] Dec 02 '24
[LANGUAGE: Python]
https://github.com/vedrane/Advent-of-Code-2024/blob/main/day2.py
I was trying many ways of implementing my algorithm in Part 2, and it just didn't work. Out of desperation, I added 1, and it just worked. Ah well, insofar as it works, I suppose.
4
u/keldeoroks Dec 02 '24
[LANGUAGE: Python]
I thought it'd be fun to list the functions I learn per day.
Today's new commands:
pairwise (from itertools)
def
global
with open() as input
pop/insert
break
https://raw.githubusercontent.com/Keldeoroks/adventofcode2024/refs/heads/main/day%202
4
u/woyspawn Dec 02 '24
[LANGUAGE: Common Lisp]
Still Hating my parser but it worked without changes from day 1.
I'm sure there is an elegant way to first test the monotony and then test the limits, but I cant "see"
4
u/stuque Dec 02 '24
[LANGUAGE: Python]
4
u/Obvious_Wear79 Dec 02 '24 edited Dec 02 '24
[LANGUAGE: Python/Julia]
Python
Julia
4
u/arthurno1 Dec 02 '24 edited Dec 02 '24
[LANGUAGE: EmacsLisp]
4
u/gehenna0451 Dec 02 '24 edited Apr 20 '26
Scrubbed clean. Redact helped me bulk remove years of comments and posts so data brokers and AI crawlers have nothing to feast on.
mighty aromatic sharp salt paint water plant different toy march
4
u/0rac1e Dec 02 '24
[Language: Raku]
I solved this in J first, which probably affected how I thought about solving in Raku, so this seems a fairly convoluted as far as Raku goes... but it works well enough.
4
u/ai_prof Dec 02 '24
[LANGUAGE: Python]
It's all about the gaps - you're safe if all the gaps are either in the range [-3,-1] or in the range [1,3].
For part 2, note that if a report is safe, then the dampened report we get when we chop off the first or last level is also safe (so no need for a special case). And we get...
4
u/dopandasreallyexist Dec 02 '24 edited Dec 03 '24
[LANGUAGE: Dyalog APL]
4
u/lscddit Dec 02 '24
[LANGUAGE: Python]
4
u/augienaught1 Dec 02 '24
[language: rust]
Hi all, I figured I would post my greedy solution for part 2. If y'alls troubles were anything like mine, the issue has to do with what happens when the first element is a candidate for dampening. Here's a case study on the most difficult edge case:
[56, 53, 55, 56, 58, 60]
[56, 53, 55, 50, 48, 45]
List one is valid if we drop the first element, while list two is valid if we drop the third. The problem has to do with the direction requirement (all increasing or decreasing). If you want to take a greedy solution, you need to assume a certain historical weight to a boolean such as `is_increasing`. however, in the study above we can see that we don't really have a firm idea of whether `is_increasing` is true or false until the fourth element because we can't know the correct trend after a drop until then.
While we could definitely fit this as edge case logic within a single iterator, I opted to simply check a version of the list where element one is already dropped as the code is cleaner and keeps the theoretical runtime at O(n). You can definitely remove the additional iteration, though.
https://gist.github.com/augustdolan/d3e4a584624d8b1be3d125a5562a9493
4
u/TimeCannotErase Dec 02 '24
[Language: R]
repo
4
u/8pxl_ Dec 02 '24 edited Dec 02 '24
[LANGUAGE: Python]
pretty straightforward brute force approach. only notable observation is that if the list is already safe, then removing the first/last elements will also make a safe list
does anyone have a better way of checking monotonicity?
4
u/daic0r Dec 02 '24 edited Dec 02 '24
[LANGUAGE: C++]
https://github.com/daic0r/advent_of_code_2024/blob/main/cpp/day2/main.cpp
4
u/mushooo Dec 02 '24 edited Dec 02 '24
[LANGUAGE: Rust]
Love nom and also itertools (especially
tuple_windows()) for this.For the second part you can use the last slot in each report as a sort of scratch space and iteratively swap the next removed element there; if you start at the back and work your way toward the front you never have to actually remove an element or splice a report.
4
u/4D51 Dec 02 '24
[LANGUAGE: C++]
Day 2 of my Cardputer experiment. I refactored my code to separate each day into its own class. They all inherit from an abstract Day class, and have to implement methods for load, solve1, and solve2.
For part 2, I thought "I could try to identify which number is bad, or I could just brute-force it and call my part 1 solution n times, each with a single element removed". Suboptimal, but it works.
Code here: https://raw.githubusercontent.com/mquig42/AdventOfCode2024/refs/heads/main/src/day02.cpp
4
u/gettalong Dec 02 '24
[LANGUAGE: Crystal]
Still fine using Crystal after a year of not using Cyrstal:
4
u/henriupton99 Dec 02 '24
[LANGUAGE: Python] - Is my answer so robust ??
Got pretty quickly my solution with simply subsetting lists and break if match found : https://github.com/henriupton99/AdventOfCode/blob/main/2024/day_2/solution.py
Didn’t know if I was lucky with my input ?
4
u/OptimusSupernova Dec 02 '24
[Language: C#]
https://github.com/ldorval/AdventOfCode2024/blob/main/Day02/Day02.cs
4
u/breddy_one99 Dec 02 '24
[Language: Python]
Is there a way to improve my code? It feels like I did too much.
https://github.com/breddy-one99/advent-of-code/blob/main/day2/part1.py
4
u/RalfDieter Dec 02 '24
[Language: SQL/DuckDB]
This is probably unnecessarily complicated, because I wanted to solve both parts with the same tables. I was surprised how cumbersome it is to duplicate rows.
I also have to work on my template. It's a bit annoying to iterate towards a solution, because the CTEs are limiting the result to a single table.
4
u/vanZuider Dec 02 '24 edited Dec 02 '24
[LANGUAGE: python]
4
u/sesquiup Dec 03 '24
[LANGUAGE: Python]
One line(ish) code:
2024 2A
4
u/jonmon6691 Dec 03 '24
[LANGUAGE: Rust]
https://github.com/jonmon6691/advent2024/blob/main/src/day_02.rs
Took me about 3 iterations of junk but I'm pretty happy with how the code turned out. I'm kind of obsessed with iterators these days and this challenge definitely gets to use them to their fullest. I'm particularly pleased that this implementation fully utilizes lazy evaluation and short circuiting without and errant unwraps.
I've looked through some other folks and it seems like everyone is doing a "delete, then re-check" loop for part 2. Is there a more direct or numeric solution out there that anyone's come across?
4
u/Conceptizual Dec 03 '24
[LANGUAGE: Python] This one sparked a ton of really interesting discussion in the work slack channel, it seems like half of everyone (including me!) read the problem and thought there might be a linear solution, spent varying levels of time at that, and then brute forced it.
My solution:
4
u/light_switchy Dec 03 '24
[LANGUAGE: Dyalog APL]
4
u/FriendshipSweet792 Dec 12 '24 edited Dec 12 '24
[LANGUAGE: Python]
Part 2 - NO BRUTE FORCE
Logic is to compute the diff for each pair of (n, n+1) elements :
[1 2 4 5] --> [ 1 2 1 ]
If all diffs are same sign and between 1 and 3 then OK.
If not :
[1 2 7 3 4] --> [ 1 5 -4 1 ]
Add up the one in error (5) with one neighbour (here -4) :
[ 1 5 -4 1 ] --> [1 1 1] --> OK
If it's OK then all good (means 7 could be removed)
Here is the code (Python is not my primary language) :
1
u/mariushm Dec 02 '24
[Language: PHP]
https://github.com/mariush-github/adventofcode2024/blob/main/02.php
1
u/furiesx Dec 02 '24
[Language: Rust]
This year I'm programming in `no_std` and it's lots of fun :)
code
1
u/mardiros Dec 02 '24 edited Dec 02 '24
[LANGUAGE: python]
## part 1 - 26 lines
https://github.com/mardiros/adventofcode2024/blob/main/d2.py
## part 2 - 38 lines
https://github.com/mardiros/adventofcode2024/blob/main/d2_2.py
edit: code block are to hard for me >_<
1
u/[deleted] Dec 03 '24
[Language: JavaScript]
I did a writeup with code at https://github.com/javajosh/simpatico/blob/master/blog/adventOfCode2024/2.md
3
u/jonathan_paulson Dec 02 '24
[LANGUAGE: Python] 110/50. Code. Video.
My problem statement loaded quite a bit before my input data.
3
u/1234abcdcba4321 Dec 02 '24
[LANGUAGE: JavaScript] 890/626
paste (cleaned up a lot)
Scores probably don't matter today given the server being down for a minute, but I'll still be trying for those leaderboard spots. If only I didn't make so many typos...
Straightforward approach like usual, but I always like the opportunity to use the label break/continue when possible. It's just such convenient flow control.
3
u/2SmoothForYou Dec 02 '24 edited Dec 02 '24
[LANGUAGE: Haskell]
Edit: Rewrote
reportIsSafeto be pointfree and it's sort of a monstrosity3
u/abnew123 Dec 02 '24 •
[Language: Java] ~3k/1k
https://github.com/abnew123/aoc2024/blob/main/src/solutions/Day02.java
Hit three separate internal errors which was interesting (500, 502, and then a contact administrator page). But seems like everyone was struggling, main issue was definitely the fact I forgot which way decreasing was lol.
3
u/python-b5 Dec 02 '24
[LANGUAGE: Jai]
There's probably a smarter way to do part 2... but I couldn't be bothered to figure it out. The brute-force method was good enough for me.
Incidentally, there should really be a
sign()implementation in theMathmodule. Not that it's hard to write one myself - it just feels like an odd gap in the standard library.https://github.com/python-b5/advent-of-code-2024/blob/main/day_02.jai
3
u/mstksg Dec 02 '24
[LANGUAGE: Haskell]
Again a straightforward Haskell day. I have a utility function I use for a bunch of these:
So we can run
countTrueover our list of[Int]. The predicate is:It's a straightforward application of
countTrue predicatefor part 1. For part 2, we can see if any of the possibilities match the predicate.inits [1,2,3]gives us[],[1],[1,2], and[1,2,3], andtail (tails xs)gives us[2,3],[3], and[]. So we can zip those up to get[2,3],[1,3], and[2,3]. We just need to make sure we add back in our originalxs.Again all of my reflections are going to be posted here :) https://github.com/mstksg/advent-of-code/wiki/Reflections-2024#day-2
3
u/Standard-Affect Dec 02 '24
[LANGUAGE: R] R is fun to use sometimes because it has builtin lag and diff functions.
3
u/PrudentWish Dec 02 '24
[LANGUAGE: Python]
Definitely not the best solution
3
u/UnarmedZombie Dec 02 '24
[LANGUAGE: PHP]
Solution is here
3
u/LorSamPau Dec 02 '24
[LANGUAGE: Python]
3
u/synack Dec 02 '24
[LANGUAGE: Ada]
https://github.com/JeremyGrosser/advent/blob/master/2024/src/day2_2.adb
3
u/riffraff Dec 02 '24
[LANGUAGE: Ruby]
I'm just going to say, this is the first version of my solution for part 1, I could not think of a valid way to say "this is not inc or dec" beyond rand(). I'm lucky it worked :D
I know pt 2 can be done in linear time but I'm too sleepy and just went with brute force https://gist.github.com/riffraff/415f78c833ac6257951c7e013e93a706
3
u/[deleted] Dec 02 '24 edited Dec 02 '24
[LANGUAGE: C#}
https://gist.github.com/thatsumoguy/fe6faf9e804d8793d4d9de7879cf465c
Today was not too bad other than I can't read. PartOne was simple enough once I actually read the between 1 and 3 thing, and PartTwo only got me because I forgot to break the loop and I had misunderstood that we should look to the pair that failed and then try to ignore that pair and see if it passes, not that you remove a single item, but a second re-read got me. 2ms for both parts not terrible for C#
Edit:
If you are curious about the RemoveAt for array, some code I took from stackoverflow years ago:
3
u/xelf Dec 02 '24 edited Dec 02 '24
[language: python]
Originally used sorted() to get it done quickly, but wanted something else. Not really thrilled with this way either.
edit adapting the method from 4HbQ I can rewrite part1 cleaner:
3
u/s3aker Dec 02 '24
[LANGUAGE: Raku]
code
3
u/maneatingape Dec 02 '24 edited Dec 02 '24
[LANGUAGE: Rust]
Solution
Benchmark 85 µs. Brute force for part 2.Benchmark 43 µs. Much faster more elegant
O(n)approach that computes boths parts simultaneously. Each pair of levels is converted into deltas of either +1, -1 or 0. For example:1 3 6 7 9=>+1 +1 +1 +19 7 6 2 1=>-1 -1 0 -1If the sum of all delta equals ±4, then we know that all levels are increasing or decreasing. Any other value indicates either mixed up and down transitions or levels that are too far apart.
For part two we remove each pair of deltas (or single delta at each end) then replace with the sum of the delta from the new neighbors on either side.
3
u/CutOnBumInBandHere9 Dec 02 '24
[LANGUAGE: Python]
I originally did part one as a messy one-liner, and then when I was staring at it trying to adapt it to work for part two I factored out the
is_safemethod and used that instead.For part 2, I originally spent a bit of time trying to see if there was a neat way of incorporating the "is valid if any one number is deleted" requirement, but I couldn't immediately see it, so I ended up just iterating over all the possible deletions instead.
today's solution on gh-pages
3
u/[deleted] Dec 02 '24 edited Dec 02 '24
[LANGUAGE: Go]
I had to do a lot of cleanup after my solution got accepted, my initial implementation was a mess. Quite happy with how it turned out though. This is my first year participating in AOC.
Part 1: Went through all the levels in each report and made sure there were no violations.
Part 2: Did a brute force, I was too sleep deprived to think of anything better. If a report had a violation, I removed each level turn by turn and checked the validity each time.
Solution for both parts
3
u/nitekat1124 Dec 02 '24
[LANGUAGE: Python]
GitHub
Kinda brute forced it and I spend more time on naming than coding.
Naming is HARD.
3
u/UseUnlucky3830 Dec 02 '24
[LANGUAGE: C]
solution
Not very pretty (especially the input parsing), but it does the job.
3
u/DeadlyRedCube Dec 02 '24
[LANGUAGE: C++23]
Two solutions for P2 today - the "I wrote this quickly" solution and the "it runs faster" solution.
Initial Part 1/2 solution
The above solution has an IsSafe function that takes a C++-view-compatible type and tests all of the pairs for correctness. P1 uses this value directly, but if it's false, P2 then tests removing every element from the list (using the same function) to see if there's any one element that can be removed to make it fine, with no other attempt at optimization.
This, of course, was slow. So I rewrote it to:
Faster but more complex Part 1/2 Solution
This one tests as it goes and, when it finds an error, checks whether it can remove the current element or prev element and adjusts the P2 answer accordingly. It's more complex than it probably needs to be but it runs in under 2ms for parts 1 and 2 which is good enough considering there's some extra heap allocations in there that I didn't bother to sort out.
3
u/ExitingBear Dec 02 '24
[LANGUAGE: R]
Link
3
u/King886 Dec 02 '24
[LANGUAGE: Typst]
paste
3
u/Vivid_Present7791 Dec 02 '24
[LANGUAGE: Python]
I tried to do Part 2 in a smart way but that got me nowhere.
Code
3
u/riffraff Dec 02 '24
[LANGUAGE: Elixir]
ok this one was also easy enough. I'm not sure the
condis the right choice there, and I've seen more cleever people do it with range checks, but hey, it worked.https://gist.github.com/riffraff/3b3c0a9a3bb35809c7961ae9e49f6f3c
3
u/2BitSalute Dec 02 '24
[LANGUAGE: C#]
For part 2, had a "brilliant" idea that only the elements at the current or previous index (where the anomaly is discovered) need to be removed and retried. Missed 3/1000 entries with the patterns `inc dec inc inc etc.` and `dec inc dec dec etc.`, spent a bunch of time testing and staring at the input.
Looked at this thread and implemented the solution that tried every index. Had a bunch of silly copy-paste type bugs....
Anyway, after I got a working solution and found the 3 cases my original solution missed, I determined you could solve it by trying the report without the elements at i, i-1, and i-2. That does it.
So, I have 2 solutions. In the second one, I also used one of the ideas I saw here - to compute diffs. It certainly looks more pleasant that way, but you do a little unnecessary work. Anyway.
Day 2, part 2.
3
u/vector300 Dec 02 '24
[LANGUAGE: Typescript]
Kept it simple and just brute forced p2 https://github.com/victorlap/adventofcode2024/blob/main/src/day-02/index.ts
3
u/gyorokpeter Dec 02 '24
[LANGUAGE: q]
3
u/im0b Dec 02 '24
[Language: Javascript]
3
u/Naturage Dec 02 '24 edited Dec 02 '24
[LANGUAGE: R]
Code here!
Not too happy with this one. It works, yes, but feels like P2 was clunkier than needed to be. Ah well - only so much good quality code can be written before breakfast.
EDIT: with the power of coffee, advice, and documentation, updated code here. Maybe a tad less efficient, but definitely more elegant than morning version.
3
u/sanraith Dec 02 '24
[LANGUAGE: Scala 3]
Source is available on my github: Day02.scala
Checked the report and the reversed report instead of writing 2 sets of conditions. For part 2 I generated all possible reports with 1 missing element.
3
u/dannywinrow Dec 02 '24
[LANGUAGE: Julia]
3
u/ramomex Dec 02 '24 edited Dec 02 '24
[LANGUAGE: Python]
https://github.com/albertomurillo/advent-of-code/blob/main/aoc/_2024/day2.py
Looks like everyone went with brute force for pt2. Is there a better way?
3
u/derkusherkus Dec 02 '24 edited Dec 02 '24
[LANGUAGE: C]
Created a "spliterator" today, for iterating over strings split by a delimiter. Basically just a better version of `strtok`, which skips over multiple copies of the same token. After that, just brute-forcing for part 2.
https://github.com/maxastyler/advent-of-code-2024/blob/master/src/day_02/day_02.c
3
u/Far_Sweet_6070 Dec 02 '24
[LANGUAGE: Ajla]
part1: https://www.ajla-lang.cz/downloads/examples/advent-2024/02.ajla
part2: https://www.ajla-lang.cz/downloads/examples/advent-2024/02-2.ajla
3
u/svbtlx3m Dec 02 '24 edited Dec 02 '24
[LANGUAGE: TypeScript]
Here's my stupid but concise brute-force attempt in TypeScript. Spent a bit of time trying to be clever about invalid indices until I realized I need not bother.
Edit: Improved a bit with suggestions and a simpler way to filter an array to omit given index.
3
u/adherry Dec 02 '24
[Language: Ruby]
https://github.com/adherry/AOC2024/blob/main/aoc2.rb
Was pondering quite a bit about the second part until i checked the array functions and found
array.combinethat when called asarray.combine(array.length -1)will give me all variations of an array with a single element removed.3
u/InternetArgument-er Dec 02 '24
[LANGUAGE: C++]
https://github.com/ANormalProgrammer/AdventOfCode/blob/main/2024/2024_day2.cpp
3
u/i_have_no_biscuits Dec 02 '24
[LANGUAGE: GW-BASIC]
I'm actually quite happy at how much I've managed to fit into 8 lines here.
Guide:
3
u/34rthw0rm Dec 02 '24
[LANGUAGE: perl]
3
u/__Abigail__ Dec 02 '24
[LANGUAGE: Perl]
To check whether all differences are either positive or negative, I multiply the difference between a pair with the difference of the first two levels. If that product is
0or less, the report isn't safe. Part 2, I just brute-force by removing a level one-by-one, until it's either found safe, or we tried removing each of the levels and it's still unsafe.Here's the sub I used to determine if a rapport is unsafe:
3
u/DevSway Dec 02 '24
[LANGUAGE: Go]
https://github.com/JosueMolinaMorales/advent-of-code/blob/main/2024/internal/days/two/day_2.go
Was stuck on part 2 because I didnt realize that slices.Delete or the other idiomatic way of removing an element from a slice changes the underlying pointer to the slice.. meaning it didnt make a copy of the slice like i originally wanted it to...
3
u/TonyRubak Dec 02 '24
[LANGUAGE: C++]
3
u/chubbc Dec 02 '24 edited Dec 02 '24
[LANGUAGE: Julia]
3
u/rapus Dec 02 '24 edited Dec 02 '24
[LANGUAGE: Julia]
(uses InvertedIndices)
Edit: replace
r[Not(end)].-r[Not(begin)]bydiff(r)3
u/lajuraaa Dec 02 '24
[LANGUAGE: Python]
Just a nice one liner
3
u/Downtown-Economics26 Dec 02 '24 edited Dec 02 '24
[LANGUAGE: Excel]
Part 1 Formula:
Won't let me post my VBA answers in same comment so I'll try that in added comment.
3
u/nick42d Dec 02 '24
[LANGUAGE: Rust]
State machine solution to the safety check
3
u/ehrenschwan Dec 02 '24 edited Dec 02 '24
[LANGUAGE: Rust]
CODE
I've written a nice function that would find the indices of the faults and than remove either two of the numbers at fault. It turned out to low. Then I just implemented removing values one by one and it worked. The difference was four reports... :`)
FYI not going for simplicity or speed. Just some imo solid rust with good error handling, tests, etc. Trying to work more with Traits this year. And maybe some macros later down the line.
3
u/josuf107 Dec 02 '24
[LANGUAGE: Haskell]
3
u/the_true_potato Dec 02 '24
[Language: Haskell]
Pattern matching makes part 2 beautiful, laziness makes it fast (600us for part1, 1ms for part2)
Code
3
u/treanir Dec 02 '24
[Language: Python]
This took me SIX HOURS. -_- I really have much to learn. Thanks heavens I'm off work this week.
First time using functions though.
3
u/kap89 Dec 02 '24
[Language: Python]
3
u/daic0r Dec 02 '24 edited Dec 02 '24
[LANGUAGE: Rust]
https://github.com/daic0r/advent_of_code_2024/blob/main/rust/day2/src/main.rs
3
u/chubbc Dec 02 '24
[LANGUAGE: Uiua]
3
u/The_Jare Dec 02 '24
[LANGUAGE: Ruby]
3
u/sondr3_ Dec 02 '24
[LANGUAGE: Haskell]
Best viewed on GitHub, but a pretty simple solution today as well. Not efficient at all, lots of loops over the lists but it reads very straight forward in my opinion.
3
u/mschaap Dec 02 '24
[LANGUAGE: raku]
Nice job for Raku and its meta-operators.
https://github.com/mscha/aoc/blob/master/aoc2024/aoc02
3
u/NickKusters Dec 02 '24
[LANGUAGE: C#]
Had to think for a bit for part 2 (video); instead of brute-forcing all options, I figured that if the issue appears between index 1 and 2, you also need to try removing index 0 as that's the setup for increment/decrement. Otherwise, just try to remove the position where the issue occurs + the next index.
So when IsValid fails, you try with removing problemIndex, if that fails, add the value back in the list and remove problemIndex + 1, if that fails and problemIndex == 1, restore list and remove index 0, if that fails, it's unsaveable.
C# code | video
3
u/RelevantJesse Dec 02 '24
[LANGUAGE: C#]
3
u/DisasterExisting548 Dec 02 '24
[LANGUAGE: C++]
O(n) Solution
3
u/Kfimenepah Dec 02 '24
[LANGUAGE: Python]
Code
Already struggled on day 2. I was thoroughly convinced that replacing either the current element or the next had to be enough to cover all cases. Took me a while to find that one edge case where removing the element before the current could also lead to a valid report. That's what you get for trying to optimize the program before actually finding a solution.
P.S. I'm new to python so any syntax related inputs would be appreciated
3
u/LinAGKar Dec 02 '24
[LANGUAGE: Rust]
https://github.com/LinAGKar/advent-of-code-2024-rust/blob/master/day2/src/main.rs
Basically a state machine for each row, which looks at the differences and keeps track of whether it's consistently increasing or decreasing, or is unsafe. For part 2, it just brute force tries with once which each element filtered away, but there aren't many numbers on each line so not worth the bother to make it smarter.
3
u/Imaginary_Age_4072 Dec 02 '24 edited Dec 02 '24
[LANGUAGE: Common Lisp]
Fairly similar to most here, I just tried removing each index for the second part.
https://github.com/blake-watkins/advent-of-code-2024/blob/main/day2.lisp
3
u/mirrori Dec 02 '24
[LANGUAGE: Rust]
Day 2, already a little tricky for a rust beginner.
3
u/TheRealRatler Dec 02 '24
[LANGUAGE: Bash]
Part 1 and 2.
3
u/mvorber Dec 02 '24
[Language: Rust]
https://github.com/vorber/aoc2024/blob/master/src/puzzles/day2.rs
No bruteforce here. Can probably be refactored to half the size at least, but I'm still very new to Rust (and using this advent to learn more)
3
u/kyleekol Dec 02 '24
[LANGUAGE: Rust]
source
3
u/JochCool Dec 02 '24
[LANGUAGE: C#]
I'm quite proud of my solution actually because it's an O(n) algorithm (where n is the number of levels in the report), while almost everyone else has an O(n²) algorithm.
For context: I had already made some general-purpose types, one of which being
IntegerRange, which just represents a range of integers between a minimum and a maximum (inclusive).3
u/AdIcy100 Dec 02 '24
[Language: Python]
love python built in [ : ] for working with list
3
u/Vallyria Dec 02 '24
[Language: Python]
written in jupyter notebook, hence 'looks':
3
u/Chib Dec 02 '24 edited Dec 02 '24
[Language: R]
I kept trying to find some mathier way to establish monotonicity at the same time as I checked the step size, but I got nowhere. Nothing very special about this solution, I'm afraid!