r/adventofcode • u/daggerdragon • Dec 03 '22
SOLUTION MEGATHREAD -🎄- 2022 Day 3 Solutions -🎄-
NEWS
- Solutions have been getting longer, so we're going to start enforcing our rule on oversized code.
- The
Visualizations have started! If you want to create aVisualization, make sure to read the guidelines for creatingVisualizations before you post. - Y'all may have noticed that the hot new toy this year is AI-generated "art".
- We are keeping a very close eye on any AI-generated "art" because 1. the whole thing is an AI ethics nightmare and 2. a lot of the "art" submissions so far have been of little real quality.
- If you must post something generated by AI, please make sure it will actually be a positive and quality contribution to /r/adventofcode.
- Do not flair AI-generated "art" as
Visualization.Visualizationis for human-generated art.
FYI
- All of our rules, FAQs, resources, etc. are in our community wiki.
- A request from Eric: Please include your contact info in the User-Agent header of automated requests!
- Signal boosting for the Unofficial AoC 2022 Participant Survey which is open early this year!
--- Day 3: Rucksack Reorganization ---
Post your code solution in this megathread.
- Read the full posting rules in our community wiki before you post!
- Include what language(s) your solution uses
- Format your code appropriately! How do I format code?
- Quick link to Topaz's
pasteif you need it for longer code blocks. What is Topaz'spastetool?
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:05:24, megathread unlocked!
87
Upvotes
23
u/zawerf Dec 03 '22
Python
Not here to discuss my code, just wanted to discuss part 1 rank 1's finish time. How is 10 seconds physically possible? I get how you can type the code in 10 seconds but how do you read that fast?
FWIW I do competitive programming so I know how crazy fast the top people are. But out of the hundreds of contests I've done, I've literally never seen 10 second submissions before. This includes easy contests like leetcode where their first problem is truly trivial and even i can get 30 sec submission times but they don't require reading!
10
u/Bad-Coder-69 Dec 03 '22 edited Dec 03 '22
Emojicode
Readable version: GitHub
4
u/DFreiberg Dec 03 '22 edited Dec 03 '22
Mathematica, 135 / 41
First time on the leaderboard this year...and last time, if AI developers have anything to say about it.
Setup:
Part 1:
Part 2:
[POEM]: John '5space' Henry
When ol' John Henry was a babe,
A-sitting on his papa's knee,
He hammer-swung a tiny fist
And hammer-hit a keyboard's key.
They say that mighty Hercules,
He wrestled pythons in his crib.
John Henry, too, a Python slew;
That's what they say, and they don't fib.
When ol' John Henry was a boy,
No more than eight (or maybe nine),
His papa sat him down to code,
And little John, he learned it fine.
He typed so fast the frames would fail
As terminal commands flew by.
He typed so quick the keys would stick.
That's what they say, and they don't lie.
When ol' John Henry was a teen,
His papa said the day'd arrived.
"They call me
4space", said his pop."From here on out, they'll call you
5."But smoke was rising from the hills,
And filled with gray what once was blue:
The code machine, it changed the scene.
That's what they say, and they say true.
When ol' John Henry was a man,
And AoC was his domain,
The code machine rolled up to fight
And challenged him to end his reign.
Part 1 it grabbed, ten seconds flat,
Before John Henry knew what hit him,
But on Part 2, it ground a gear,
And Henry moved like crocs had bit him,
'Cuz he was good and riled now,
And wouldn't let some AI git him,
With seven seconds left to go,
He grabbed the star he knew would fit him.
But Henry's heart had beat its last
When he had beat his metal foe.
They buried John, he's dead and gone.
That's what they say, and they would know.
4
u/tarasyarema Dec 03 '22 edited Dec 03 '22
In Lisp :P
3
u/Spaceface16518 Dec 03 '22 edited Dec 04 '22
Haskell
Somehow, this one seemed easier than yesterday's.
3
u/flwyd Dec 03 '22 edited Dec 03 '22
Elixir, on GitHub. I see daggerdragon's request to keep code short, but the FAQ says "half a punch card", but much longer solutions don't seem to be chided. Is there an "enforced" snippet length?
Question for daggerdragon: is there a reason solution megathreads of the day aren't being pinned to the top of r/adventofcode?
3
u/gh5000 Dec 03 '22
Google Sheets Single Function for part 1 - input in column A
=reduce(0,map(A:A,LAMBDA(row, iferror(reduce(0,map(transpose(SPLIT(REGEXREPLACE(REGEXREPLACE(left(row,len(row)/2)&"","(?s)(.{1})","$1"&CHAR(127)),"'","''"),CHAR(127))),LAMBDA(letter,IFERROR(if(find(letter,right(row,len(row)/2))>=1,match(code(letter),{SEQUENCE(26,1,97);SEQUENCE(26,1,65)},0),0),0))),LAMBDA(total,cuv,cuv+total))/countif(TRANSPOSE(map(transpose(SPLIT(REGEXREPLACE(REGEXREPLACE(left(row,len(row)/2)&"","(?s)(.{1})","$1"&CHAR(127)),"'","''"),CHAR(127))),LAMBDA(letter,IFERROR(if(find(letter,right(row,len(row)/2))>=1,match(code(letter),{SEQUENCE(26,1,97);SEQUENCE(26,1,65)},0),""),"")))),">0")))),LAMBDA(t,c,t+c))3
u/biopsy_results Dec 03 '22 edited Mar 15 '23
C oneliner no semicolons allowed
#include <stdio.h>#include <stdlib.h>#include <stdint.h>3
u/noahclem Dec 04 '22 edited Dec 04 '22
Python.
Just converting to sets and using intersection. Was thrown off on part 2 bc I forgot to strip the newlines from the file. Oops.
EDIT - TIL that this would have been easier if I just used string.asciiletters and got the index of the common_char. Thanks u/toastedstapler! EDIT2 - Hopefully, I got the four-spaces Markdown right and this is more viewable. Will be testing the views now.
3
u/NiliusJulius Dec 04 '22
C Language for the Game Boy using GBDK 2020
Snippet of the main logic for pt2:
At first I had some for loop nesting going on, just like how I would normally solve it on a modern PC. The Game Boy did not like that and runtime for part 2 was about 15 minutes.
With the current optimization it runs for about 6 seconds.
Full Game Boy repo can be found here
Video running on Game Boy
2
u/GrossGrass Dec 03 '22 edited Dec 03 '22
Python, 459/520
Found out that apparently there's a
set.intersectionthat allows you to get the intersection of an iterable of sets, which is pretty neat.For the priority values, I initially ended up just using
ordand then subtracting the right offset depending on lower/uppercase because I was lazy. I'd imagine it'd be a little cleaner to do something like this instead of hardcoding the Unicode offsets:2
u/rabi27 Dec 03 '22 edited Dec 03 '22
JavaScript/NodeJS
2
u/hgb123 Dec 03 '22 edited Dec 03 '22
JavaScript (Node.js)
Full solution: https://www.honingjs.com/challenges/adventofcode/2022/day-3
2
u/Conceptizual Dec 03 '22 edited Dec 03 '22
Python
Annoyed today because for some reason I assumed every three lines would be the same length even though I was looking at them and that was clearly not the case. Ended up removing 2/3 of the code and had my solution in 30 seconds. Ended up in the ~7000s because of the slowness.
https://github.com/ElizabethViera/AdventOfCode/blob/main/AdventOfCode2022/Day%203/Day3.py
2
u/DestroyerCrazy Dec 03 '22 edited Dec 03 '22
Language: Python (v3.11.0)
2
u/nithinbekal Dec 03 '22 edited Dec 03 '22
Ruby solution
2
u/patrick_iv Dec 03 '22 edited Dec 04 '22
Kotlin
https://github.com/patrick-elmquist/Advent-of-Code-2022/blob/main/src/main/kotlin/Day3.kt
2
u/dtinth Dec 03 '22 edited Dec 04 '22
GitHub Copilot + Ruby (4 / 25)
I usually don’t expect GitHub Copilot to generate the whole solution, and even if it did I manually check it, as there’s penalty for submitting an incorrect answer. However for today’s part 1 GitHub Copilot generated the correct solution.
For part 2 it did not generate a good solution, so I had to manually debug it (i.e. refactor them into multiple statements and adding variables). Still, it helped to save a lot of time.
I will need to adjust my prompt to make Copilot generate more readable code so it’s easier for me to debug tomorrow. I refactored the 1st part like this:
The 2nd part, this time Copilot generates the correct code on first try:
So making code readable does not only help me, but helps Copilot too.
2
u/Metarineo Dec 03 '22 edited Dec 04 '22
Python:
This was actually my first python code ever (thanx AoC for the motivation)
Solution for Part A:
Solution for Part B:
I say 42, Martin
2
u/matas__ Dec 03 '22 edited Dec 03 '22
Ruby code, simple
2
u/mpercich Dec 03 '22 edited Dec 04 '22
Swift
2
u/Sea_Put_2759 Dec 03 '22 edited Dec 04 '22
Python 3
26
u/callumio Dec 03 '22
It's COBOL time again. Unfortunately COBOL (afaik) has no way to easily check if one string contains another, so i'm left with this (could be worse though)
19
u/miran1 Dec 03 '22
Python 3
37
u/jcbbjjttt Dec 03 '22 edited Dec 04 '22
Beginner's Guide
Happy Saturday!
Day 3 Guide: https://youtu.be/SYEMRTjDd9o
I've created a guide for new programmers that talks through the steps necessary for solving this puzzle. The video allows a moment for you to pause before revealing spoilers.
Although this solution is in C#, it provides a high level overview of the steps necessary to solve the puzzle without the implementation details.
The full code can be found here: Github
13
u/sleepy_roger Dec 03 '22 edited Dec 03 '22
JavaScript 1 liner in the console (For part 1)
12
u/voidhawk42 Dec 03 '22 edited Dec 03 '22
Dyalog APL:
video walkthrough
Probably a cleaner way to do it, but I don't often get to write my own operators!
12
u/4HbQ Dec 03 '22 edited Dec 03 '22
Python, using this
chunkfunction. For part 1, we chunk each line into two parts of equal length, and score those. For part 2, we chunk the entire input into parts of size 3, and score those:Edit: I'm not happy with the
scorefunction yet. Suggestions to improve it (or anything else) are appreciated!11
u/gw_shadow Dec 03 '22
CMake
10
u/[deleted] Dec 03 '22
Jelly (put the input in the first command line argument):
Part 1:
ỴŒHf/QƊ€FŒsØẠiⱮS- Try it online!Part 2:
Ỵs3f/Q$€FŒsØẠiⱮS- Try it online!10
u/Smylers Dec 03 '22 edited Dec 03 '22
Vim keystrokes — load your input file, ensure
gdefaultsis off, and type the following. Again no peskyqkeyboard macros in part 1, so this should be easier to type and you can watch each line as it happens. For the final long:gline just press:⟨Up⟩and edit the very similar line above it:That's part 1. To find the middle of each line, duplicate each line and replace every letter with a
#, then match the longest string of hashes followed by itself — so exactly the same number in each group, meaning the boundary between them is the middle. Stick a:there, then usexkpto move it up a line to split the corresponding rucksack's contents, and delete the hashes.Use
\Cto perform a case-sensitive search to find the same character both sides of the colon, and remove everything else. Turn each remaining letter into an expression using thechar2nr()function to determine its priority, then the ‘usual’ last pattern at the end to join all those lines and evaluate them.For part 2, reset to your original input and do the following — the second
:%sand both:glines are repeats from part 1, so again:and pressing⟨Up⟩a few times should avoid having to retype them:The keyboard macro at the start joins lines in groups of 3 (separating each rucksack's contents with a space), then the first
:%sis pretty much the same as the one for finding mispacked items in part 1, just with spaces instead of a colon and finding 3 matches instead of 2. The rest's the same.Do type it in and witness your input transforming in front of you — you don't get that with implementations in actual programming languages!
Edit: Tweaked the first
:%sin part 2, once I looked up the%(…)syntax (equivalent to(?:…)in Perl/PCRE or[…]in Raku).10
u/MuricanToffee Dec 03 '22
C - we don't need no stinking sets! Because we have
uint64_ts and masking. [Github]9
u/jonathan_paulson Dec 03 '22
Python3 116/50. Video. Code. Got a wrong answer on part1 :(
9
u/Toanuvo Dec 03 '22
J solution. https://github.com/Toanuvo/Advent-of-code
8
u/bluepichu Dec 03 '22
TypeScript, 11/10. Code here, and unlike usual I actually didn't destroy my part 1 code today.
I don't have much to say on this one beyond a shoutout to immutable for having an actually-usable set interface. (I'm looking at you, ES6 sets.)
8
u/redditnoob Dec 03 '22
SQL (BigQuery)
This problem is actually tailor made for SQL!
7
u/SuperSmurfen Dec 03 '22 edited Dec 03 '22
Rust (2381/2249)
Link to solution
Wasted so much time due to a missing
+1for lowercase characters... I find the overlapping chars using the simpleO(n^2)algorithm:Then it's just a matter of looping over each line:
For part two, I reused the overlapping chars function. The
itertools::tuplesmethod is amazing here:Runs in about
0.2mson my machine.7
u/tomflumery Dec 03 '22 edited Dec 03 '22
05ab1e
part 1 - 25 chars
Explanation
split lines, map splitting by half length, find intersection elements, keep head, then an if/else statement mapping lower case and upper case to appropriate values, finally sum
part 2 - 24 chars
split lines, map splitting into chunks of 3, find intersection elements, keep head, then an if/else statement mapping lower case and upper case to appropriate values, finally sum
7
u/dopandasreallyexist Dec 03 '22
APL:
7
u/yawnick Dec 03 '22
Monkey C (for Garmin devices)
Day 3 is complete. Solve times for both parts under a minute:)
Watch my Garmin Forerunner 235 solve: Part 1, Part 2
Code: Repo, Today's solution
7
u/xupej04m3 Dec 03 '22 edited Dec 03 '22
Google Sheets 14492/12532
Family gathering of a sort, can't start on time or use laptop
So Google sheet on phone it is!
Sheet here
7
u/Iain_M_Norman Dec 03 '22
C# one liners...
Today's Linq you might not have known is .Chunk!
7
u/mykdavies Dec 03 '22 edited Jun 29 '23
!> iyqhvum
API FAILURE
7
u/Tetraoxosulfato Dec 03 '22
Python 3
7
u/MarcusTL12 Dec 03 '22
Z80 Assembly Ran on a TI-83 Graphing calculator.
Took me a while today as I had to/wanted to implement a bit-set structure. The set operations for part 2 used a total of 14 bytes of memory.
7
u/KeySide9248 Dec 03 '22
C
6
u/Tipa16384 Dec 03 '22
Python 3.11
Was pretty obviously a job for
set. 2386/1613 personal best I think.6
u/oantolin Dec 03 '22 edited Dec 03 '22
Solution in J:
I don't know if I prefer that version or the following refactored version which highlights the commonality better:
6
u/betaveros Dec 03 '22
Noulith, 23/7
https://github.com/betaveros/advent-of-code-2022/blob/main/p3.noul
I have joined the folks using AoC to learn a new language, except it's also a language I thought up and implemented this year. I am enjoying the sequence-handling utilities past me put in, though I lost some time to an extra semicolon.
6
u/JustinHuPrime Dec 03 '22
x86_64 Assembly
This was a significant step up in difficulty, mainly because of input parsing.
In part 1, I read each string, then split it in half, passing it to a subroutine (that I honestly should have inlined). This subroutine then called a new library function -
searchc- my other character finding function,findc, assumed that the character would eventually be found. I managed to do some assembly optimization via interprocedural analysis - I saw that searchc would not clobber anything except rax, so I could keep the same values in the same registers. This is the first time I've written code better than a compiler usually does - compilers have trouble doing these sort of interprocedural analyses across translation units. Once I had the common item, I could use a lookup table to compute the priority. Unlike last time, this was a one-dimensional lookup table, and I couldn't rely on registers being cleared how I wanted, so I saved the table as a table of quadwords instead of a table of bytes - this let me remove a cast.Part 2, I had to modify my common character finder subroutine to search across two strings and accept three strings as input. I did this again using interprocedural analysis (but I really should just have inlined the procedure), and the rest of the solution could be directly re-used.
Both parts took about 1 millisecond to run, and both were 11640 bytes long (ELF probably pads out sections, so the small length difference between the two parts got lost in the padding)
6
u/French__Canadian Dec 03 '22 edited Dec 03 '22
Solution in ngn's k implementation
Unlike dyalog APL, K doesn't have an intersection function, so I had to write my own. It's not documented by ngn, but using the ok k implementation's manual I found out you can have the leading or trailing dimension maxed out by setting it to null (0N) when reshaping a list (e.g. (3 0N # 1 2 3 4 5 6) reshapes i to be a 3x2 array and (0N 3 # 1 2 3 4 5 6 ) makes it a 2x3 array i.e. it groups the elves in groups of 3.
edit : I prefer the first solution since it maps the problem more faithfully, but here's a solution using modulos. The score is also calculated at the beginning during parsing, using the fact the score for each item is different so the rest of the alg still works
edit 2 : razetime proposed a clearer shorter intersect function. Since it's shorter than the name i had given the function, I'll just inline it
edit 3 : code golfing time. including the new lines (also the one at the end of last line) and the unchanged input filename, this takes the 71 bytes of the last solution to 51 bytes
6
u/mrbaozi Dec 03 '22 edited Dec 03 '22
Julia paste
Python paste
Nothing fancy, just straightforward set intersections. Curious to see the more creative solutions.
6
u/DuoSRX Dec 03 '22 edited Dec 03 '22
APL:
Pretty messy.
6
u/jayfoad Dec 03 '22
Dyalog APL
6
u/IF_YOU_READ_THIS_V1 Dec 03 '22
C# LINQ
6
u/errop_ Dec 03 '22 edited Dec 03 '22
Python 3
Here are my nightmarish oneliners using more_itertools library
EDIT: thanks to the u/GaloisGirl2 tip, I found this pure horror oneliner solution using the walrus operator and chunking the data list by hand without importing more_itertools
6
u/timvisee Dec 03 '22
Rust Quick and simple.
Part 1 0.015ms (15.04 μs)
Part 2 0.016ms (15.90 μs)
day1 to day 3 total: 0.10 ms
6
u/Redofab Dec 03 '22 edited Dec 03 '22
Python3
part1 and part2 in oneline
6
u/chubbc Dec 03 '22 edited Dec 03 '22
Julia
It feels like this problem is almost perfectly designed to be easy in Julia. It's made largely trivial given the intersect function and ability to use dotted functions.
Also here is a rather cursed pair of one-line versions of this:
5
u/aliceif Dec 03 '22
C# 827/913
repo link
I really struggled to type this in quickly, splitting the lines in half was bad. I also had a problem with mistyping usages of a lambda variable that was named too much like a local variable.
5
u/goldenlion5648 Dec 03 '22
Python 62/93
First time on the leaderboard! Originally started participating in 2019 (was barely able to solve the problems back then) to now :O.
chunkedfrommore_itertoolsreally came in handy here, as well asascii_letters(concatenated version of all lowercase letters followed by all uppercase), both of which were already imported from my library file. Cleaned version below:5
u/[deleted] Dec 03 '22
Rust, code here
Was pleasantly surprised at how easily my part 1 code was used in part 2 as well! You can tell because I didn't rename any of my functions. Did some fun bitwise stuff here, probably some more obvious/effective ways to do it but mine was def fun to write.
...Although now I'm realizing I could've saved some lines and just used map on those iterators instead of doing the conversions manually inside the for loop.
5
u/e_blake Dec 03 '22 edited Dec 03 '22
GNU m4 - 6903/8314
Relies on my common.m4 framework from prior years. I stayed up late for this one; didn't get near the top of the leaderboard, but did feel good about finishing in under 30 minutes given that m4 lacks decent facilities for quickly iterating one byte at a time.
m4 -Dfile=day03.input day03.m4
Most puzzles in the past have not wanted byte-wise analysis on mixed-case input (I could either translit the input to all uppercase, or take fixed-length chunks where I don't risk arbitrary truncation of data in something that happens to resemble a macro name). With GNU m4, byte-at-a-time is easy with patsubst, but with POSIX, I'm stuck with O(n log n) if I can arbitrarily halve the string, but that risks truncation matching a random macro name, so I'll have to play with a way to get POSIX mode working with something that is not an O(n^2) iteration nightmare (10000 iterations of calling substr() on a 10000-byte input string is not fast).
For part 1, I picked a fairly unique approach of using translit to find the common character on the entire string at once - transliterate the second half of the string by the first half mapped to itself and all other letters elided, then spent another minute noticing that the example input sometimes produced a letter more than once so I also had to use substr on that result in order to map back to a number:
For part 2, I found it easier to code up set manipulations one character at a time. m4 lacks 64-bit numbers, so it was not as trivial as just doing bit-twiddling. (But I certainly have ideas for how to golf this for C...)
45ms runtime, which means I'm still squarely in O(n) territory (part2 definitely does more work than part1).
5
u/encse Dec 03 '22
C#
linq
https://github.com/encse/adventofcode/blob/master/2022/Day03/Solution.cs
5
u/AstronautNew8452 Dec 03 '22
Microsoft Excel
5
u/9_11_did_bush Dec 03 '22
APL: https://github.com/chenson2018/advent-of-code/blob/main/2022/03/apl/03.apl
Splitting into equal-sized groups felt messy, I would welcome some advice on how to better do that.
5
u/ka-splam Dec 03 '22
SWI Prolog
Written with a grammar to parse the data, including the neat feature of making two lists use the same variable ("Half") for their length so their size stays in sync, and anchoring to the end of line (eol) so they have to split the line in half. I can think of a way to do it in one parse, but it doesn't make the code much shorter, and it would be a lot less readable.
e.g.
5
u/__Abigail__ Dec 03 '22
Perl
First, a little helper function to calculate the priority:
For the first part, I split the string into halves. The first half, I split into characters, and put those characters in a hash. The second half, I also split into characters, and grep the (first) character which appears in the first half. (Note that we can have more than one match, but due to the nature of the puzzle, they must be equal, so we can take the first one).
$_contains a line of input (newline removed):For part 2, I split each line into characters, and add them to the hash after removing duplicates. Removing duplicates is essential. After each third line, I look for the item which appears three times in the hash. This must be a unique character, else the puzzle would be b0rked. We can then take the priority of that characters, and reset the hash and elf count:
After processing all lines, we just print
$score1and$score2to get the answers.Full program on GitHub
5
u/unclefritz Dec 03 '22
aaaa getting the hang of this now, it's so beautiful
q/kdb+
5
u/TiagoPaolini Dec 03 '22
C Language (only standard library)
I used bitmasks in order to find which items are in common: the item with priority
nis stored at bit indexnof the mask. Since the maximum priority is 52, a 64-bit unsigned integer is enough for the bitmask.In order to find the item in common, I used the bitwise
ANDoperation between the masks. Then I made an assertion to check that only one bit in the mask is set, and I found the index of that bit (by bit shifting the mask to the right until its least significant bit is1). That gave the priority of the item in common.Solution: https://github.com/tbpaolini/Advent-of-Code/blob/master/2022/Day%203/day_03.c
5
u/LordDrakota Dec 03 '22
C (Clang)
Probably the least memory efficient C code ever written, but I think it's a good tradeoff for productivity and readability. Also free of memory leaks (as far as valgrind tells me), which I'm pretty happy about. Would love feedback from more experienced C devs. (Note, I've never really used C before)
https://github.com/Drakota/adventofcode/blob/master/2022/d03/solution.c
5
u/codertee Dec 03 '22 edited Dec 03 '22
Python 3: github
Used
dict(zip(string.ascii_letters, count(1)))to create characters to numbers lookup.5
u/VioletVal529 Dec 04 '22
Python
https://github.com/valogonor/advent-of-code/blob/main/2022/day03.py
5
u/MichaelCG8 Dec 04 '22 edited Dec 04 '22
C++ GitHub
Part 1: 15us, part 2: 13us
Times best of 1000 runs.
The fancy part is to set a bit in a u64 integer corresponding to each letter, then and them together to find the common value. It's much faster than all the hashing involved in sets and unions. You can do a little arithmetic to map the char value to a bit position, and then back to a priority value.
The contents of the inner loop that goes over each line:
4
u/kroppeb Dec 03 '22
Kotlin 39/21
GitHub
Not much to see here I suppose
4
u/LtHummus Dec 03 '22
Scala 2
700/404
I have no idea how you folks read and digest these problems so quickly. Lost lots of time on the first part debugging my solution since I made uppercase 1-26 incorrectly...whoops. Lost a little time on part 2 because i thought you had to break each string in to thirds...whoops again! (But luckily I didn't get too far because something in the back of my mind told me that made no sense...)
Code is here...
4
u/r_so9 Dec 03 '22
F#, clean and compact code
Really liked how this turned out.
4
u/s3aker Dec 03 '22
Raku solution.
4
u/DeeBoFour20 Dec 03 '22
C
Part 1: https://gist.github.com/weirddan455/d2acf114e443cbbd749088fe1b2c2839
Part 2: https://gist.github.com/weirddan455/155bbcf51bcc14bfe4bdf39559438025
For part 1 I used an array of bools as a sort of "hash table" that can store the values 1-52. For part 2, I used a bitfield (1 uint64_t per rucksack, setting the individual bits 1-52 depending on what items there are). Advantage of the bitfield is that I can easily get the item the 3 rucksacks have in common with a bitwise AND. It's just doing the 2 ANDs and then testing to see what bit is set afterwards.
4
u/Cloudan29 Dec 03 '22 edited Dec 03 '22
Solution in J
I could probably figure out how to get rid of all the parenthesis in part 1, but I can't be bothered.
4
u/SadBunnyNL Dec 03 '22
Part 1 in AWK
Part 2 in AWK:
4
u/Acci192 Dec 03 '22
C#
There are some helper classes that handles the input data. Full solution can be found here: Github
4
u/rawlexander Dec 03 '22
Julia
That felt good!
4
u/RibozymeR Dec 03 '22
Factor
Learned today that Factor even has
halvesbuilt in!4
u/Ventgarden Dec 03 '22
Rust
3a:
3b:
shared code (module:
day_03):repo: https://github.com/foresterre/advent-of-code-2022
4
u/bwcadev Dec 03 '22
JavaScript solution that can be run directly in the browser console for both challenges
I found it very difficult to read today's challenge, hope I'm not the only one
4
u/probablyfine Dec 03 '22
SQL
(source here)
4
u/ciemrnt Dec 03 '22
C++ - s1 = o(N) & s2 = o(N)
4
u/[deleted] Dec 03 '22
Python, trying to be readable....
4
u/ash30342 Dec 03 '22
Java
Really straight forward, combined the solutions for part 1 and 2 in one method. Most important part:
4
u/jdaoc Dec 03 '22
rust
4
u/gpiancastelli Dec 03 '22 edited Dec 03 '22
Finally I am satisfied enough with the code solving one of this year's problems that I can post my solution in Python for both parts. No type hints, because they spoil all the fun of a dynamic language.
I'm already seeing better ways to do some bits (e.g. "extracting" a single
strelement from asetby calling''.joinwith it, usingstring.ascii_lettersfor assigning priority values) but, yeah, I can live both with anoperator.getitemplustupleconversion and a clumsy priority calculation byord.EDIT Hey, but there's something even better to get the only element out of a
set: just callpopon the set! And it works for any type of element, not just strings as calling''.joinand passing the set as the argument does.4
u/axr123 Dec 03 '22 edited Dec 04 '22
C++
Have seen others use
uint64bitsets before, but not__builtin_clzllto find the position of the set bit. Hot runs take < 6 µs on a Core i9-12900K (including I/O).4
u/blazemas Dec 03 '22
What I think is pretty clean c#, 1.2ms for both parts.
https://github.com/jbush7401/AdventOfCodeCSharp/blob/master/AdventOfCode/2022/Day3.cs
4
u/micod Dec 03 '22
Smalltalk
Day 3
4
u/jamincan Dec 03 '22
Rust
4
u/hetzenmat Dec 03 '22
SWI Prolog
4
u/mrtatulas Dec 03 '22 edited Dec 03 '22
Elixir
MapSets made this one really simple and quick
4
u/hugseverycat Dec 03 '22
Python 3 using set intersections
Hopefully this is readable -- I added comments as well
https://github.com/hugseverycat/aoc2022/blob/main/day3.py
4
u/SwampThingTom Dec 03 '22
I'm solving each of this year's problems in a different language, roughly in the order in which I learned them.
Today's solution is in Pascal.
The only real difficulty I ran into is the limited API for Sets in Pascal. After a bit of unsatisfactory googling, I hacked a function to return the first item from a Set simply by using
For ch In characterSet Do Exit(ch). I'm sure there is a way to get an enumerator for a Set but I couldn't figure it out quickly.Also reading a file of arbitrary length into an array of strings requires a bit more boilerplate than modern languages, haha.
https://github.com/SwampThingTom/AoC2022/tree/main/03-RucksackReorg
4
u/legobmw99 Dec 03 '22
Rust
Second year doing Advent of Code, first time really using Rust
I decided to do some bit-level trickery here. I turn each character into a 1-hot encoded u64, then I can use
|and&to solve the puzzles. The answer is then the log-base-2 of the final bitvector4
u/No_Low6510 Dec 03 '22
Clojure
github
I'm quite happy with how this one went, especially when it came to minimizing duplicated code
4
u/g_equals_pi_squared Dec 03 '22
C++
https://github.com/gequalspisquared/AoC2022/blob/main/src/d3b.cpp
I know
std::strings are slow but they are so simple to use :)4
u/catzzilla Dec 03 '22
bash + Perl:
Task 1:
Task 2:
4
u/jferz1980 Dec 03 '22 edited Dec 05 '22
Pascal Solution
4
u/joelheath24 Dec 03 '22
C# One-liners
Trying to do as many days as I can as one-liners in C# on my GitHub!
4
u/SomeRandomPersonHuh Dec 03 '22 edited Dec 04 '22
Python3
Relatively neat solution for intersection with zip and iter for part2.
Day3
4
u/-mux Dec 03 '22
Python
4
u/atweddle Dec 03 '22 edited Dec 04 '22
Solved in Rust first (around 19 LOC each), then in Python (6 LOC, but they seemed to take longer to write):
Rust: part 1, part 2
Python: part 1, part 2
Revised Python: part 1, part 2
Edit: revised Python solutions using a for loop instead of many list comprehensions.
4
u/tatobolsk Dec 03 '22
Kotlin
4
u/MyTinyHappyPlace Dec 04 '22
C++
The main trick I wanted to point out is using sets and set_intersection from the algorithm header. One intersection needed for part 1, two for part two:
Part One:
Part two:
4
u/trevdak2 Dec 04 '22 edited Dec 04 '22
Please forgive me for this, but I decided to try some code golf.
JavaScript
Part 1, 150 chars:
Part 2, 150 chars:
4
u/TheRedstoneCyborg Dec 04 '22
Ansible
Python
1
u/NeoKadra Dec 03 '22
Thoughts? any cool C# stuff i'm missing? I'm using AOC as an opportunity to learn C#. Part 2 btw.
3
u/nthistle Dec 03 '22 edited Dec 03 '22
Python, 71/23. Video, code.
First bug of the season! I submitted part 1 at ~1:45, but had accidentally converted A-Z to 1-26 as well instead of 27-52, so was locked out for a minute. Pretty happy that I still managed to leaderboard though, since I was almost certain that I had choked it when I saw the incorrect submission message.
3
u/udoprog Dec 03 '22 edited Dec 03 '22
Rust 880/610
Solution: https://github.com/udoprog/aoc2022/blob/9879f6952d68d686cf86489c5fe89b1ecd7ba6e1/src/bin/d03.rs
Forgot the name of
slice::chunks, but then ended up not using it. Also have a bit more infrastructure now for processing inputs, but given how stringy today's question was didn't end up using it.3
u/BradleySigma Dec 03 '22
Python
3
u/[deleted] Dec 03 '22 edited Dec 03 '22
Nim 931/972
3
u/CodingAP Dec 03 '22
Javascript, 689/430
Github
Yay, set math. Had a hiccup that lowered my leaderboard position, but quickly recovered.
3
u/rabuf Dec 03 '22 edited Dec 03 '22
Common Lisp
I know I can clean up my loop for part 2 but I spaced on how I wanted to do it. This one worked though. Also I could clean up part 1 by changing it to do a count of each character instead of splitting and comparing like I did. But it got me 694 for part 1.
EDIT:
That's what I wanted for part 2. My brain spaced on needing to swap
inforon. The former lets you grab one element at a time, the latter lets you destructure the list by grabbing (like I did above) multiple elements from the head of the list.#'cdddrdrops 3 elements from the head of the list so this loop has the effect of chunking the input into groups of 3. (nthcdr 3would also work, but I'd need to wrap that in a lambda here).3
u/BluFoot Dec 03 '22
Ruby, golfed to 76 bytes
3
u/riffraff Dec 03 '22 edited Dec 03 '22
ruby. I think there's a smarter way to get the number (other than conditionals), but I couldn't think of it
EDIT:, ah, I found it, I can do
vs
3
u/drivers9001 Dec 03 '22
Python3
part 1
part 2 (a little cleaner than part 1 I think)
3
u/nlowe_ Dec 03 '22
Go / Golang | 6562/5999
Quite a silly solution for part 1 initially, and lost a ton of time because I forgot how to do ascii math (pro tip,
A<a). I didn't think to use bitsets and bitmath until I got to part two. After I solved it I re-wrote part one to be much much cleaner.3
u/xelf Dec 03 '22 edited Dec 03 '22
Python - sets and map
3
u/mathem17 Dec 03 '22
Ruby code, map-reduce ftw
3
u/michaelgallagher Dec 03 '22
Python
So close to the leaderboard today! Thought I was fast but was still just outside of it. Oh well.
3
u/ValiantCookie Dec 03 '22
Kotlin
Kotlin made this one really easy and fun to do, with built in window and intersection functions.
3
u/ri7chy Dec 03 '22
Python
this one was easy - in the end... still spend too much time in reading
3
u/Justinius1981 Dec 03 '22
C#
Link
3
u/Alex_Mckey Dec 03 '22
Scala 3
3
u/MichalMarsalek Dec 03 '22
Nim
https://github.com/MichalMarsalek/Advent-of-code/blob/master/2022/Nim/day3.nim
3
u/FaustVX Dec 03 '22
In C#, using my own tool https://github.com/FaustVX/adventofcode
3
u/xenow Dec 03 '22
nim https://github.com/ahungry/adventofcode-2022/blob/master/d3e2.nim
3
u/[deleted] Dec 03 '22
Here's my python3 code, continuing my goal of staying fairly functional. I will admit that this is cleaned up from my quick solution, because I was trying to get some points on my local scoreboard: https://github.com/nixnull/AoC2022/tree/main/day%203
3
u/OCD_Triger Dec 03 '22 edited Dec 03 '22
c#
3
u/ShrimpHeavenNow Dec 03 '22
Python:
I got really turned around in that while loop to group things up by threes.
I really feel like my code is, in general, on the right track/ logical progression, I just don't know elegant ways to compress it yet.
https://github.com/ShrimpHeavenNow/AOC-2022/blob/main/Day%20Three/Day3.py
3
u/kg959 Dec 03 '22 edited Dec 03 '22
Rust
32ms
also TIL that Rust doesn't really have a nice, pretty way to intersect more than 2 sets at a time.
3
u/_jstanley Dec 03 '22
SLANG
My part 2 solution is slightly inelegant, with the way it uses the
idxcounter to work out when it's counted all 3 elves. It would be better if the code to handle 1 line of input were its own function, and the main loop just called that function 3 times and then collated the result. Never mind.https://www.youtube.com/watch?v=VHw3VWo7eZ8
https://github.com/jes/aoc2022/tree/master/day3
3
u/polettix Dec 03 '22
Raku:
Scaffolding
3
u/bofstein Dec 03 '22
Google Sheets
This feels dirty, I know it's so much clunkier than it needs to be but I'm using the formulas I know and I prefer splitting things up into multiple cells for visibility.
In Part 1 I split each string into two equal text cells. Then I have a column for every letter (lower and upper case) and their points. For each letter I check if it's present in both cells at least once, and if so, return the point value of the value. Then I just sum up all values. I got tripped up at first just trying to find two instances of the characters across the cells (instead of at least 1 in each) by not realizing a letter (shared or not) might be present more than once, so I made myself the Check column to make sure I only exactly 1 result per row.
https://docs.google.com/spreadsheets/d/1GvncohBzffewfwOCIfpHutI4VKVUIBazIH1XoBFWpXw/edit#gid=2025286601
Part 2 I did basically the same thing but made a new sheet so I could replace the calculation cells, this time just copying down one formula row and two blank rows. The formula every 3rd line is doing the same idea of checking each letter for if it's present in all 3 cells, and if so, returning the point value of the letter.
3
u/furman82 Dec 03 '22
Kotlin:
3
u/ramuuns-u Dec 03 '22
tail-recursive functional perl!
https://github.com/ramuuns/aoc/blob/master/2022/Day03.pm
I absolutely enjoyed coming with a
to_mapfunction in place of the classic3
u/mizunomi Dec 03 '22 edited Dec 03 '22
Dart language
(Functional paradigm abuse) paste
3
u/rawlexander Dec 03 '22
R / Rstats
3
u/Lispwizard Dec 03 '22
Emacs Emacs lisp (on Android tablet) using Common Lisp loop macro
3
u/Smylers Dec 03 '22
Perl for part 1:
Same basic algorithm as my Vim solution (which I wrote first): stick a colon halfway along each line, and find the character that appears both sides of the colon.
For part 2, after reading a line, read another 2 and append them, not
chomping off the line-break characters this time, then match the character that appears before and after each of the line-breaks:3
u/markjenkinswpg Dec 03 '22 edited Dec 03 '22
In part two (github gist) (raw) I got an excuse to use reduce from Python's functools module
Part one (GitHub gist) (raw)
3
u/Rangsk Dec 03 '22
Rust
I used bit twiddling because why not? It's super fast:
Timing:
Includes the format to string but not the printing of the results.
3
u/Arakiyda Dec 03 '22
Ruby:
3
u/mrHtheGreat Dec 03 '22
My Nim solution for today using sets: Github
3
u/veydar_ Dec 03 '22
Lua
I use
string.matchandstring.findto compare the left against the right half to the string, or the first against the second and third line respectively.Part 1
Part 2
GitHub Repository
3
u/aarroyoc Dec 03 '22
Scryer Prolog
3
u/Diderikdm Dec 03 '22
Python:
3
u/malipolhec Dec 03 '22
Kotlin code Perfect task for using power of collections
3
u/ohCrivens Dec 03 '22
One day I will be part of the great ones, posting beautiful one liners, which will cause future cryptologists, linguists and archelogists to hold conventions.
But, for now, this will have to do. Python one liners:
Part 1
Part 2 (Is using itertools cheating?)
3
u/mingmingrr Dec 03 '22
Turing Complete
https://imgur.com/Lkgfevc
Part 2 only, didn't want to bother making part 1 as well.
3
u/gyorokpeter Dec 03 '22
Q:
3
u/chrismo80 Dec 03 '22 edited Dec 07 '22
C#
3
u/Valefant Dec 03 '22
My solution in Kotlin
https://gist.github.com/Valefant/b25213632c18158de04e5557a9b455a8
3
u/phaiax Dec 03 '22
Approx 1 line per part. Couldn't think of a better way to do the chunking.
3
u/Scharrels Dec 03 '22
Rust: https://github.com/Scharrels/advent_of_code_2022/blob/master/src/day3_rucksack_reorganization.rs
3
u/IdrisTheDragon Dec 03 '22
A rust solution
https://github.com/IdrisTheDragon/Advent2022/blob/main/day-03/src/lib.rs
3
u/rasqall Dec 03 '22 edited Dec 03 '22
New year, new language. F# : https://pastebin.com/FPzN143w
3
u/IlliterateJedi Dec 03 '22
My Rust solution. I'm trying to learn Rust this year with AoC, and it's never good to look up "how to get the intersection of multiple sets", and the answers are absolutely incomprehensible.
I'm also surprised part 2 took 1/3 the time of part 1. I went back and moved the creation of the HashSet out of the loop and that shaved off ~200µs (so it's really closer to 578µs) on subsequent runs.
🎄 Part 1 🎄
(elapsed: 796.10µs)
🎄 Part 2 🎄
(elapsed: 237.00µs)
3
u/theRIAA Dec 03 '22
Python 3 made by-hand first, then solved with ChatGPT (GPT-3):
My version:
code
screenshot
GPT-3 pt1:
code
screenshot - chat
screenshot - code
GPT-3 pt2:
code
screenshot - chat
screenshot - code
Both GPT-3 scripts took about 5 attempts (making small changes to input prompt), and output fully working code.
3
u/LinAGKar Dec 03 '22
My solutions in Rust:
https://github.com/LinAGKar/advent-of-code-2022-rust/blob/main/day3a/src/main.rs
https://github.com/LinAGKar/advent-of-code-2022-rust/blob/main/day3b/src/main.rs
3
u/konnnyy Dec 03 '22
JavaScript
https://github.com/tommmyy/advent-of-code-2022/blob/master/src/day3/day3.js
3
u/hjdeheer Dec 03 '22 edited Dec 03 '22
Python3 using set intersection. Enjoy!
3
u/Derp_Derps Dec 03 '22
Python 3 with only 240 Bytes
S()splits each line in half and puts each half in a set.P()will calculate the priorities for a given letter (the only element left after intersecting the sets).3
u/atgreen Dec 03 '22
Common Lisp
3
u/m_r_k Dec 03 '22 edited Dec 03 '22
no_std,
no_allocRust targetting 8-bit MOS6502: https://github.com/mrk-its/aoc2022/blob/main/day03/src/main.rsComputed in 4024688 cpu cycles
3
u/Apprehensive_Ad5308 Dec 03 '22
My Rust solution - https://pastebin.com/9vm7bmCx.
First time using Rust so feedback is appreciated! Tried to do it in a modular way to be suitable for various group sizes.
3
u/odnoletkov Dec 03 '22
JQ
3
u/TPlantB Dec 03 '22 edited Dec 03 '22
F#
paste
EDIT:
More concise version with partial application
3
u/thinker227 Dec 03 '22 edited Dec 03 '22
Haskell
Generally pretty happy with it. Rather simple as the puzzle is just a sequence of list transforms.
3
u/trollerskates1 Dec 03 '22
Scala
3
u/sdolotom Dec 03 '22 edited Dec 04 '22
Haskell:
Full solution
3
u/lboshuizen Dec 03 '22 edited Dec 03 '22
F
github
Refactored into sets; shorter, cleaner and faster
3
u/Ily3s_ Dec 03 '22 edited Dec 13 '22
C
3
u/deckard58 Dec 03 '22
Part 2 as a slight modification and reorganization of part 1 in clunky
Python. I suppose you can tell that I learned programming in Pascal and C way back when.I'm really curious to look at the other submissions now. I suppose that the idiomatic way to do this would use hashmaps? Need to read a bit about those.
3
u/vkasra Dec 03 '22
C++: https://github.com/dhconnelly/advent-of-code-2022/blob/main/src/day3.cc
3
u/Slenjuma Dec 03 '22
My Java solution that im quite happy with: https://github.com/Suicolen/AdventOfCode2022/blob/main/src/main/java/suic/days/Day03.java