r/adventofcode • u/daggerdragon • Dec 04 '23
SOLUTION MEGATHREAD -❄️- 2023 Day 4 Solutions -❄️-
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
- Before creating a
Visualization, please review the guidelines for creatingVisualizations as there's good advice relating to accessibility, readability, colors, timing, etc. Posts containing AI-generated art must:
- Use the standardized post title syntax
- Indicate in their titles with the tag
[AI art] - Use the
Funnypost flair
THE USUAL REMINDERS
- All of our rules, FAQs, resources, etc. are in our community wiki.
Outstanding moderator challenges:
Community fun event 2023: ALLEZ CUISINE!
- 2 DAYS remaining until unlock!
AoC Community Fun 2023: ALLEZ CUISINE!
Today's theme ingredient is… *whips off cloth covering and gestures grandly*
PUNCHCARD PERFECTION!
Perhaps I should have thought yesterday's Battle Spam surfeit through a little more since we are all overstuffed and not feeling well. Help us cleanse our palates with leaner and lighter courses today!
- Code golf. Alternatively, snow golf.
- 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? >_>
ALLEZ CUISINE!
Request from the mods: When you include a dish entry alongside your solution, please label it with [Allez Cuisine!] so we can find it easily!
--- Day 4: Scratchcards ---
Post your code solution in this megathread.
Read the full posting rules in our community wiki before you post!
- State which language(s) your solution uses with
[LANGUAGE: xyz] - Format code blocks using the four-spaces Markdown syntax!
- State which language(s) your solution uses with
- Quick link to Topaz's
pasteif you need it for longer code blocks
18
u/voidhawk42 Dec 04 '23 edited Dec 04 '23
[LANGUAGE: Dyalog APL]
Video walkthrough
Apparently the infinite series sum of matrix exponentiations converges to (𝐼−𝐴)^−1, thanks to rak1507 on the APL discord for pointing that out!
17
u/FlyingPlatypus5 Dec 04 '23
[LANGUAGE: python3]
89/437
First time getting leaderboard in my life!
Around 0.9ms to run :)
3
u/presidentpanic Dec 06 '23 edited Dec 06 '23
[Language: GDScript]
For some reason I really struggled with part 2, originally going down the route of keeping a stack/queue. After a few hours I was too tired and used this solution for reference by u/LastMammoth2499, and now it makes sense:
Solution to Part 1 and 2
2
u/bigmagnus Dec 04 '23
[Language: Fortran]
Part 1
Part 2
20
u/jonathan_paulson Dec 04 '23 edited Dec 04 '23
[LANGUAGE: Python 3] 58/9. Solution. Video.
Had a wrong answer on part 1 because I didn't read the scoring system carefully enough. It's interesting that the part 2 answer was small enough that you could afford to simulate each card (rather than each type of card) - although that would've been more complicated to code up.
19
u/syntaxers Dec 04 '23 edited Dec 04 '23
[LANGUAGE: Python] 70 / 70
Original solution
[Allez Cuisine!] golfed solution that fits in 80x5 chars
First time getting top 100 since starting 3 years ago with a few close calls :)
19
u/Smylers Dec 04 '23 edited Dec 04 '23
[LANGUAGE: Vim keystrokes] [Allez Cuisine!]
Load your input, type the following, and your part 1 answer will appear:
After removing card numbers,
/\v<(\d+)>\ze.*\|.*<\1>/matches any entire number which is followed by a|and then the same number again — so a winning number that is in the list of numbers we have. Replace it with a#to indicate a match. Do that for all winning numbers, then get rid of everything that isn't a#character.The sample input will now look like this:
[plus 2 blank lines at the end]
Replace the first
#on each line with+1and any subsequent#s with*2. The sample input is now:At which point, deploy the usual design pattern to evaluate the expression and get the answer.
I'm not sure whether this counts as code golf (for ‘Allez Cuisine!’ purposes) or not? I mean, I haven't intentionally golfed the keystrokes; it just naturally comes out like that.
Update: A part 2 solution which loops in a fraction of a second rather than ... I dunno — hours? days? And it fits within the forum rules on code size:
The first line is the same set-up as in part 1: creating a histogram of matching numbers out of
#s. Replace each string of#s with their length and prepend+1to each line, to represent initially having one of each card.Consider a line like:
This represents 17 instances of a card with 4 matching numbers, so the cards on the next 4 lines each need their counts increasing by 17. This is what the main loop does. It finds the next match count (a number that follows a space) and deletes it with
D, which both stops it getting in the way of future calculations and handily saves it to the"-small-delete register.Then it goes back and yanks the number of cards. Yanks by default get stored in the
"0register, which crucially is different from"-.To increase the appropriate counts it does something like
V4joj17⟨Ctrl+A⟩: start by visually highlighting the current line, then extend down 4 lines (or fewer if near the bottom). However, that will have highlighted 5 lines, because it includes the line we started visual mode on as well as the 4 we added. To adjust for this fence-post error,oswitches control to the start of the area andjtakes the it down a line. Then17⟨Ctrl+A⟩adds 17 to the first number on each highlighted line, the card count that's just after the+.Except of course the
4and17can't be hard-coded. Just like@aruns the keyboard macro of keystrokes saved in the"aregister,@-runs the keystrokes stored in"-. If"-contains4then@-jis like doing4j. Yes, this means the keyboard macro ‘runs out’ partway through a command, but try not to let that bother you; the important thing is that it works! And similarly,@0⟨Ctrl+A⟩prefixes the⟨Ctrl+A⟩operator with the number stored in"0.By the time the loop ends, all the numbers of matches will have been removed, leaving just the card counts, each preceded by a
+. Join them together and evaluate the sum to get the answer.This is a massive improvement on my original solution for part 2, which represented each instance of a card visually with
#. This worked fine on the sample input, but on my real input ... well, since I set it off, I've eaten breakfast, showered, tidied away last night's board game, walked a child to their bus stop, implemented the faster version above, and written up this explanation of it, and it's still going. I don't think it's going to reach Matt Parker-like levels of percentage speed-up between it and the fastest solution, but we can't be sure yet. (I'll move its original explanation to a reply for posterity.)Update 2: I
⟨Ctrl+C⟩ed it after 6½ hours (because we needed the fan to stop being so noisy). Vim's status line said50%. It was processing line 99 of 196, and the first 96 593 copies of the card on that line had been processed (the#s already turned into.), with 238 662 cards still to go. Line 100 already has 330 651#s on it. So optimistically it was about halfway through. Realistically, the lines have been getting longer so it probably had much more than half to go, and it might not have finished before the boat leaves tomorrow.13
u/4HbQ Dec 04 '23 edited Dec 04 '23
[LANGUAGE: Python] Code (9 lines)
Nothing clever today, but I like this part:
8
u/CCC_037 Dec 04 '23
[Language: Rockstar]
Listen to my words for they carry knowledge of thine winnings...
8
u/[deleted] Dec 04 '23 edited Dec 04 '23
[LANGUAGE: Google Sheets]
Assuming the input is in A:A
One formula for both parts
8
u/JustinHuPrime Dec 04 '23
[LANGUAGE: x86_64 assembly with Linux syscalls]
Alas, even 8086 assembly would be far too late for actual punchcards, and I would also need at least an 80386 to get 32 bit integers, a soft requirement given the size of numbers eventually encountered in the problem.
Part 1 was parsing; this was a bit fiddly, I needed to be careful about whether I interpreted the numbers as having leading whitespace (the correct way) or trailing whitespace (incorrect, since I'd be skipping the newline at the end). The actual computation was relatively nice, involving a nonconstant shift left to do the exponentiation of the base 2 required.
Part 2 was more of a fibonacci-type problem. Re-using the parser from part 1, I had to keep two lists - one list mapping the card number to the number of wins for one card, and another counting the number of cards. The one counting the number of cards had to be zero-terminated, a fact which I forgot, since I wanted to operate on variable length data (either the example or the actual input, since my personal rules require me to write code that accepts either the example or the actual input depending on what filename is passed in as a command line argument).
The actual computation was relatively straightforward, but the debugging was not. I ended up learning about GDB's foibles - it considers global labels to be actual variables and not the pointers that they so obviously are. (Well, I suppose if you're one of the folks who uses a compiler, global labels are actually variables, but this is at odds with how they're treated in assembly.)
Part 1 and part 2 run in 1 ms; part 1 is 8232 bytes long, and part 2 is 8480 bytes long. I think the shrinking size is because I moved a global from the .data section to the already-existing .bss section. Since I no longer used the .data section, this could be omitted from the generated executable, saving quite a bit of space, apparently.
8
u/kaa-the-wise Dec 04 '23 edited Dec 04 '23
[Language: Python] one-line/single-expression solutions
Had fun with this one! A short solution for part 1, using as an heuristic, that numbers on each side are distinct, and a functional-style one for part 2:
https://github.com/kaathewise/aoc2023/blob/main/4.py
8
u/niccolomarcon Dec 04 '23
[LANGUAGE: Haskell]
Really proud of my solution today, short and efficient, with no explicit recursion c:
8
u/clbrri Dec 04 '23 edited Dec 04 '23
[LANGUAGE: C/C++]
Part 2 in 23 lines of code
(Solved on stream in twitch channel
clbi)Runs in about two minutes on my Commodore 64. (runtime is dominated by disk accesses)
EDIT: Also benchmarked the same code on AMD Ryzen 5950X, which took about 0.00075 seconds. (making it about 160,000x times faster than the C64)
Daily journal
7
u/leijurv Dec 04 '23
[LANGUAGE: Python3]
10th place, 22nd place
Screen recording: https://youtu.be/IsOIBSoY85k
7
u/msschmitt Dec 04 '23
[LANGUAGE: Python 3]
Part 2
Fortunately no recursion needed. Just add whatever count the current card number has to the x cards that follow.
If this were later in the month we'd be making copies of specific cards, such as "multiply the Card Id * winning number, you get another of that card". But how would it ever end?
My real job isn't Python which is why I'm lacking in the list comprehensions the cool kids use.
7
u/[deleted] Dec 04 '23 edited Dec 04 '23
[LANGUAGE: Forth] [Allez Cuisine!]
For Allez Cuisine!, I minimized my part 1 to less-than-punchcard size. It even executes your input file directly as code and automatically detects the scratchcard's size! Simply download your
inputfile to the same directory and callgforth part1.fth(or use some other Forth that supportsinclude). Code below:https://github.com/tcsullivan/advent-of-code/tree/master/day4
6
u/boblied Dec 04 '23
[LANGUAGE: Perl]
Part 2
(a) No need to split the winners and picks, just find the ones that appear more than once. Perl has a cute FAQ idiom using a hash to find duplicates.
(b) Recursion will kill us if we try to calculate the matches every time. Do it one pass while reading the input.
(c) There's no need to carry the lists around; it's all a function of match counts and id numbers. Sequential id numbers make great array indexes.
6
u/purcell Dec 04 '23
[LANGUAGE: uiua]
6
u/Zweedeend Dec 04 '23
[Language: Python] [Allez Cuisine]
How do I save more characters?
5
u/seligman99 Dec 04 '23
[LANGUAGE: Python] 151 / 170
github
I like this one a lot. Straight forward enough, but still, a different sort of puzzle.
5
u/KayZGames Dec 04 '23
[LANGUAGE: Dart]
So far my shortest solution at around 30 lines of actual code.
5
u/penguinencounter Dec 04 '23 edited Dec 04 '23
[Language: Python 3.8] [ALLEZ CUISINE!] Part 1 and Part 2 solutions fit on one 5 ln / 80 col card each. (please don't make me cram both of them into one card >_< I just wanted the bonus points)
Both parts need an EOF to work, so either hit
Ctrl-D(*nix afaik) after entering the last line or pipe the input in from a file.Part 1:
Part 2 (295 bytes) was the real tough one. Highlights include using
__setitem__to avoid a for-loop and opening stdin as a file.Edit 1: -14 bytes by using
&instead of.intersectionEdit 2: -8 bytes with
readlines()instead ofread().splitlines()5
u/encse Dec 04 '23
[LANGUAGE: C#]
Finally a bite size one.
https://github.com/encse/adventofcode/blob/master/2023/Day04/Solution.cs
5
u/SpaceHonk Dec 04 '23
[Language: Swift] (code)
Easiest day so far, IMHO.
Sets make counting winners in part 1 trivial. For part 2 I keep an array of copy counts, initialized with all 1s that I simply need to add up for the final result.
5
u/TiagoPaolini Dec 04 '23
[Language: C]
In order to keep track of the numbers for each card I used an array of booleans: the index represents the number, if it is present on the card then its value is
true. Since there numbers go up to 99, the array had 100 elements. I also had array to keep track of how many winning numbers each card have, and another for how many of each card there is. When each card was parsed, its count was incremented by 1 and its amount of winning numbers were stored. Needless to say, I performed bounds check on each array operation.For Part 1, the card's score was
1 << (win_count - 1)if its amount of winning numbers was greater than zero, otherwise the score was zero. Then all scores were added together.For Part 2 I had an outer loop that went over each card once, and an inner loop that went through the obtained cards following the current card. The inner loop added the amount of the current card to each of the obtained card. That is because if you have
nof a card withmwinning numbers, then it is going to winntimes, and each of those wins gets you 1 new card for each of the followingmcards. After all cards were processed, I added together the final count of each card.My solution: day_04.c
5
u/Potential-Series-105 Dec 04 '23
[LANGUAGE: Ruby]
66 bytes seem to be enough for part 1
5
u/ka-splam Dec 04 '23 edited Dec 04 '23
[LANGUAGE: APL]
Part 1:
Part 2:
Stumbled on the number of doublings, tripping over intersections which resulted in empty sets. Then tried to 'power' through part 2 and 90 minutes later I still couldn't. Came back and made it work now.
5
u/bozdoz Dec 04 '23
[LANGUAGE: rust]
https://github.com/bozdoz/advent-of-code-2023/blob/master/day-04/src/main.rs
Still a newbie. Felt like one of the the easiest days so far 🦀
4
u/UseUnlucky3830 Dec 04 '23 edited Dec 04 '23
[LANGUAGE: Julia]
I got tripped up by trailing whitespace because I didn't use a regex. On a more positive note, I had been waiting for a chance to use the left shift operator in the real world and today it finally happened (yes, advent of code *is* the real world). But seriously, I should start worrying about my reading comprehension skills..
GitHub
4
u/Imaginary_Age_4072 Dec 04 '23
[LANGUAGE: Common Lisp]
Day 4
Parsing wasn't too bad, got tripped up a little with extra whitespaces here and there but not too bad.
Then, the part 2 solution just used a hash table and a couple of loops to count how many of each card were dealt:
4
u/Prudent_Candle Dec 04 '23
[LANGUAGE: Python]
I used the sets. So find the matching numbers is just a
intersectionmethod. The second part two I made by dictionary, which kept how many card with specific index has been given to the player (for the example given in the task, it is:1:1 2:2 3:4 4:8 5:14 6:1).The code paste
4
u/Hasbro10 Dec 04 '23 edited Dec 04 '23
[Language: Python] import re from math import pow from dataclasses import dataclass
4
u/enelen Dec 04 '23 edited Dec 04 '23
[Language: R]
Solution
4
u/Lispwizard Dec 04 '23
[Language: EmacsLisp]
4
u/brtastic Dec 04 '23
[Language: Perl]
Github
Had problems understanding part 2, so my solution ran super slow. After getting the right answer I refactored the code and got a whooping 420 times speedup (1.68s -> 0.004s).
4
u/AnxiousMasterpiece23 Dec 04 '23
[LANGUAGE: JavaScript]
Look Ma, no recursion!
Whenever I encounter recursive rule sets I opt for an iterative solution because my view on recursive functions is "just because you can, doesn't mean you should"
https://github.com/ccozad/advent-of-code/blob/master/day-4.js
4
u/Fyvaproldje Dec 04 '23
[LANGUAGE: Raku] [Allez Cuisine!]
4
u/[deleted] Dec 04 '23 edited Dec 04 '23
[LANGUAGE: Python] Part 2 fried my brain but heere we go. Runtime 2.5-3.5ms
4
u/faeryl Dec 04 '23
[LANGUAGE: C#]
https://github.com/tomaszcekalo/AdventOfCode2023_4
Was definitely easier than day 3. Note: GitHub incorrectly states that the code is in smalltalk, it's not. Not sure why its doing that.
4
u/wubrgess Dec 04 '23
[language: perl]
day 4
uses my lib packages
it's interesting that after parsing, the actual winning numbers aren't useful
4
u/litezzzOut Dec 04 '23
[LANGUAGE: asm]
MASM 64bit
Both Parts
4
u/Wraldpyk Dec 04 '23
[LANGUAGE: JavaScript]
Luckily I realized you don't need to make actual copies, but just increment the number of cards you have. Makes for a very quick resolution. Probably could be improved even further, but I'm happy with my 4ms execution of part 2.
Github Day 4
4
u/FrontPale Dec 04 '23
[LANGUAGE: Julia / Julialang]
4
u/Salad-Extension Dec 04 '23
[Language: C#]
Short...ish, to the point, but still readable. Both parts with a single traversal.
Code
4
u/_rabbitfarm_ Dec 04 '23
[Language: Perl]
Solutions to both parts in Perl. I decided to make things a little more object oriented than usual. In this case I used the lightweight Class::Struct module.
Part 1: https://adamcrussell.livejournal.com/48067.html
Part 2: https://adamcrussell.livejournal.com/48162.html
4
u/Zach_Attakk Dec 04 '23
[LANGUAGE: Lua]
Part 1 was pretty simple. Calculate the number of wins for each line, any score above 1 is 2wins.
Part 2 sort of looked like recursion but turns out it's easier to keep a separate list of multipliers and increase the future winning multipliers by how many the current card has. If you step through the code you can follow the bulleted clarification line by line.
Part 1
Part 2
4
u/erikade Dec 04 '23 edited Dec 04 '23
[LANGUAGE: Golang]
As last two years, I'm trying to compose the speediest programs possible with no external dependencies. Thanks to u/topaz talent, while doing so I'm sometime rewarded by finding a gem. I mean a particular insight of the challenge at hand that translates beautifully into code.
Today I found one that reminds me some of the neatest math/physics formulas. Namely, today's part1 score is computed as: score += 1 << nmatch >> 1
Right now, it's going really well with all parts, all days running in less than
4ms:Last year collection runs end-to-end with
make -j8in less than50mson a regular MBAir M1.Happy coding to you all!
Github Repo
4
u/EagleDelta1 Dec 04 '23
[LANGUAGE: Go]
https://github.com/dhollinger/adventofcode/tree/main/2023/go/day4
4
u/chicagocode Dec 04 '23
[LANGUAGE: kotlin]
Today's puzzle answers the question - "Can Todd solve this and write it up during his lunch break at work?" - YES! Basically, store the scores only because that's the only thing we really care about, and then use an array to keep track of cards for part 2.
My code can be found on GitHub, I've written this up on my blog, and here are my 2023 Solutions so far.
4
u/dec0nstruct0r Dec 04 '23 edited Dec 04 '23
[LANGUAGE: R]
always love to use the %in% operator in R
https://gitlab.com/Yario/aoc_2023/-/blob/master/AoC_04.R
4
u/jpjacobs_ Dec 04 '23
[LANGUAGE: J]
Of course my code fits on a punch card (with space to spare to fit in an alternative recursive version (pp2) for part 2)! Part 2 uses Fold multiple fwd, starting with extra 1 in state to keep initial card in count. {. keeps current card count for each card. Win reduces #state at every iteration to keep track of where copies times ones should be added.
PS: p1 and p2 take input as string (with ending linefeed, as read from file).
4
u/readyforwobbles Dec 04 '23
[language: python 3]
part 1
4
u/whezya Dec 04 '23 edited Dec 05 '23
[LANGUAGE: Elixir]
Still took me much longer than expected, mainly because I am not used to standard lib. But the special feeling of functional prog, when you solve one function call after misreading doc and everything start to work together cleanly, is here.
Parser combinators are overkill, but this is a good way to practice.
Edit : I am glad I could manage a state in Elixir, but I found an easier functional solution just after finishing this one...
https://github.com/rbellec/advent_of_code_2023/blob/main/lib/day04.ex
4
u/chubbc Dec 04 '23
[LANGUAGE: Julia]
Sadly couldn't think how to shrink things down any further, but its pretty concise.
4
u/emmadotx Dec 04 '23 edited Dec 05 '23
[Language: Pascal]
4
u/nicuveo Dec 05 '23
[LANGUAGE: Haskell]
Not showing part 1 for brevity. The fun trick here is using a hashmap that's defined in terms of itself for memoization. :)
4
u/Krryl Dec 05 '23 edited Dec 05 '23
[LANGUAGE: Python]
Part 1
Part 2
with open ('input4.txt', 'r') as f:
4
u/wzkx Dec 05 '23
[LANGUAGE: C]
4
u/collegesmorgasbord Dec 05 '23 edited Dec 05 '23
[LANGUAGE: python]
Clean python solution (depends on your idea of "clean", you may not like list comprehension for part 1 but part 2 solution is nice and simple)
4
u/Infamous-World-2324 Dec 07 '23 edited Dec 07 '23
[LANGUAGE: bash] [Allez Cuisine!] Run it with
bash 4.sh 4.txtwhere4.txtis your input and4.shis the following:And it fits on a punchcard!
4
u/xHyroM Dec 12 '23
[LANGUAGE: Python]
part 1
part 2
4
u/nicuveo Dec 12 '23
[LANGUAGE: Brainfuck]
won't fit in here: it's 9000 lines of Brainfuck just for part 1!
VOD: https://www.twitch.tv/videos/2002551041
code: https://github.com/nicuveo/advent-of-code/blob/main/2023/brainfuck/04-A.bf
4
u/lsloan0000 Dec 13 '23 edited Dec 14 '23
[Language: Python]
I see that many other people take the time to convert the numbers on each card from strings to numerical types (
int()). That's unnecessary because no math operations are performed on those numbers.You may have noticed I like to use assignment expressions (AKA the "walrus operator",
:=→ [place walrus emoji here]). I don't want to write repetitive code, so this helps. It may make my code a little less readable. The expressions alone don't make my code a lot shorter, so it doesn't quite qualify for "Allez Cuisine" code golf. Maybe it's the worst of both worlds. 😆2
u/nikscorp Dec 04 '23 edited Dec 05 '23
[LANGUAGE: Go]
Quite simple and straightforward solution
GitHub
1
u/TankLivsMatr Dec 04 '23 edited Dec 05 '23
[LANGUAGE: Go]
Got this in about 2 hours. I knew that part two would be a bit more complex so I opted to start with a struct / methods for it. 2nd part was a lot easier due to preparation for that.
https://github.com/kyallanum/advent_of_code_2023/blob/main/Day_4/main.go
1
u/starryhound Dec 04 '23
[LANGUAGE: C#]
https://nbviewer.org/github/starhound/AoC2023/blob/0baeed33a24bb5051685fb6d56641984e0977975/AdventOfCode2023.ipynb#Day-4
3
u/DFreiberg Dec 04 '23
[LANGUAGE: Mathematica] Mathematica, 228 / 751
Today's part 2 feels like it's amenable to an in-place replacement trick to make it a true one-liner, but the
Do[]loop was so natural I did the problem procedurally anyway.Import:
Part 1:
Part 2:
3
u/Goues Dec 04 '23
[LANGUAGE: JavaScript] 604 / 281
3
u/ButterHotline Dec 04 '23 edited Dec 04 '23
[LANGUAGE: C#]
3
u/RinkAttendant6 Dec 04 '23
[LANGUAGE: JavaScript]
1177/4833. Stumbled on part 2 by trying to build a queue with all the cards and memoizing the results, then realized that it can be solved by keeping track of the number of copies of the current card to know how many of the subsequent cards to add.
3
u/mebeim Dec 04 '23
[LANGUAGE: Python 3]
758/2614 — Solution — Walkthrough
I did not think it was possible to mess up so many times such a simple problem. My brain refused to understand part 2 rules for a good 10 minutes. You can tell I am definitely NOT a morning person :'). Regardless, nice problem!
3
u/coderhs Dec 04 '23 edited Dec 04 '23
[Language: Ruby]
Part 1
Part 2 (Took a while to run this code (10 seconds) looking into more efficient way)
3
u/Ferelyzer Dec 04 '23
[LANGUAGE: Matlab]
This was fairly straight forward. I am a big fan of loops which I know will probably make me suffer in later challanges. I need to look more into optimizers and equation solvers.
3
u/Cyclotheme Dec 04 '23
[LANGUAGE: QuickBASIC]
Github link
3
u/Maravedis Dec 04 '23
[LANGUAGE: Clojure]
This felt like a day 1. Extract numbers, sum numbers.
Clojure day 4
3
u/YenyaKas Dec 04 '23 edited Dec 04 '23
[LANGUAGE: Perl]
Quite short and straightforward: Part1 Part2
It took me a while to re-read the task 2 and realize that the cards are duplicated in-place, instead prepending the just-won cards to the top of the card deck.
All my AoC solutions in Perl
3
u/rs10rs10 Dec 04 '23 edited Dec 04 '23
[LANGUAGE: Python 3]
Sets were king today.
ls = [[re.findall("\d+(?!\d*:)", l1.strip()) for l1 in l.split("|")] for l in open("2023/input/04.txt").readlines() ]### <----------------------- PART ONE -----------------------> ###S = [math.floor(2**(len(set(ws) & set(ns)) - 1)) for ws, ns in ls]print("PART ONE: ", sum(S))### <----------------------- PART TWO -----------------------> ###n = len(ls)C = np.array([1]*n)for i, (ws, ns) in enumerate(ls):C[i + 1:i + 1 + len(set(ws) & set(ns))] += C[i]print("PART TWO: ", sum(C))3
u/Symbroson Dec 04 '23 edited Dec 04 '23
[Language: Ruby]
almost golfed. how can I compress this further?There has to be a way to generate the cnt array in one line!
3
u/LinAGKar Dec 04 '23
[LANGUAGE: Rust]
My solution: https://github.com/LinAGKar/advent-of-code-2023-rust/blob/master/day4/src/main.rs
Simple enough, no need to parse the numbers. I figure I probably wouldn't gain any performance from a set instead of a vec with a collection this small.
3
u/Busata Dec 04 '23 edited Dec 05 '23
[LANGUAGE: Rust]
Trying to learn rust by participating here, pretty happy with today!
https://github.com/Busata/advent_of_code/blob/main/src/bin/2023_04.rs
3
u/rooneyyyy Dec 04 '23 edited Dec 04 '23
[LANGUAGE: Shell]
Part-2
3
u/joelheath24 Dec 04 '23
[LANGUAGE: C#]
C# One-liners
I pass my inputs in as raw strings, so to do it in one line you have to split on newlines twice for part 2, which is rathe unoptimal. Heres what they look like but storing the split input, and broken up to make them (somewhat) readable.
For more days pointlessly made into one-liners check out my GitHub
3
u/anatedu86 Dec 04 '23 edited Dec 04 '23
[LANGUAGE: Awk]
Idea:
In part 1, for every line
Iterate over winning numbers (column 3 to 12).
for(i=3;i<13;i++) { ... }Iterate over other numbers (column 14 to last).
for(k=14; k<=NF; k++) { ... }if($k==$i) { score++; }if(score>=0) { a+=2**score }(score is reset to -1 for each new line)In part 2, store the count of line (card) copies in an array.
lc[NR]+=1;(all cards have at least one copy)score, AND the copy count of the linen+scoreis bumped by the number of copies of the current line.if($k==$i) { score++; lc[NR+score]+=lc[NR]; }a+=lc[NR]Sol. Part 1:
Sol. Part 2:
3
u/InternetArgument-er Dec 04 '23
[LANGUAGE: C++]
Part 1 is just parsing again, get it and the task is done
Part 2 hinted a lot towards recursion + memorizing.
https://github.com/ANormalProgrammer/AdventOfCode/blob/main/2023/2023_day4.cpp
3
u/danvk Dec 04 '23
[LANGUAGE: Zig]
https://github.com/danvk/aoc2023/blob/main/src/day4.zig
I kind of like how you can use a mutable slice as an easy queue.
3
u/sansskill Dec 04 '23 edited Dec 04 '23
[LANGUAGE: Kotlin]
https://github.com/SansSkill/AdventOfKode2023/blob/main/src/main/kotlin/days/D04.kt
Was a rather easy day compared to yesterday
Edit: Reddit 'helpfully' changed the capitalization of the url, fixed it so it should work now
3
u/emiltb Dec 04 '23
[LANGUAGE: Python]
Quite happy with this solution, though I'm unsure whether the approach of creating and processing a queue is overkill and whether there is a smarter way: Source (topaz.github.io)
3
u/bubinha Dec 04 '23
[Language: Scala]
3
u/greycat70 Dec 04 '23
[LANGUAGE: tcl]
Part 1, part 2.
Finally, a proper first week puzzle! Put the winning numbers in a hash (array), then iterate over the second list of numbers and count how many are in the hash.
3
u/jamincan Dec 04 '23
[LANGUAGE: Rust]
https://github.com/jamincan/aoc2023/blob/main/src/day4.rs
I initially used
Hashsetto store the numbers, making it easy to find the intersection, but when I tested it against usingVec,Vecended up being significantly faster which makes sense given the few numbers to check.Pretty straightforward otherwise compared to dealing with the edge cases from Day 1 and 2.
3
u/hrunt Dec 04 '23
[LANGUAGE: Python]
Code
Today was the easiest yet. I didn't check to see if a number could be considered a winner more than once, but it doesn't look like that's the case. While Part 2 talks about making copies of the cards, all the solution really requires is knowing the number of copies of each card, so that's all I track.
3
u/waffles_and_boobies Dec 04 '23
[LANGUAGE: javascript]
Pretty straight-forward. Remembering how exponents actually work was a big time-saver in part 1.
Part 2 was easy once I stopped trying to actually materialize all the winnings.
paste
3
u/pem4224 Dec 04 '23
[LANGUAGE: Golang]
https://github.com/pemoreau/advent-of-code/blob/main/go/2023/04/day04.go
Quite simple today ;-)
3
u/petacreepers23 Dec 04 '23
[LANGUAGE: Nim]
Still learning Nim, any feedback is appreciated. Also is quite slow to run part 2.
https://github.com/petacreepers23/ADVENT2023/blob/master/day04.nim
3
u/tylersavery Dec 04 '23
[LANGUAGE: Dart]
Part 1 Part 2
3
u/Lindii98 Dec 04 '23
[LANGUAGE: Python]
The elf is reading the instructions as thoroughly as I read docs. Used Series and Sets to solve it
[Code]
3
u/bo-tato Dec 04 '23
[LANGUAGE: Common Lisp]
Part2:
full code: https://github.com/bo-tato/advent-of-code-2023/blob/main/day4/day4.lisp
3
u/jcmoyer Dec 04 '23
[LANGUAGE: Ada]
paste
Pretty typical AoC set problem.
3
u/calebegg Dec 04 '23
[LANGUAGE: TypeScript interpreted with Deno]
Part 1 ("one" liner): https://github.com/calebegg/adventofcode/blob/main/2023/4.1.ts
Part 2: https://github.com/calebegg/adventofcode/blob/main/2023/4.2.ts
3
u/_2bt Dec 04 '23 edited Dec 04 '23
[LANGUAGE: Python]
3
u/Lars-Kristian91 Dec 04 '23 edited Dec 04 '23
[LANGUAGE: C#]
Code: Github
Observations/Assumptions:
The input is read line by line. Everything before ':' is discarded and the rest is split up into 2 sections (win numbers and other numbers). Both sections are parsed and converted to u8 types so more data fits into SIMD registers. "win numbers" are checked against "other number" and score is calculated.
Today I had some troubles while making my code faster. I got similar results on my laptop and desktop. The standard deviation was also high (3-5 us) and I did not understand why. After much trial and error I discovered the 'modulo' operator created problems for me. When parsing the numbers I used
index % 3 == 2to detect if a number was done parsing. I changed it with a for loop and the time used was cut in half. :)I run benchmarks on 2 computers:
[search tag: ms]
Part 1
Part 2
3
u/Yazirro Dec 04 '23
[Language: Javascript]
https://gist.github.com/Yazir/013634809c5cbcc94d69b10fc1ab8f10
3
u/pdavisonreiber Dec 04 '23
[LANGUAGE: Python]
A Python one-liner:
3
u/huib_ Dec 04 '23 edited Dec 04 '23
[LANGUAGE: Python 3.12]
3
u/TheBali Dec 04 '23
[Language: Rust]
Day 4 of learning Rust. Oh boy that one is not pretty. A few times the compiler was like "hey you're missing a & or a * there" and I'm not sure why but I add it and it works. And I'm really not at ease with the HashMap functions, but I worked my way through them. I think it's a symptom of my code not being very idiomatic of Rust.
Also lost a fair bit of time because my hashmap that keeps track of how many times you have to process a card was initialized inside the line loop.
Clicky
3
u/Gprinziv Dec 04 '23 edited Dec 04 '23
[LANGUAGE: Python 3]
Did this one on a break at work. Probably could roll the parser and sanitizer into a nice, code-golfy single line, but I liked this method for its readability. Combined both parts took just under 40 minutes, and I just spent another 10 really cleaning it up.
The original version is here. Not significantly different, but clunkier.
3
u/Zorr0_ Dec 04 '23
[Language: Kotlin]
cheeky one expressions for part 1 and 2 :)
https://github.com/ckainz11/AdventOfCode2023/blob/main/src/main/kotlin/days/day04/Day4.kt
3
u/ProcessFree Dec 04 '23 edited Dec 04 '23
[Language: RUST]
here is the code :
https://github.com/ishqDehlvi/Advent-of-Code-2023/tree/main/Day-4
3
u/tuijnman Dec 04 '23
[LANGUAGE: Rust]
Solution for part 2 is pretty not-optimal... if I can find some time I'll likely rework it quite a bit
https://github.com/bastuijnman/adventofcode/blob/master/2023/04-12/src/main.rs
3
u/AverageBeef Dec 04 '23
[LANGUAGE: Rust]
I really expected part 2 to involve a queue, but it was more of an Advent of Reading Comprehension challenge for me today. AoC really makes you get familiar with iterators in Rust! Gist
3
u/Steinrikur Dec 04 '23
[Language: bash]
Spent more time trying to figure out why the input isn't handled in bash5 like bash4 did it. Now I have to set IFS to put my input into an array of lines, and then change it again to split my lines into tokens.
3
u/micod Dec 04 '23
[LANGUAGE: Common Lisp]
GitLab
3
u/zndflxtyh Dec 04 '23 edited Dec 04 '23
[LANGUAGE: Python]
This seemed easier than the first 3 days.
code - about 20 lines
3
u/sikief Dec 04 '23
[LANGUAGE: C++]
[PLATFORM: Nintendo DS (Lite)]
Solution - Part 1 and 2
3
u/Vesk123 Dec 04 '23
LANGUAGE: Rust
Overslept for today's puzzle, so I had to do it later in the day. Maybe that wasn't such a bad thing, as once the pressure of the leaderboards was off, I decided to write some cleaner code that I'm quite happy with.
3
u/jumpy_flamingo Dec 04 '23
[LANGUAGE: Lua]
https://github.com/pabloariasal/advent-of-code-2023-lua/blob/master/day4/solution.lua
3
u/toastedstapler Dec 04 '23
[language: rust]
~50us on my m1 & reasonably short, not too bad overall. first draft at solve was 1000x slower
3
u/thousandsongs Dec 04 '23 edited Dec 05 '23
[LANGUAGE: Haskell]
I used Parsec to parse, and the State monad to memoize. Here's the link to the full code on GitHub, some interesting bits are parser:
and the recursive win computation in the state monad:
The memoization still can be improved, but I haven't yet had the time to tinker with the code because I managed to distract myself into instead writing a blog post that outlines how the state monad can be used for (almost transparent) memoization in Haskell.
Here's the link to the blog post - if you're new to the State monad, you may find it useful. I'll see if I can also do a follow up post with newer memoization techniques I learn from the solutions some of you have posted!
3
u/Horsdudoc Dec 04 '23
[LANGUAGE: C++20]
cpp file on GitHub
This is my optimized solution. My first jot had defensive coding in part 1, keeping the all the cards in memory for part2.
Runs in about 2 ms
3
u/keithstellyes Dec 04 '23
[LANGUAGE: Common LISP] Nothing too exciting externally, but good practice for me to learn just a little more LISP :)
p1.lispp2.lispshared.lisp3
u/Per48edjes Dec 04 '23
[LANGUAGE: Haskell]
Day 4: Part 1, Part 2
TL;DR: Getting the hang of these monads! :burrito: Knew what I wanted to do, a lot of the friction came from fighting the compiler and not doubting myself (easier said than done!) or talking myself out of my strategy.
Felt like Part 1 was probably the easiest task to date?! Sure enough, Part 2 was the complication I've come to expect. Finding that functional programming makes things really easy to refactor or re-model as I'm [slowly] massaging a solution...which tracks with sentiments I've heard from other Haskell Rascals.
Part 2 called for keeping state, so reached for the
Statemonad, using aHashMapto keep state. Amazed how terse / expressive this language is to do something a little involved. Not sure this approach is any good, so someone, please do yell at me if there was a better functional approach!3
u/Afkadrian Dec 04 '23
[LANGUAGE: Rust]
https://github.com/adriandelgado/advent-of-code/blob/main/src/y2023/d04.rs
32 lines of code, standard library only.
Part 1 is allocation free.
Both parts are as branchless as possible. Sub 100 microseconds on my laptop.
3
u/Cheap_Squirrel_3871 Dec 04 '23
[LANGUAGE: JavaScript]
3
u/D3dd1 Dec 04 '23
[LANGUAGE: Java]
https://github.com/H4-MM-3R/Algorithms-in-Java/blob/main/AOC/2023/Day4/day4Part1.java
https://github.com/H4-MM-3R/Algorithms-in-Java/blob/main/AOC/2023/Day4/day4Part2.java
https://github.com/H4-MM-3R/Algorithms-in-Java/blob/main/AOC/2023/Day4/day4.md
3
u/rabuf Dec 04 '23
[LANGUAGE: Python]
This is a slightly tidied up version of what I had last night. I originally tracked the card numbers but since they weren't used I stripped that out as it cluttered things up. I moved the conversion of the number sequences to sets from the core functions to the parsing function.
That calculates the score for each card. Seems like most people did something similar. This is applied to each card and then summed in my
mainfunction.And that calculates the number of copies (starting at 1 each) there will be for each card. That also gets summed in my
mainfunction.3
u/codertee Dec 04 '23
[LANGUAGE: Python 3.12]
Counter was useful here: github
3
u/tsenart Dec 04 '23 edited Dec 04 '23
[LANGUAGE: Zig]
No heap allocations: https://github.com/tsenart/advent/blob/master/2023/4
Part 2 runs in 150 microseconds on my M1 mac.
3
u/efvincent Dec 04 '23 edited Dec 04 '23
[LANGUAGE: Haskell]
3
u/gil0mendes Dec 04 '23
[LANGUAGE: Rust]
GitHub
3
u/staticflow22 Dec 04 '23
[Language: Go]
https://github.com/Static-Flow/adventOfCode2023/tree/master/cmd/day4
Pretty happy with 500 µs! Curious if anyone got lower?
3
u/[deleted] Dec 04 '23
[LANGUAGE: Elixir]
Topaz link
Still don't really know what I'm doing with Elixir but coming along
3
u/iskypitts Dec 04 '23
[LANGUAGE: Zig]
Part 1 and Part 2
3
u/gigobyte Dec 04 '23
[LANGUAGE: Type-level TypeScript]
Solved using types only: solution
3
u/mantelisz Dec 04 '23
[LANGUAGE: Java]
Using streams and general good programming practices.
Both parts:
https://github.com/MantasVis/AdventOfCode/blob/master/src/advent/of/code/days/day4/Day4.java
3
u/NullT3rminated Dec 04 '23 edited Dec 05 '23
[LANGUAGE: Raku] (part 2 only)
[Allez Cuisine]
Properly golfed: wc -c gives 138 bytes.
3
u/[deleted] Dec 04 '23
[LANGUAGE: Scala]
(Part 1 Only)
code
3
u/i_have_no_biscuits Dec 04 '23
[LANGUAGE: GWBASIC]
Could have squished it into 5 lines but better to have it as a readable 7 lines.
3
u/doodlebug80085 Dec 04 '23
[LANGUAGE: Swift]
I'm like, dropping hints that Swift has really nice higher-order functions.
CODE
3
u/The_BNut Dec 04 '23 edited Dec 04 '23
[LANGUAGE: Kotlin]
3
u/Superbank78 Dec 04 '23
[LANGUAGE: rust]
rust btw. My first rust program. Recursive, yeah! But otherwise probably ugly
https://gist.github.com/Dronakurl/fdf0c65805013084a89bc30d295a959f
3
u/loquian Dec 04 '23 edited Dec 04 '23
[LANGUAGE: C++]
github, 1148 microseconds (both parts together)
std::transformis cool.3
u/Regex22 Dec 04 '23
[Language: Rust]
3
u/atobiedwa Dec 04 '23
[Language: Python]
Day_4 : https://github.com/monpie3/adventOfCode2023/blob/master/Day_4
3
u/oatmeal_andy Dec 05 '23
[LANGUAGE: Python]
paste
Pretty straight forward application of dynamic programming.
3
u/tcbrindle Dec 05 '23
[LANGUAGE: C++]
Github
3
u/nicenic Dec 05 '23
[LANGUAGE: Powershell] Part 1
Part2
3
u/marcja Dec 05 '23 edited Dec 05 '23
[LANGUAGE: Python]
If anyone is wondering about the curious
1 << wins >> 1construction, it arose when I couldn't immediately get2 ^ (wins - 1)to give me the right value. "Don't like my power function? Fine, I'll bit-shift..."Then I remembered later that
x ^ y != x ** yin Python... <sigh>3
u/NotTreeFiddy Dec 05 '23 edited Dec 05 '23
[LANGUAGE: Rust]
Late as always (actually a day late by UK time).
My solution to this one runs slow, but it gets the job done. I didn't actually need the CardInfo struct by the time I was done, but couldn't be bothered to remove it. Previously, it held more than just count.
Day 04 in Rust 🦀
View formatted on GitLab
Edit: Removed oversized code
3
u/Tipa16384 Dec 05 '23
[LANGUAGE: Haskell]
I was going to give up on trying this in Haskell -- yesterday I did it in Python, and this morning before work I did part 1 in Java -- but I'm back.
3
u/blueg3 Dec 05 '23
[Language: Python]
[Allez cuisine!]
Part 1, Python "one-liner":
3
u/sm_greato Dec 05 '23 edited Dec 06 '23
[LANGUAGE: Rust]
Noticed that all numbers are less than 100 and that there are no repeats. And Rust actually provides a 128 bit integer type, so I thought why not encode the bars in integers, and then use binary & to figure out the intersection. Then we can simply count the number of ones to find the number of winning values. You can find it here. Below is a snippet.
3
u/Zealot_TKO Dec 05 '23
[LANGUAGE: Python}
link
3
u/aleks31414 Dec 05 '23
[LANGUAGE: rust]
Puzzle 1
Puzzle 2
3
u/pzicoalex Dec 05 '23
[LANGUAGE: Python]
Sooo, I am very new to programming, and pretty bad. This works though, somehow. Runtime on part 2 is about 7 seconds :)
Part 1
Part 2
3
u/bamless Dec 06 '23 edited Dec 06 '23
[LANGUAGE: J*]
Part 2 was really fun! Happy to finally see some dynamic programming!
part 1
part 2: similar to above, but with dynamic programming to compute the total number of ticket won
3
u/ethansilver Dec 06 '23 edited Dec 12 '23
[LANGUAGE: FORTRAN]
Learn Fortran!
https://github.com/ejrsilver/adventofcode/blob/master/2023/04/main.f08
3
u/e_blake Dec 07 '23
[LANGUAGE: m4 (golfed GNU)] [Allez Cuisine!]
Here, in 385 bytes, is my golfed offering that fits in a punchcard. 4 of the 5 newlines are optional, but can you tell which one is essential? Won't work if you strip the final newline out of your input file. The name of macro
Cis hard-coded by the input file, all other macro names are somewhat arbitrary. Run bym4 -DI=filename day04.golfm4. Requires GNU m4 (things likedefn(define)orpopdef(X,.)are GNU extensions). Executes in about ~50ms, with just one pass over the input file.Uses my more-legible (hah, if you think m4 is legible!) day04.m4 solution as its starting point, although that version also depends on my helper macros in common.m4.
3
u/Virus_RPi Dec 07 '23 edited Dec 08 '23
[LANGUAGE: Python]
I am currently trying to only write one line of python code for each part of this year advent of code.
Part 1:
Part 2:
3
u/distracted_sputnick Dec 08 '23
[LANGUAGE: Rust/Uiua]
Wanted to come back to this one and give it a go in Uiua and finally got to to it today. A third of the code is just spent on parsing, but once we have arrays life is expectedly good.
Indecipherable code on UiuaPad (emojis 'coz I could)
Much better commented version here
After the text is parsed into two tables:
3
u/bofstein Dec 09 '23
[LANGUAGE: Google Sheets]
https://docs.google.com/spreadsheets/d/17ksEDNktiYB8Q0af4au5I8Ok7qa8MZRkDPXGEQys17M/edit#gid=0
Part 1 was straightforward, not even different numbers of potential winners on each card to make it hard to use cell references. Just count how many instances of the winning numbers are in the card set, add it up, then do a modified 2^ that number formula and add those. Originally I did it with a bunch of formulas, then went back and cleaned it up moving them to ARRAYFORMULAs since that's a lot better and I need to learn how to do that.
Check winners on each card: =ARRAYFORMULA(SUM(COUNTIF(R2:AP2,G2:P2)))
Add up the points from all cards:
=ARRAYFORMULA(SUM(FLOOR(2^(B2:B202-1),1)))
Part 2 I did in a really inefficient way initially where I have a column for each round, where a round is that card's winning propagating to the others, then repeat that for each card.
=IF(ROW(C2)<E$1+2,D2,IF(AND($A2<INDIRECT("C"&(E$1+1))+1,$A2>INDIRECT("A"&E$1+1)),D2+INDIRECT(SUBSTITUTE(ADDRESS(1,COLUMN(E$1),4),"1","")&E$1+1),D2))
It worked, but there's a much simpler way after talking with others of figuring out for each card how many of the cards above it would have added to it, and adding their card amounts if so, so it can be done in one column instead.
=1+IF(B11>0,D11,0)+IF(B10>1,D10,0)+IF(B9>2,D9,0)+IF(B8>3,D8,0)+IF(B7>4,D7,0)+IF(B6>5,D6,0)+IF(B5>6,D5,0)+IF(B4>7,D4,0)+IF(B3>8,D3,0)+IF(B2>9,D2,0) (edited)
3
u/floflo455 Dec 11 '23
[LANGUAGE: Python]
Both parts in TDD
The second part is a bit slow and took 7 seconds on my laptop.
4
u/Radiadorineitor Dec 04 '23 edited Dec 04 '23
[LANGUAGE: Dyalog APL]
4
u/trllnd Dec 04 '23
[LANGUAGE: Python]
2
u/Boojum Dec 04 '23 edited Dec 04 '23
[LANGUAGE: Python3] [Allez Cuisine!] 551/600
A nice and straightforward puzzle today, with a some set intersection for both parts, and a little dynamic programming for Part 2:
Edit: Code-golfed to a bit under (70x5) "punchcard" size for Allez Cuisine:
This prints a running sum. The final results are on the last line.
2
u/GiraffeFire Dec 04 '23 edited Dec 04 '23
[LANGUAGE: Elixir] 2773/3348
paste
Part 1 was relatively simple, although I initially didn't account for multiple spaces between the card number and the first called number.
During part 2, I was really scared that I'd have to memoize because it felt exactly like a Fibonacci problem. Really grateful that it managed to run fairly quickly.
2
u/Shot_Conflict4589 Dec 04 '23
[LANGUAGE: Swift]
code
I should start reading the problem description properly again.
I went for adding up all results in the second part instead of just calculating how many cards there are in the end.
2
u/Prof_McBurney Dec 04 '23 edited Dec 04 '23
[LANGUAGE: Kotlin]
[Pretty happy with the cleanliness of the code](https://github.com/Will-McBurney/AOC-2023/blob/master/src/main/kotlin/year23/day4/Main.kt), but it feels like the difficulty is all over the place right now.
Kotlin can give you some really nice looking stuff, and I'm really falling in love with all of the standard library functional stuff:
Not the best example, I know, but it's quite nifty imo
2
u/xoronth Dec 04 '23
[LANGUAGE: Python]
paste.
Today wasn't too bad. I'll be honest though, my first instinct in part 2 was "how bad could it be if you checked every card one by one", then the rest of my brain kicked in, remembered the lanternfish from 2021, and I realized you could just multiply the number of cards you have at the moment to determine how many additional cards to add.
2
u/wace001 Dec 04 '23
[Language: Kotlin] 1655 / 1630
Fun today!
Code
2
u/Valletta6789 Dec 04 '23 edited Dec 04 '23
[LANGUAGE: Python]
Here is mine approach:
For part2, using extra dict to store num of copies:
https://github.com/Aigul9/AdventOfCode/blob/master/year2023/Day_04/main.py
2
u/simpleauthority Dec 04 '23 edited Dec 06 '23
[LANGUAGE: Java]
Nice and easy day today.
However, my part 2 is kind of slow. I'd like to fix that. Might edit later.Made it faster.Faster solution: Link to GitHub
2
u/s3aker Dec 04 '23
[LANGUAGE: Raku]
solution
2
u/ranikola Dec 04 '23 edited Dec 04 '23
[Language: JavaScript] Code
Simple and clean, I hope...
2
u/Traditional-Salt-737 Dec 04 '23 edited Dec 04 '23
[Language: Python golf]
188 bytes
2
u/[deleted] Dec 04 '23
[Language: Elixir]
paste
Parsing was much easier today, and the logic was also easier. This problem is nice for functional languages, and having built in functions to do Maps and reduces made it nice and easy.
For Part 1 the only insight I got was that for the score you could just do 2 to the power of the number of winning numbers minus 1 (2^(n-1)) as long as n isn't 0. Other than that, pretty straight forward.
For Part 2, I was thinking of doing a recursive solution, but I was worried about the performance on body recursive solutions, so using for comprehensions I implemented an iterative solution to add the current number of cards of that number to the successive wins. Which was conceptually similar and more performant than a naive body recursive solution.
2
u/Wrenky Dec 04 '23
[LANGUAGE: Go]
github here. I'm enjoying samber/lo a bunch for the functional primitives, but does anybody know the correct functional pattern for dealing with a map like part2? This might be one of those cases where go just isn't a great language for functional stuff.
2
u/knl_ Dec 04 '23
[LANGUAGE: Hy]
Spent way too long understanding what the puzzle was asking; I initially misread part 2 as saying that the matched numbers were the cards that were duplicated, not simply the next X cards.
Went back and refactored my solutions to use the `parsy` library to use parser-combinators instead of repeatedly splitting strings, which was satisfying.
https://github.com/kunalb/AoC2023/blob/main/aoc/day04.hy
2
u/JSdoubleL Dec 04 '23
[LANGUAGE: Python 3]
2
u/xavdid Dec 04 '23
[LANGUAGE: Python]
Step-by-step explanation: https://advent-of-code.xavd.id/writeups/2023/day/4/
This felt like a simpler day again. Do some parsing to build sets of numbers and winning numbers (useful for both parts).
For part 1, I added
2 ** (num_winners - 1)to a running total.For part 2, I kept a
dictof how many copies of each card there were. For each winner, I'd increment the subsequent cards by the number of copies of this card, which took care of the "compounding interest".This felt more in line with a day 4. But like Topaz has said, puzzle difficulty is hard!
2
u/AlexTelon Dec 04 '23
[LANGUAGE: python] [ALLEZ CUISINE!]
I have two solutions for the all important punchcard challenge!
part1 that fits on 5 lines of 80 cols each:
part2 that fits on 5 lines of 80 cols each:
2
u/Upbeat_Spite_9674 Dec 04 '23
[LANGUAGE: Python3]
This is my punchcard fitted code, can be golfed more but then some lines are longer than 80 characters. (Only works for part 2)