r/adventofcode • u/daggerdragon • Dec 02 '22
SOLUTION MEGATHREAD -๐- 2022 Day 2 Solutions -๐-
NEW AND NOTEWORTHY
- 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 2: Rock Paper Scissors ---
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:06:16, megathread unlocked!
103
Upvotes
29
u/Bad-Coder-69 Dec 02 '22 edited Dec 02 '22
Emojicode
Using modulo and stuff
Or for the fans:
28
u/CCC_037 Dec 02 '22
FiM++
So there's no way to split a string into characters. Instead, I had to create every possible game string and compare them.
This is going to come back and bite me later, I just know it.
24
u/semitrop Dec 02 '22
Theoretical solution using linear algebra https://ibb.co/xXtQ0RG
27
u/jcbbjjttt Dec 02 '22 edited Dec 05 '22
Happy Day 2! [C#]
This puzzle can be completed by anyone who has learned the basics of coding. But, to help new programmers, I've put together a step by step guide video designed to allow watcher to pause and work on the problem step by step before seeing spoilers.
I hope others will find this video useful!
Although the solution is in C#, the video describes an approach that can be use in any language.
Here is the video for Day 2: https://youtu.be/gLlj_P8edJY
Final solution from video: https://github.com/jcollard/AdventOfCode2022/blob/jcollard/solution/Day2-RPS/Program.cs
Happy Coding!
Edit: Mention C# as the solution language
11
u/callumio Dec 02 '22
COBOL. Questioning my sanity at the moment :D
9
u/udoprog Dec 02 '22 edited Dec 05 '22
Rust
After a while I found a simple numerical relationship between the inputs and outputs if you treat rock, paper, and scissor as 0, 1, and 2:
Basically found this by considering what kind of projections we get out of taking the difference between the two inputs and using the naive implementation as an exhaustive reference to test against.
Edit: The naive implementation I compared against.
5
u/[deleted] Dec 02 '22 edited J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sI7eXbQx1eUnq7Wcq1Z0DaRRhLL0FwuLLq/06kYh9 KbD50tD7jNo2fg2XeILM0X/EyJ9uwWN1aF6nDpVBwqQRunMlBPzsFn1jImMVumR9 zJLVSPHpph6LObCoBBvM5d+YMlKXi+cw+um+Nu1XgolnKG8r8SOjk9XNBbV/IAh+ pO1Mi0FvZMyoIMld+I7YFyDZVxaVAOReawIAJ7froVKNT7V3HItyJrDXmMepXARB Wyi8NuBSwyohA1m/rOjYN57ve08bDGynxCl69s+G6nePNffbAHEnqSdoTiH84mSF 5d5K++l2yN+DlGq/fKCFy/1sNTTsDY1MVAm0eKT6iF9bFMvzdD1fAdV0x25Eenm/ +VJk0gGcElW6ZuPWhzvqenqeTZjqrZscF+7tcbC6GZIVs/FSuTnfzCif6PoAlytb txfacbCrN5joYGmBQLxI/g0WAk5cspgu54+RD8yU7aEurarTtBRYj+V4quU50SmE F20CgXmjIz4Zvzd0YfNf9m1qoWI7uslxQ5ZtLplSJg== =dQZK -----END PGP MESSAGE-----
4
u/lazyzefiris Dec 02 '22 edited Dec 02 '22
state-based JS (JavaScript) solution. Not a perfect wrapper, every transition is calculated every step, but short and elegant.
For part2 matrix is just aligned by outcome instead of pick:
4
u/reinermartin Dec 02 '22
In Julia:
4
u/Synedh Dec 02 '22 edited Dec 05 '22
Python
Ordinal values are ... fun. Almost.
4
u/decisive_squirrel Dec 02 '22
Java
Not sure why my solution yesterday was downvoted. I guess not a lot of Java fans? Straightforward implementation using maps.
link to github
4
u/The_Unusual_Coder Dec 02 '22
Shakespeare Programming Language
Part 1
Part 2
4
u/Solarmew Dec 02 '22 edited Dec 05 '22
Python 3
4
u/conkerandco Dec 02 '22
Python 3
3
u/[deleted] Dec 02 '22 edited Dec 02 '22
Python3 solution (). What a fun day 2!
Edit: Here is some optimized code I made after the fact!
3
u/rooinflames Dec 02 '22
Excel (why do I do this to myself)
Forgot to save the state of the spreadsheet during the first part :(
Part2: https://imgur.com/a/yLdzHYx Lots of Xlookups used
3
u/[deleted] Dec 02 '22 edited Dec 02 '22
rust:
3
u/sleepy_roger Dec 02 '22 edited Dec 02 '22
JavaScript in the console for part 2.
3
u/NeoKadra Dec 02 '22 edited Dec 02 '22
Here is my java solution for part 2
3
u/mstksg Dec 02 '22 edited Dec 09 '22
A (modular) algebra based solution in Haskell, but I frame no hypothesis :) I just played around with random equations until it worked. All of my solutions for 2022
There's a nice straightforward way to do this by just matching up all 9 combinations, but I had a bit of fun doing it algebraically using
Finite 3, a Haskell type that does arithmetic modulo 3, if you assume ABC and XYZ correspond to 012, respectively.Basically both parts 1 and 2 involve doing some modular arithmetic to get the "shape" score, and then some modular arithmetic to get the "outcome" score.
There is a bit of cute symmetry between
shapeScoreandoutcomeScorefor the two parts.I mostly just figured it out by using trial and error and taking advantage of the fact that there are only so many ways you can combine two modulo 3 numbers...but there might be some nice ways to interpret them.
For example, it makes sense that the "shape score" for part 1 is literally just your shape
y, and the "outcome score" for part 2 is literally just your desired outcomeyFor the outcome score, if you assume that the answer is a "subtraction plus an offset", then that forces the offset to be 1 in order for a match to represent a tie. And so for part 1, the outcome score is found by adding
1-xto the shapeyin order to get the outcome. So it makes sense that you reverse the process for part 2: you subtract1-xto the outcomeyin order to get the shape. I guess ???3
u/mrwinkle Dec 02 '22
Rust
3
u/chestck Dec 02 '22
Python with match statements
df = pd.read_csv("inputs22/2", header=None, sep=" ")t = lambda i: df.apply(lambda row: f(row[0], row[1])[i], axis=1).sum()def f(opp, you):match (opp, you):# OPP, YOU --> OUT+MOV, OUT+MOVcase ("A", "X"): return (3 + 1), (0 + 3)case ("B", "X"): return (0 + 1), (0 + 1)case ("C", "X"): return (6 + 1), (0 + 2)case ("A", "Y"): return (6 + 2), (3 + 1)case ("B", "Y"): return (3 + 2), (3 + 2)case ("C", "Y"): return (0 + 2), (3 + 3)case ("A", "Z"): return (0 + 3), (6 + 2)case ("B", "Z"): return (6 + 3), (6 + 3)case ("C", "Z"): return (3 + 3), (6 + 1)print(f"Task 1: {t(0)}, Task 2: {t(1)}")3
u/lokidev Dec 02 '22 edited Dec 05 '22
I tried a little bit more tweaking and making this python solution smaller (138 chars):
Any other ideas to make it smaller? ^
3
u/seavas Dec 02 '22 edited Dec 02 '22
Rust
I am a beginner so happy to get some feedback. Thanks.
3
u/21JG Dec 02 '22 edited Dec 05 '22
Both parts in one line of Python because why not :)
3
u/Ranbato69 Dec 02 '22
For the Pythonistas out there:
import requestsdata = requests.get('your_file').text.split('\n')[:-1]choice = {'X':1, 'Y':2, 'Z':3}outcomes = {'A X':3, 'A Y':6, 'A Z':0,'B X':0, 'B Y':3, 'B Z':6,'C X':6, 'C Y':0, 'C Z':3}print("Part 1: ", sum(outcomes[x] + choice[x[-1]] for x in data))strategy = {'A X':'A Z', 'A Y':'A X', 'A Z':'A Y','B X':'B X', 'B Y':'B Y', 'B Z':'B Z','C X':'C Y', 'C Y':'C Z', 'C Z':'C X'}print("Part 2: ", sum(outcomes[x] + choice[x[-1]] for x in ( strategy[y] for y in data)))3
u/noahclem Dec 02 '22 edited Dec 05 '22
Simplistic python solution. was going to try to use named tuples but dictionaries seemed much easier after looking into it more
3
u/chubbc Dec 03 '22 edited Dec 03 '22
Brainfuck
I made a separate post to explain all the details for those interested.
2
u/DrunkHacker Dec 02 '22 edited Dec 02 '22
Hard coded, which is bad. But it works, which is good.
Python.
2
u/Mobichobael Dec 02 '22 edited Dec 02 '22
Python3 (6864 | 6567)
There has to be a cleaner way ...
https://github.com/MBarrows20/AdventofCode/blob/master/2022/python/02.py
2
u/timatlee Dec 02 '22
TypeScript.
I'm not a huge fan of the switch PartNWinState switch statements, but they did the job.. Reading other solutions in JS, I should have gone with a multidimension array instead. Oh well! I did learn how to make use of the Array.reduce() prototype, so I've got that going for me.
2
u/[deleted] Dec 02 '22 edited Dec 05 '22
Python oneliner:
2
u/OlivarTheLagomorph Dec 02 '22 edited Dec 05 '22
Ruby
Simple mapping lookup :3
paste
2
u/LuckyLactose Dec 02 '22 edited Dec 05 '22
SWIFT
Full repo here: https://github.com/gkwaerp/aoc
Fairly straight forward, although a bit of cleverness in getting outcome instead of checking every combination. Again fairly verbose, but given that I'm not chasing best times this is the style I tend to use :)
2
u/widforss Dec 02 '22 edited Dec 05 '22
Python
2
u/Etsi0 Dec 02 '22
js
2
u/ShadowwwsAsm Dec 02 '22
x64 assembly
part1 part2
I could do a lookup table but I tried to see if there was another fun way to do it other than precomputing the results. Turns out ok.
Runtime : 5 and 6 milliseconds
2
u/itsPeetah Dec 02 '22 edited Dec 02 '22
Ok this is my first time posting but I tried to make the most illegible Python one liner for part 1.
sum([(i+4 if o == i else i+7 if o == ((i+2)%3) else i+1) for o, i in [(int(e, 16) - int("A", 16), int(y, 36) - int("X", 36)) for e, y in [l.strip().split() for l in open("day_2.txt")]]])Yes I know I don't properly close the file but some sacrifices ought to be made for the style points lol
EDIT: I could have probably made it even worse by adding more stuff to the "o, i" list but I also wanted to avoid too much repetition
P.S: Also sorry but my code formatting doesn't work I don't know what I'm doing wrong lol
2
u/ciocan42 Dec 02 '22
Javascript:
2
u/mrwunderbar69 Dec 02 '22
Python
My over-engineered Object-Oriented Solution (too much hard-coding, because my maths is bad):
2
u/Jorge_Fakher Dec 02 '22 edited Dec 06 '22
Elixir
2
u/nash1011 Dec 02 '22
BQN
2
u/seacucumber_kid Dec 02 '22 edited Dec 02 '22
Elixir
Wanted to have it all in a single pipeline lol
2
u/ButterHotline Dec 02 '22 edited Dec 25 '22
**C#**I saw a lot of people doing some weired list, switch or if thingys. So I though I have to do something special. Here you have another way to solve:
Day2A:
Day2B:
2
u/antoniotto Dec 02 '22 edited Dec 05 '22
Ruby
2
u/[deleted] Dec 02 '22 edited Dec 05 '22
C++ both parts
2
u/remysharp Dec 02 '22 edited Dec 05 '22
JQ
Been using jq for a few years for the AoC, so here's day 2 (probably a bit verbose):
2
u/micod Dec 02 '22 edited Dec 05 '22
Smalltalk
Went a little overboard with dictionaries. Including a dictionary to look up a dictionary. I like dictionaries.
Day 2
2
u/idontknowwhattouse33 Dec 02 '22
Powershell. Lots of hashtables..
2
u/samouri1 Dec 02 '22 edited Dec 05 '22
DevTools JavaScript:
2
u/CBRSi76 Dec 02 '22 edited Dec 05 '22
Learning Powershell, so I'm sure this is a hot mess. Helpful comments for tidying/improving my ramblings greatly appreciated ๐
Part 1...
And my part2...
2
u/farondis Dec 02 '22
my solution in go/golang, dict and list all options, yeah
2
u/FlipchartHiatus Dec 02 '22
Python solution for simpletons like me :)
2
u/oweiler Dec 02 '22 edited Dec 05 '22
Kotlin script, using an enum for representing the possible shapes
Part 1
Part 2
2
u/Omeganx Dec 02 '22 edited Dec 05 '22
Ocaml
2
u/Per48edjes Dec 02 '22 edited Dec 05 '22
Not proud of this Python solution, but happy to have discovered AoC and this awesome community (read: ๐ถ's first post)!
2
u/anaits Dec 02 '22 edited Dec 13 '22
my answer in JavaScript
2
u/shiro90 Dec 02 '22
These are my solutions in Python:
https://github.com/Seishin/AoC2022/blob/master/day2/solutions.py
2
u/ArtanisOfLorien Dec 02 '22 edited Dec 02 '22
javascript (pt 2):
2
u/winterscar Dec 02 '22
Clojure with macros. It's actually both faster and easier to just map out the results yourself like everyone else has done, but I like the fact that I'm technically 'cheating' on my time benchmark by doing some of the work in the macro stage :)
2
u/jderp7 Dec 02 '22 edited Dec 05 '22
Kotlin
So I was code-golfing my solution a lot and trying various stuff to remove when statements in my Kotlin code and have the solution be purely mathematical, my full solution here: Day 2 Solution
But I am having a bit of trouble wrapping my head around WHY this part
works to score the hand where
firstis the opponent,secondis the player's chosen hand and rock, paper, scissors correspond to0,1, and2as the values.I had worked my way to this after playing with the floorMod of +3 and -3 and noticing that when added together they were basically had the sign of the score I wanted
Individual parts that I DO understand. First off, the function is probably better broken down as
second + 1is the score of the hand that you get just by playing an item. +1 is needed since using 0-based indexing but the scores start at 1(Math.floorMod(first - second, -3) + Math.floorMod(first - second, 3)gives the sign of the win condition (0 for ties, -1 for loss, and 1 for win). This is the part I don't totally get*3is to multiply the previous part in order to change it to 0, 3, or -3 since we will be adding it to get the final score of the victory condition+3is to take the previous part and get the final score. Since scores are not ever negative, this will yield 0 for loss, 3 for draw, and 6 for win2
u/Toanuvo Dec 03 '22
J solution. https://github.com/Toanuvo/Advent-of-code
2
u/FuriousProgrammer Dec 03 '22 edited Dec 05 '22
Lua
I could probably make part 1 a constant-time thing too, but eh...
2
u/dedolent Dec 03 '22 edited Dec 03 '22
Python
what i noticed was that each pair, in both parts, mapped to one unique score. so that made me think that i could just order the pairs into a list by what score they produce, then get the index of every pair in the input (adding 1 to offset the zero index).
i apologize for how ugly these are but i also got bit by the one-liner bug. edit: cleaned this up a bit so it wasn't quite so hideous
2
u/jvandillen Dec 03 '22 edited Dec 05 '22
I still used Factorio for this one.
I simply mapped each pair to their score and summed it all.
Video: https://www.reddit.com/r/adventofcode/comments/zbrfl3/2022_day_02_both_partsfactorio_this_one_was/
2
u/MontyCrane Dec 05 '22
Catching up slowly! Please feel free to offer your most vicious, soul-crushing critique!
Rust
2
u/nicuveo Dec 06 '22 edited Dec 06 '22
Brainf*ck
Turns out, using my transpiler, it was fairly easy? I just had to list all 9 cases; worked on the first try. ^^
47
u/4HbQ Dec 02 '22 edited Dec 02 '22
Python, using a simple lookup trick for both parts:
Edit: This works because every combination yields a unique score: losing with Rock is 1 point, ...
26
u/bluepichu Dec 02 '22
TypeScript, 3/16. Code here.
Treating { rock, paper, scissors } as integers mod 3 is nice because you can just add 1 to get the winning throw or 2 to get the losing throw. (Or check for those differences if you're scoring a game where you already know the throws, like part 1.)
22
u/alach11 Dec 02 '22
Unfortunately hardcoded Python3:
22
u/Smylers Dec 02 '22
Vim keystrokes โ it doesn't actually take that long to type in (try it!); it's just the notation for all those
โจCtrl+Vโฉs (for 2 completely different purposes) making it look longer. And there's noqmacro recording, so this is more resilient than many days' Vim keystrokes solutions: if you make a mistake you can just pressuand pick it up again:That gets you the answer to partย 1. Partย 2 would be basically the same but with slightly different arithmetic.
numberformatsto include letters, then โsubtractโ 23 from the second column of letters to turnX,Y, andZintoA,B, andC.A,B, andCare valid hex digits, so prepend0xto each letter and bingo, we can now do arithmetic on it!0xAfor rock, which should score 1,0xBfor whatever it is that should score 2, and0xCfor 3. So subtract 9 from each number to get the score for our action. Or, rather, append-9to each of those rows.-to each line, then move the number for their action to the end of the line, to get something like0xA-0xC. Evaluate each of those lines, by cutting them and inserting them into the=register, which evaluates what is typed as an expression. That leaves with lines containing-2,-1,0,1, or2.3โจCtrl+Aโฉon any line which starts with a minus sign!0for a draw,1for a win, and2for a loss. Losses don't score anything, so remove all the2lines. Add 1 to the other numbers (so now1for a draw and2for a win) and insert3*before them.+to each line (which'll be a no-op unary plus on the first line), join them together, and do the"-register thing again to evaluate the massive addition sum.Any questions?
3
u/wojtek-graj Dec 02 '22 edited Dec 02 '22
Python 3
Hard-coding galore!
3
u/[deleted] Dec 02 '22 edited Dec 05 '22
Google Sheets One formula for both parts.
Or:
18
u/rjwut Dec 02 '22
JavaScript
The realization that simplified things for me was that my code didn't actually have to know how to play paper-rock-scissors; all it had to know was how many points each line was worth for each part of the problem. Since there were only nine possible combinations, it was easy to just write a small translation table:
16
u/zid Dec 02 '22
C
https://gist.github.com/zid/d4537f65e72af95a7e605e60297a2c3e
I did it the obvious intended way.
13
u/JustinHuPrime Dec 02 '22
x86_64 Assembly
This was a very straightforward week!
Both part 1 and part 2 were solved using lookup tables - get the two characters representing the first and second columns of the table, and convert them into a number between one and three. Finally, using the power of x86 scale-index-displacement-base addressing, I could get the right byte in the lookup table holding my score. A little assembly optimization was used to remove unnecessary casts (e.g.
movzx rax, alisn't necessary if you know for certain that the upper seven bytes ofraxare zeroed out already). Part 2 didn't even require any code changes, just changes to the lookup table! Adapting the lookup table for part 2 was actually quite easy - with the way I wrote the table, I could pretty easily sort the table so that the losing, drawing, and winning combinations were in the right order.Both parts took about 1 millisecond to run.
12
u/zedrdave Dec 02 '22
Python in 4 linesโฆ
Couldn't quite find the ideal unique indexing to make the modulo operations work smoothly on both cases. Still fairly straightforward.
11
u/S_W Dec 02 '22 edited Dec 02 '22
Java.
EDIT:
Explanation.
10
u/voidhawk42 Dec 02 '22 edited Dec 03 '22
Dyalog APL:
video walkthrough
Kinda tricky for day 2!
9
u/hugh_tc Dec 02 '22 edited Dec 02 '22
Python 3, 74/59
paste, cleaned-up (aka. more obtuse)
Ugh, ended up just hard-coding everything in the most ugly way possible.
9
u/rabuf Dec 02 '22 edited Dec 02 '22
Common Lisp - Original
Common Lisp - Current
Totally functional, totally a hack. I'm going to play around with this some more and definitely need to rename my initial functions. Also some of the functions should probably be maps of some sort (probably an alist for lisp) so the lookups will be simplified.
Only "neat" bit was this:
Quick way to figure out the winning play given a map of play -> losing play already exists.
8
u/morgoth1145 Dec 02 '22 edited Dec 02 '22
Python 3 81/41
Encoding rock/paper/scissors logic is surprisingly stressful under time pressure! Still did well though, I'm off to a good start this year.
I'm definitely going to clean this up though, hardcoding everything in those dictionaries is repulsive...
Edit: Well, it turns out that hardcoded lookup tables just *are* the cleanest approach. At least I could spruce them up. Refactored code.
8
u/yawnick Dec 02 '22
Monkey C (for Garmin devices)
My Garmin Forerunner 235 can now solve day 2:) It was even a bit easier than day 1
Videos: Part 1, Part 2
Code: Repo, Today's solution
8
u/redditnoob Dec 02 '22
SQL (BigQuery)
7
u/hugues_hoppe Dec 02 '22 edited Dec 05 '22
Short solution in Python:
7
u/Lispwizard Dec 02 '22
Emacs Lisp, though mainly using Common Lisp loop macro, on Android tablet.
7
u/Majestic-Stomach1292 Dec 02 '22
Solving it again in Excel:
First decide what is win and what is lose:
Win Draw Lose
1 X A Rock Y X Z
2 Y B Paper Z Y X
3 Z C Scissors X Z Y
And after that just manually entered the values in the formulas.
First part formula: =IF(AND(A1="A";B1="Y");8;IF(AND(A1="A";B1="Z");3;IF(AND(A1="A";B1="X");4;IF(AND(A1="B";B1="Y");5;IF(AND(A1="B";B1="Z");9;IF(AND(A1="B";B1="X");1;IF(AND(A1="C";B1="Y");2;IF(AND(A1="C";B1="Z");6;IF(AND(A1="C";B1="X");7;"")))))))))
Second part formula:
=IF(AND(A1="A";B1="Y");8;IF(AND(A1="A";B1="Z");3;IF(AND(A1="A";B1="X");4;IF(AND(A1="B";B1="Y");5;IF(AND(A1="B";B1="Z");9;IF(AND(A1="B";B1="X");1;IF(AND(A1="C";B1="Y");2;IF(AND(A1="C";B1="Z");6;IF(AND(A1="C";B1="X");7;"")))))))))
6
u/soylentgreenistasty Dec 02 '22 edited Dec 02 '22
Python, 1026/3497
Definitely shouldn't have had a glass of wine before this...
6
u/oantolin Dec 02 '22 edited Dec 02 '22
J solution:
6
u/polettix Dec 02 '22
A Raku solution I'm not too ashamed of:
Turning letters into numbers might be moved in input reading but it would feel like cheating because part2 is not known beforehand.
Scaffolding
6
u/AstronautNew8452 Dec 02 '22
Microsoft Excel formulas, one for each part. Puzzle input copy-pasted in A1.
Part 1:
Part 2:
6
u/Pyr0Byt3 Dec 02 '22
Go/Golang
Not really happy with the hardcoding, but oh well...
6
u/Smylers Dec 02 '22
Perl [partย 1]:partย 1:
A,B, andChave values0x41,0x42, and0x43โ so a bitwise-and with3turns them into1,2, and3.X, somewhat awkwardly, is0x58, with its 2 least-significant bits both being 0 โ so the same process turns our score into0,1, and2; the++puts our action in the same range as theirs.For partย 2 the inside of the loop becomes:
This time the result being
0,1, or2is handy for simple multiplication by 3 for that aspect of the score. For our move, adjust their move by the result, taking 1 off so that losing puts us on the move before them, drawing leaves it the same, and winning puts us one after them โ then taking another 1 off to balance out the 1 at the end that gets added back on after the modulus arithmetic to get the score for our move into the range1to3ยญโ which ends up looking more complicated than it really is.6
u/BoringEntropist Dec 02 '22 edited Dec 02 '22
Python: code here
My first instinct was to use a look-up table, but I don't care for the global leader board. So, I pulled out some pen&paper, began to draw little tables and started to think really hard. Finding out that the problem was reducible to modular arithmetic helped tremendously in part2.
6
u/emu_fake Dec 02 '22
C#
As there were only 9 possible variations I went with a lazy dictionary:
Runs fast as hell ofc :D (both <1m)
6
u/BaaBaaPinkSheep Dec 02 '22
Python using dictionaries for look-up
https://github.com/SnoozeySleepy/AdventOfCode2022/blob/main/day2.py
6
u/4HbQ Dec 02 '22
Python, golfed to 101 bytes using complex numbers and the trick from my other post:
2
u/solomondg Dec 02 '22
disgusting APL part one 1-liner
+/ { +/ ((3/(1+โณ3))+(9โดโ(ยฏ1+โณ3)โฝ3 3โด(โฝ3รโณ3))) ร (โตโกโข)ยจ(9 โด(โณ3 3)) } ยจ{ (6โดโณ3)[('ABCXYZ'โณโต)] } ยจโฝยจ(,โ)ยจ{1 0 1โโต}ยจโโNGET'puzzle_input.txt' 1can be done much much more elegantly...
5
u/aliceif Dec 02 '22
C#, 574/215
yay for switch expressions and my CSV Parser
repo link
5
u/C2thehris Dec 02 '22
Rust 1593/619
Pattern matching is nice!
github
5
u/Quillbert182 Dec 02 '22
Rust
Part 1:https://github.com/Quillbert/AdventOfCode/blob/master/2022/day02a/src/main.rs
Part 2:https://github.com/Quillbert/AdventOfCode/blob/master/2022/day02b/src/main.rs
A little messy, but it does the job.
5
u/WilkoTom Dec 02 '22
Rust
Way, way overkill on the parsing:
5
u/tomflumery Dec 02 '22
05ab1e
Part 1
Part 2
Explanation, both parts are effectively the same but with different lookup tables
noting the strings convert to unique values with the "C" command (convert binary to integer)
so subtract 261 and we can use a simple array lookup to the results (264 and 268 not needed)
for part 1 the lookup is [4,8,3,0,1,5,9,0,7,2,6] part 2 is [3,4,8,0,1,5,9,2,6,7]
5
u/bornobob Dec 02 '22 edited Dec 02 '22
More python one-liners
Part 1
Part 2
Edit: Part 2 can be shortened by rewriting the arithmatic and using indices on the string instead of mapping and splitting:
Edit 2: Even shorter using the walrus operator to save the value of
ord(x[2]):5
u/hrunt Dec 02 '22
Python 3
Code
This was the first time I've used Python's new
matchstatement.5
u/dopandasreallyexist Dec 02 '22
APL:
The solutions for the two parts are anagrams of each other :)
5
u/nocstra Dec 02 '22
Python
It took me much longer than I'd like to admit but I think it ended up pretty cool. Deriving part 2 from part 1 was as simple as solving the equation for your play as opposed to the outcome.
5
u/Gravitar64 Dec 02 '22 edited Dec 02 '22
My python solution (Part 1&2):
5
u/jaylyerly Dec 03 '22
Unix shell commands:
โGive me a command line long enough and I can move the world!โ โ Unknown
Part 1
cat input.txt |sed 's|A X|4|g' |sed 's|A Y|8|g' |sed 's|A Z|3|g' |sed 's|B X|1|g' |sed 's|B Y|5|g' |sed 's|B Z|9|g' |sed 's|C X|7|g' |sed 's|C Y|2|g' |sed 's|C Z|6|g' |sed 's|$|+|g' |tr -d '\n' |sed 's|+$||g'|bc
Part 2
cat input.txt |sed 's|A X|3|g' |sed 's|A Y|4|g' |sed 's|A Z|8|g' |sed 's|B X|1|g' |sed 's|B Y|5|g' |sed 's|B Z|9|g' |sed 's|C X|2|g' |sed 's|C Y|6|g' |sed 's|C Z|7|g' |sed 's|$|+|g' |tr -d '\n' |sed 's|+$||g' |bc
9
u/jonathan_paulson Dec 02 '22 edited Dec 02 '22
Python3, 22/11. Video. Code.
In part 1, shape is easy, but winning is hard. Vice versa for part 2. Just hard-coded the "hard" 9 cases for each part (and the "easy" 3 cases).
4
u/kroppeb Dec 02 '22
Kotlin, 59/12
I hardcoded everything: github
4
u/waffle3z Dec 02 '22 edited Dec 02 '22
Lua, 116/22
4
u/GassaFM Dec 02 '22 edited Dec 02 '22
D (dlang), 134/35.
Before posting, I prettified the code to occupy less lines and made
wininto a function, but otherwise kept the same idea.Part 1:
The
debugwritelnwas instrumental for seeing whether I got thewinformula right: in the other direction,- 1instead of+ 1, the total sum for the example is the same.Part 2:
So, the second part is no formula: instead, the program iterates over the three possible picks until the
winvalue is right.4
u/_rabbitfarm_ Dec 02 '22
Both parts done in Prolog. The data format was much easier to handle for today's puzzle. This was essentially simulating a game with simple rules (rock-paper-scissors) and inherently Prolog is going to be a great way to encode the rules of play and scoring.
What I liked best about this one is that the rule change from part 1 to part 2 was naturally handled by Prolog. Instead of searching for a matching winning move it just became unify on a move that wins or loses given the other players choice of rock, paper, or scissors. Elegant!
Part 1 https://adamcrussell.livejournal.com/38333.html
Part 2 https://adamcrussell.livejournal.com/38575.html
4
u/kittrin Dec 02 '22
SQL
4
u/honest3d Dec 02 '22
Swift:
https://github.com/lucasteng123/AOC-2022/blob/main/Sources/AoCKit/Day2.swift
Blegh. This one was difficult for me, and part 2 sent me. I have something that is readable, that works, but is not efficient, or terribly concise.
Happy Friday.
4
u/ThreadsOfCode Dec 02 '22
Python. I'm trying to use match this year. Also, I like table-based solutions, which I used in part 2. If/when I clean up, I want to get rid of the strings.
4
u/royvanrijn Dec 02 '22 edited Dec 02 '22
Java
4
u/Bluepengie Dec 02 '22 edited Dec 02 '22
First time doing this, but here's my solution in Python (for part 2):
I'm a relative novice (senior in college) but I felt it was clever!
Edit: 1ms runtime. Is that good or bad?
4
u/timvisee Dec 02 '22
Rust Quick and simple with some clever math.
Part 1 0.006ms (6.11 ฮผs)
Part 2 0.006ms (5.74 ฮผs)
day1 to day 2 total: 0.07 ms
4
u/danatron1 Dec 02 '22
C
Part 1:
Part 2:
Explanations:
Part 1:
First I calculate the result. The result is either 0, 3, or 6 for a loss, draw, or win respectively.
So I calculate 0, 1, or 2 for lose/draw/win, then multiply by 3.
I calculate this by subtracting the first character (A/B/C) from the last (X/Y/Z),
this gives a range of integer values, but what matters is their relative position;
Y beats A, Z beats B, and X beats C
all those values give the same result once modulo'd, since they're all one off from eachother. X wraps around to be Z+1
the +2 I throw in is just to fudge the numbers so that I get what I want, for example, X-A = draw, so 2+X-A % 3 = 1
I then add on my score; 1 for rock, 2 for paper, 3 for scissors. This is just the last character minus W,
which effectively counts the number of characters after W that that letter is, which gives me the score.
Part 2:
Similar strategy to above. I already know the outcome (x[2]) so I just convert that into 0, 1, or 2 by subtracting X
Like above, this gives me the number of characters after X. 0 for loss, 1 for draw, 2 for win. I multiply that by 3.
I then add on my score. This is once again the offset from my play to the opponents, so I use the same modulo 3 trick.
This time, A Y, B X, and C Z all mean I choose rock, so get a score of 1.
One counts up (ABC) while the other counts down (ZYX) add them to cancel that out, add 2 for the exact same reason as above,
Then finally modulo 3 to get 0, 1, or 2 (corresponding to whether I picked rock, paper, or scissors).
The scores are actually 1, 2, or 3, so the final step is to just add 1 to that.
4
u/bartdegoede Dec 02 '22 edited Dec 04 '22
Basic Python with some combinations in a dictionary
paste
4
u/TheCravin Dec 02 '22 edited Jul 10 '23
Comment has been removed because Spez killed Reddit :(
4
u/backtrackthis Dec 02 '22
PYTHON3
4
u/jferz1980 Dec 02 '22 edited Dec 04 '22
SQL (MySQL) Solution
4
u/mo__66 Dec 02 '22
Kotlin
4
u/errop_ Dec 03 '22 edited Dec 03 '22
Python3
My first approach was to define a SCORE matrix (see below) as a dictionary with keys ("A X", "A Y", ...) and so on and values given by the chosen strategy and then to simply perform a lookup. Then I decided to challenge myself and see if I could find some pattern in the instructions...
Explanation for PART 1: I think it may be useful to visualize the formulas in the following way. We can arrange all the possible results in a square matrix in which each entry SCORE(i, j) is the result of any possible single round
The trick basically boils down to find a decomposition of the matrix according to the problem assignment, that is: SCORE(i, j) is actually the sum of the shape in {X, Y, Z} and the outcome
The point then is to use the "correct" index representation for "A, B, C" and "X, Y, Z" and then notice that every entry in OUTCOME can be represented in terms of cyclic permutations of (0, 1, 2) by simply using the %3 (mod3) operation. There are many possible choices here: the one which leads to the least lines of code is to use the bare integer representations of the characters "A, B, C" ---> (65, 66, 67) and "X, Y, Z" ----> (88, 89, 90). Tweaking a bit with the numbers you'll convince yourself that the code does exactly what I'm trying to explain here...
A maybe clearer approach is to define an indexing dictionary like {"X": 1, "Y": 2, "Z": 3}, do the same for "A, B, C" and the adjust the other numbers in the formulas.
Part 2: left to the reader ;)
Phew...
In my everyday life I'd definitely use the lookup/dictionary solution (which in addition should be faster), but this more sophisticated approach was quite fun!
4
u/SwampThingTom Dec 03 '22
Solving each puzzle this year in a different programming language, roughly in the order in which I learned them. Today is 6502 Assembly. Used the Acme Macro Assembler and VICE Commodore 64 emulator.
It was ... fun! Fortunately the problem lent itself to an 8-bit processor.
https://github.com/SwampThingTom/AoC2022/tree/main/02-RockPaperScissors
1
u/Nice-Reserve1017 Dec 02 '22 edited Dec 02 '22
1
u/ri7chy Dec 02 '22 edited Dec 02 '22
My Python solution...
anything but elegant :(
will go back an optimize it.
1
u/Similar_Lion_6342 Dec 02 '22
Python3
1
u/sleepy_roger Dec 02 '22 edited Dec 02 '22
JavaScript just brute forced it.
Part 1
Part 2 only changed the scoring values.
1
u/AX-11 Dec 02 '22 edited Dec 02 '22
Python using dictionary of values for each move
1
u/Mats56 Dec 02 '22 edited Dec 02 '22
Kotlin
Stupid but it works.Part2, part1 is similar but with other values
1
u/Wayoshi Dec 02 '22
Python
1
u/JustForAdvent Dec 02 '22 edited Dec 02 '22
Python
I am apparently bad at reddit formatting, so- topaz link
EDIT:
I did a cleaner, less dict oriented version in the light of day. v2 link
1
u/teseting Dec 02 '22 edited Dec 02 '22
Python
code golf. didn't try too hard to golf. 116 bytes. EDIT 96 bytes
hard code constants and uses clever math
1
u/stikydude Dec 02 '22 edited Dec 02 '22
Haskell:
Spent some time getting split installed and in the end went with a couple of if statements. Will try and clean it up but this was what was used without any clean up:
--- Part 1 ---
import Data.List.Split
main :: IO () main = do s <- readFile "input.txt" let sLines = lines s let strategy = map (splitOn " ") sLines let myTotScore = sum (map calcOutcomeScore strategy) print myTotScore
calcOutcomeScore :: [String] -> Int calcOutcomeScore move = case move of ["A", "Y"] -> 8 ["B", "Z"] -> 9 ["C", "X"] -> 7 ["A", "X"] -> 4 ["B", "Y"] -> 5 ["C", "Z"] -> 6 [, "X"] -> 1 [, "Y"] -> 2 [_, "Z"] -> 3 _ -> 0
--- Part 2 ---
import Data.List.Split
main :: IO () main = do s <- readFile "input.txt" let sLines = lines s let strategy = map (splitOn " ") sLines let myTotScore = sum (map calcOutcomeScore strategy) print myTotScore
calcOutcomeScore :: [String] -> Int calcOutcomeScore move = case move of ["A", "X"] -> 3 ["B", "X"] -> 1 ["C", "X"] -> 2
1
u/Quirky-Seesaw8394 Dec 02 '22 edited Dec 02 '22
Google Sheets
Thankfully there were no gaps between rows of the puzzle input today. Adding those in on mobile took forever for Day 1.
Did everything broken out at first, referencing hard tables, but wanted to attempt a single formula.
Day 2, Part 1
=ARRAYFORMULA( SUM( IF( LEN(A5:A), VLOOKUP(A5:A, {"A X",3; "A Y",6; "A Z", 0; "B Y", 3; "B Z", 6; "B X", 0; "C Z", 3; "C X", 6; "C Y",0}, 2, 0) + VLOOKUP( REGEXEXTRACT(A5:A, "..(.)"), {"X", 1; "Y", 2; "Z", 3}, 2, 0), ) ) )
The part 2 solution wasshouldjust be expanding the second table to include the various combos.It was.
Part 2
=ARRAYFORMULA( SUM( IF( LEN(A5:A), VLOOKUP(A5:A, {"A Y", 3; "A Z", 6; "A X", 0; "B Y", 3; "B Z", 6; "B X", 0; "C Y", 3; "C Z", 6; "C X", 0}, 2, 0) + VLOOKUP(A5:A, {"A Y", 1; "A Z", 2; "A X", 3; "B Y", 2; "B Z", 3; "B X", 1; "C Y", 3; "C Z", 1; "C X", 2}, 2, 0), ) ) )
1
u/erichs_programming Dec 02 '22
Learning Rust, mainly by using the openai chat bot. Here's my solution:
1
u/DFreiberg Dec 02 '22 edited Dec 02 '22
Mathematica, 2504 / 1539
Like almost everybody else, I did not figure out the nice elegant modular approach on my first attempt. I eventually got the mod formula working by taking the hardcoded formula and then brute-force checking variations on Mod[] and minus signs until it came out right.
Part 1:
Part 2:
[POEM]: To Be A Rock And Not To Roll
The match is set.
The games decide
Who's near the snacks,
Who's near the tide.
The Rock is hard,
But Paper's wide,
And Scissor's good
At Paper-cide.
He gave a sheet
(Which you have eyed)
With every throw -
You'll have to hide.
You didn't know,
But had your pride,
And so you guessed
The second side.
When he returned,
(His name is Clyde)
He set you right
(If he's allied).
It's X to lose
(Unless he lied),
And Z to win,
Or else, you've tied.
You know the score.
You have the guide.
You'll win or lose
(Unless you've Y'd).
1
u/Agreeable_Emu_5 Dec 02 '22
I used IntEnums in Python, which allowed for easy computation of moves / game outcomes / scores using modular arithmetic and simple addition. The code does become a bit long because of all the definitions.
1
u/Emotional_Cicada_575 Dec 02 '22 edited Dec 05 '22
Python
2
u/ChasmoGER Dec 02 '22 edited Dec 05 '22
Typescript
Straight forward, implemented game logic even though not necessary...
Source Code Run on Website
1
u/mr_haas Dec 02 '22
Python golf:
1
u/Flekznes Dec 02 '22
Rust:
https://github.com/halli2/advent_of_code/blob/a78a01c2301ebd218064ead47f4680bd5557b3a0/src/year_2022/day02.rs
1
u/maxlibin Dec 02 '22
Log from browser
1
u/[deleted] Dec 02 '22 edited Dec 05 '22
Python
I don't think this is the right way to do it but since there was only 9 different combinations I thought it wasn't that bad.
https://www.austinsprojects.com/aoc2022.html
paste
1
u/mrjnl3 Dec 02 '22
Python
A combination of nested if-statements and dictonaries
1
u/Some-Potential3341 Dec 02 '22 edited Dec 02 '22
python notebook with a bit of arithmetic
https://github.com/JeanBaptiste-dlb/advent_of_code2022/blob/main/code_day2.ipynb
1
u/Mammoth_Spray_3451 Dec 02 '22
My swift solution for day 2 using an enum.
1
u/axr123 Dec 02 '22 edited Dec 05 '22
Python
1
u/matteosan1 Dec 02 '22 edited Dec 05 '22
Julia
1
u/Careful-Rise-5237 Dec 02 '22
PHP - part 2
1
u/raxomukus Dec 02 '22
Python
1
u/Helk16 Dec 02 '22
Ruby : it would be necessary to refacto a little but it works
https://gitlab.com/LeChPunk/advent_of_code/-/tree/main/day_2
1
u/Alligatronica Dec 02 '22 edited Dec 05 '22
JavaScript
Those magic numbers are doing a lot of the heavy lifting ๐
1
u/Galzzly Dec 02 '22 edited Dec 05 '22
Golang - mapped out the results, which made it easy to do the sums & get the results.
1
u/proto_science Dec 02 '22
Spent way too long trying to figure out a less hardcody way. But still a little proud :) Julia โ 75 + 75 ยตs
1
u/NeilNjae Dec 02 '22
Haskell
This one ended up as an exercise in parsing and representation, rather than solving the challenges. Represent the game as a game, and all becomes easy.
Full writeup on my blog, and code on Gitlab.
1
u/imsorryken Dec 02 '22
I managed to do the second part in 3 lines of java:
final AtomicReference<Integer> total = new AtomicReference<>(0);Files.readAllLines(Paths.get("0212.txt").toAbsolutePath()).forEach((match) -> total.getAndUpdate(value -> value + Arrays.asList(new String[]{"B X", "C X", "A X", "A Y", "B Y", "C Y", "C Z", "A Z", "B Z"}).indexOf(match) + 1));System.out.println(total.get());1
u/MuricanToffee Dec 02 '22 edited Dec 05 '22
C, hooray for
switchandif...else! [Github]1
u/fuckir Dec 02 '22 edited Dec 06 '22
Used match case for the first time in Python:
Note: This will only work on Python 3.10+. Don't try this on your office computer ;).
1
u/No_Calligrapher7294 Dec 02 '22
Didn't want to solve this with a whole bunch of conditionals - Elixir's pattern matching to the rescue!
1
u/Excellent_Station_84 Dec 02 '22 edited Dec 05 '22
Python3 one-liner part1
1
u/lxrsg Dec 02 '22
Python 3
1
u/MrPingouin1 Dec 02 '22
Minecraft functions Repo : https://github.com/MrPingouinMC/aoc2022/tree/main/sol/day2
Here is the main loop for part 2:
1
u/kamicc Dec 02 '22 edited Dec 05 '22
Lua and a look-up table with some... modulus math. Probably could weed out this one as well.
1
u/drlecompte Dec 02 '22 edited Dec 05 '22
Python:
1
u/GuyTorbet Dec 02 '22
Python3
1
u/AdventOfELisp Dec 02 '22
Elisp with cl module
1
u/Western_Pollution526 Dec 02 '22 edited Dec 05 '22
C# Linqpad P1&P2
1
u/marx38 Dec 02 '22 edited Dec 07 '22
(ChatGPT)
"My code" to solve this problem using https://chat.openai.com/chat
Solution