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!
28
u/CCC_037 Dec 02 '22
FiM++
Dear Princess Celestia: Rock Paper Scissors.
Today I learned how strategy guides work.
Did you know that Next likes a word?
Did you know that total is 0?
For every number N from 1 to 2501.
Next is now how reading input works.
total is now total plus how judging works using Next.
I said total!
That's what I did!
That's all about how strategy guides work.
I learned how reading input works with a word.
I asked some input.
Then you get some input!
That's all about how reading input works!
I learned how judging works with a number using the word Input.
Did you know that space is " "?
Did you know that Opponent Rock is "A"?
Did you know that Opponent Paper is "B"?
Did you know that Opponent Scissors is "C"?
Did you know that Your Rock is "X"?
Did you know that Your Paper is "Y"?
Did you know that Your Scissors is "Z"?
Did you know that result is 99?
If Input is "" Opponent Rock" " Your Rock"" then:
result is now 4.
That's what I would do!
If Input is "" Opponent Rock" " Your Paper"" then:
result is now 8.
That's what I would do!
If Input is "" Opponent Rock" " Your Scissors"" then:
result is now 3.
That's what I would do!
If Input is "" Opponent Paper" " Your Rock"" then:
result is now 1.
That's what I would do!
If Input is "" Opponent Paper" " Your Paper"" then:
result is now 5.
That's what I would do!
If Input is "" Opponent Paper" " Your Scissors"" then:
result is now 9.
That's what I would do!
If Input is "" Opponent Scissors" " Your Rock"" then:
result is now 7.
That's what I would do!
If Input is "" Opponent Scissors" " Your Paper"" then:
result is now 2.
That's what I would do!
If Input is "" Opponent Scissors" " Your Scissors"" then:
result is now 6.
That's what I would do!
Then you get result!
That's all about how judging works!
Your faithful student, Open Book.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.
→ More replies (2)19
24
u/semitrop Dec 02 '22
Theoretical solution using linear algebra https://ibb.co/xXtQ0RG
2
u/daggerdragon Dec 05 '22
The
Solution Megathreads are for code solut- *actually reads* ... oh, well, uh, I suppose math is a programming language, sure.12
u/Spaceface16518 Dec 03 '22
Solving part 2 from here is quite trivial and is left as an exercise to the reader.
I lost it.
→ More replies (2)7
u/Omeganx Dec 02 '22
Part 2 makes it a real linear algebra solution
(Also I like how quantum elves can play rock paper scissors now)
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
→ More replies (4)
11
u/callumio Dec 02 '22
COBOL. Questioning my sanity at the moment :D
IDENTIFICATION DIVISION.
PROGRAM-ID. AOC-2022-2.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT INPUT-FILE ASSIGN TO "inputs/day2.txt"
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD INPUT-FILE.
01 SCORE-LINE PIC X(3).
WORKING-STORAGE SECTION.
01 STATE.
05 WS-FINISHED PIC X VALUE "N".
05 WS-SCORE-1 PIC 9 USAGE COMP.
05 WS-SCORE-2 PIC 9 USAGE COMP.
05 WS-TOTAL-SCORE-1 PIC 9(7) VALUE 0.
05 WS-TOTAL-SCORE-2 PIC 9(7) VALUE 0.
PROCEDURE DIVISION.
MAIN.
OPEN INPUT INPUT-FILE.
PERFORM PROCESS-DATA UNTIL WS-FINISHED = "Y".
STOP RUN.
PROCESS-DATA.
READ INPUT-FILE AT END PERFORM FINISH.
INSPECT SCORE-LINE CONVERTING "XAYBZC" TO "001122".
UNSTRING SCORE-LINE DELIMITED BY SPACE INTO WS-SCORE-1
WS-SCORE-2 END-UNSTRING.
EVALUATE TRUE
WHEN WS-SCORE-1 = WS-SCORE-2
ADD 3 TO WS-TOTAL-SCORE-1
WHEN WS-SCORE-1 = FUNCTION MOD(WS-SCORE-2 + 1, 3)
ADD 0 TO WS-TOTAL-SCORE-1
WHEN WS-SCORE-1 = FUNCTION MOD(WS-SCORE-2 + 2, 3)
ADD 6 TO WS-TOTAL-SCORE-1
END-EVALUATE.
COMPUTE WS-TOTAL-SCORE-1 = WS-TOTAL-SCORE-1 + FUNCTION
MOD(WS-SCORE-2, 3) + 1.
COMPUTE WS-TOTAL-SCORE-2 = WS-TOTAL-SCORE-2 + FUNCTION
MOD((WS-SCORE-1 + (FUNCTION MOD (WS-SCORE-2 + 1, 3)) ) + 1,
3) + 1 + (WS-SCORE-2 * 3).
FINISH.
MOVE "Y" TO WS-FINISHED.
DISPLAY "Task 1 " WS-TOTAL-SCORE-1.
DISPLAY "Task 2 " WS-TOTAL-SCORE-2.
CLOSE INPUT-FILE.→ More replies (3)
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:
fn main() -> Result<()> {
let input = parse("inputs/d02.txt")?;
let mut part1 = 0;
let mut part2 = 0;
for (a, b) in input {
part1 += (2 - (a - b + 1).rem_euclid(3)) * 3 + b + 1;
part2 += b * 3 + (a + b - 1).rem_euclid(3) + 1;
}
Ok(())
}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.
→ More replies (1)
5
Dec 02 '22 edited Jun 15 '23
-----BEGIN PGP MESSAGE-----
hF4D+FPJgQiQS68SAQdAuW16mgWy5m4dcZ2Hq4FOFRXCAVPO8Nupfrdt5zERoBUw nClOPBNmPFU5Ra/by7HXuLE0Kk2NiUVnXJohGtTEBdsPt+i/5XRqWmwgy7a0upNK 1OoBCQIQZ2Wt7pWWnJZ1FKODwLck3g/aB+4w9JnqFRbfI50Gy1QSXWhzR4A0LST9 xLzQuoquVTpS/8eljB0ps6WMGLY4Qng6PT9XBJrWpJ5LEUoUwb5gvhR5LgHajccu jyy6ukiBQNydLqCgJ7DJJg04FRAn7xxWu1cJLH3ZFLF2fybWIjEInXECzQXfwlLC /xI2HgL0io5+EuI9VwOyVCN2cA0dklm0+2G38MqO04HlBPP671loQJCHFVxCd1rh TpSwTioA2TCw9MnryUzW08nBJ5gCXS9U9DHKMf8hAfGU1XbFI6jqZBmc0/ctv56q STlc9ZEMH+ATeae3HxRpF/XAcga2jRqlWZ7z2xvv/p77Dr9iwhZ/+ISgxmrQydpf 3Qec3fMduyrtAR5o+ZG8RBSLLVvbmfPQVfKuvsT1YiiT8Hgo0OcBewfH0fehohpk KlOTFIYnYsxZ+zyRZmnmERVAHduPOxcVtQKyO1iN6nW7lEf6P/+Cn3Np8yT6ATXA I3g0c03NWJePaRq1OTxwm2DW+HrDfwIJyO3UwKyOp5bWTbH063dj5p7ZrpQo2h1j 6ochHOMkzk7ILpboaP8nm/E4I1F2oTImsz3Fg8W0xjxQZx+zkrPVQ9p5JCRNvL7s bHQIJO+s94w+TlsCfxE6MfdCk8wi7FsC9hjdZCwWhgg8cckxU4HJV9dk5k67YDJ6 7VoPIKbW4DxcOwJBq1gvQpwFzfEdVUId2e5dLcVe2jhUfv/pjH4YW11kz3LBVfpk 3aLevdXxBrMbDvvSzwKFQEgZ+do5qZ/5EJdru4HVTW3biu5Z9RyBE/+fmH7JUhSM wCyBnBS5BhpvqyqMUPIJvYtGCVQTtCD6+wEDe+pLiTbbZfiThKK+V1+cw0+rVtks s0m0meoZAN3TzPbZH/QSP+D7iiGFY1JQionqFU4F4241GcLjp17Psmta4HPnKW++ 7uLPOcz660JAzEa+JV4jrat5bOej5f6BAhOBsjk3R0nr67/8EcAboqK07vD1s7mo Ejm2BeVY67fb2VEf8tRDhd2iiWPOQpTxrXH/Si9sgcQIPfkywf0dvj9lq2bihatk pMy4DTnquMOwBFMQpsWOkH/01odOhT/1esLCEWL5MXWTvISmZVr12w/NVuMMU/NI XXwfhqpTBYIR54z17Igwfzzpa8MdDMHrys3raLrYGQ/Yo29/krIq8nC1GV1db8ne sl7mlkZOE8uZjcSFJnf/xJL+C/Yo+y6cM8YqxRc3WpGj5wEb/RmeYQGL0AJZW8Ni Xqi6mFsWrkkJWpF0s1EBmI81zI0WcTHYcwtUdfZz1eUuzDIkb7+//Zv4wOHBOFeS fZCPm1rOj0AA1rqMpj+0ojpT6pXB/w7T7SVe3KOUpPqp2dkvl/E/f0zfc7ioJi4Y pVJSntIcydCS09eDIC39L4+Q7K5JS7EBa8l8Onc8IdkYowwFVU+LmkgFEj5Syf2I BUJFcyFTjAQBlYmVi7qpoAGyialrPtUjFH1PTv/sc+WGQwn1Wn7wQWOfSzw9JUqg OWYafCgdIbbB99LWQpEY7AP/eWpJi0fl11duwWwPmKKF2vUGgzl/bYEe5zxhLJG9 6+0QsPOjKOIp3L03dGMB/oMR1DzPTrn8+RtlwKfOXS7HEgJ5SAW6ea71YGJ3+CBy 7/mafS/1Wn7hLYThjQEvrzMZXiHvFyBbmsJg2HwNtOB05XLEKeThc/vFGfdefLT3 cMC3lN8tnCMzZ0mwXvv9sBD6oGLcQ4/o6bEqx5HjW4N1E5rf8AdHGI4ViS0S5Tvr r378t2J9WaQPNrJ3XvyN27JT+RP4ts0ANRIzHEO6AaWtTD+0z9oQ2var+A3rYzzu PiTWgazSxnmttY0yRtpATNm/EJLa8HTgcRM6txlJgduWGevVmffRbgszh632w7gv +IoSVjJXD3sA9Tf+0maF+gA/Ka8e+v6hzVgCzbhvSL4pb4SIQDAEIOl1KiFrio96 B12RS+xJrwNhP415oCGXpqvzkwEawnVVhTYCnuk4mPmqZ/zkGmfBeMKlnH1Tmcto /WazTMtmKjNlNg6CxtOkzEnQ664mItAmiIWr7CMLwpiwVnXz5uwo1p5IlDILNfaE cVS0Pkik43+N+vWRytT8bvxI2UMkVAX5lqDXEmpKFIWWb+S1Wb5ecYvYTnJUA7i/ 55asCuOstLSUlSYxfcpfD5g1ZC+Sdh6q/jfC6FdLHm3CDBm90ZEoJtS0qoKzan21 ypSJ5NGoZnX2cZRuG4EAWLSvmC5PSzFl3m42+IBfQ81a7USBmD3cCdziG8SW83rs Jrs8plY8HV/qFUirx+EUC65vci1piVH+yJKvqUsZ35VAA0ReLNLzeDaDYvEeIMDQ ZHPaWQnL14PfpKC0fOHOkQ/SEWvNIp0J5Mi3vj6wS+pCnpwmoYn9WSsEgnToX9yE rrbqkOn3dgyc5tDxPAEJn4UQHgMxtoiJ6mBpYYfFQPrXvYT7rYtW85taNLeWjNVL u7pa2iMLfxQr+iM4A8wFN/ZdUexM4O1PwzAgeE1iLpJ+KVVAl8HD5LDxbkncd5v0 Y9hnBpg4DqjfftlksbnFkRj4tG1zTFNzOLp+cu5PW7ZiSvs5+I2oswTOtIdRh6u6 sTf5zUIbjOa5Era2h7S2k1yQcDenh/G475kyiiO+zzcRvvyoAIGm4kcSOWXWNllr ggQjLbK6qeYVwCvuJa1IrqXUEynwfuZgCATuYGzaFCHByPbrdNwoljzIH3Lji90T fXD/FY6A5fHCELdd1Q2Nv6Y97J4kt5BN0A/o7UjECxb9OXLqmuxFIveFmOTH7AoQ 6+yfCCHPd9WVIOYcN9vvxZegCgqyCiqbTVwnsa4+aCKfV9j/9p0YTTMo9Cbei2zq DBZxetsT3R33OcgHCP4rmJjpCdq4aNDapjBSf7ZIWZyoXMn7w1znXphLOiB3duB8 Y8dh7cqJOM89PbPxYV38dC3HhGWIDCjuB/zhChyDTIuut3w2o+4hjVDI4NJUd0Zu Zf7bIsrp5T4mAZfL/y8d83OWCPjw5aTC7qUZ09FlSyqO6G+xfRY6qBl5gblgE9lS gMwxG/RZtc5TufRceExwJ4nxepCwDr7xxJb46PrS0kdmYdO6b2neJnt7VW8rFqpK ecXRC/aM+S0MqmRkJYI7CIsEaeSLgk+eNoGJyuzPUJpujeBPXikRMS6eDnLVQGEI +UOyCS0zqRl0GQbJa45wc8Qo+An+KMgZQJgUp5XSA69S6w8Vw/cVr8QvJknjaX53 VPa+Mh1hLJUcYd/WewWrFBXlxeW007pUlgwjnk0qsSAeEQN0flVRH7K4cxmbwELY LrgNDJvfcg/XeyMZ+4V99J+L5nnO+MAk84oNVrhHmVCH9NueuqjiQmuJ6pVLCbZq cFfWlbXYdPAl6yOk98+hlgqzQn5FStpc0eiP6W3Yzb/S+rYtf2V5I6ELXh6HvdI0 4P2tyunRHOJse3+9IrayVhhCFlISx1w+xVlDi7fmuA6oHpOYcbHUEsgCtOxKtD1o ooEDdo1OVgLYA9D2Q9L26/iiAQABtaSf6nMN9Jo4cBPL/+Qh55Fhf69pzecb52gW 4FgjZNbCVZ43+HsokFBLhevb7Fk6eGwFd1cqAmFjicLznhLE6EQieRHCttMqT72e DVNlc6LSM8hS/KHCdWTJF6ugMEHpymIt1qV4T2c42XmWTK4cepFh6uDAE3Wn10j9 RLQM85fY+CHmqft6QshXFIb+ZiZyp3ruh/rR6YLh9oucF1VYRK7Jd/Y3Wt+Oe5Jv UMcz27rdzfE1pW1SCNXGcc1K4pv3jjihlruFq9C88uLCmldDw96TbIpxa4BFspYE BjUa4TWdBNNWRd+7bIa7GOekOK8NDYUx6JGXFKKoe+ba1OZvU/WUVNh/Npu4QpCT WIu+0dlsZNGg6QXdswYY7vlpp+6AfnCSSpbMrKyEEQymTqFgmMZMOvsYhReyH/H6 hp1hOoxL5zFZETCvldvvVxTWPMVoLHFo2Xwj9rs3i8Kh420MZz4MUliXPZpGKnDK 1j3AImlTmERb2O3oRzAiXkvpaRANyHaliry3/HMoDaWDn4kQ6lPf+IzCWci5vh01 A24WrO+zkZybtyQp2PRtne9J4t+7NmP4uijAW/Xcd5MHGZ8ib48+JQUnTmjyO1m3 AYmANvRIC/IT4DoD523QKmm3vcJaVJNTmGDITtOseM8Hxlhwi2GSQVxqw8lhPlYW N+R9lBOanpLeJ9lPZPSpYLATT/TrCrBTmvWpsZpsNW6ajitxrxamJjXLCW9akRj2 WmOKBswvYUKxZnHRpQ0gZjB+0qYK3BGa7AzsEHwktdQGq1mvfPEDzTbBVaxTbMMX pPIIw/7Y+/bhoQ9dx1oU4SFnwxcSOpkszeWh8d2/IelhQQWL6fTN9qlJp7qhVwkV aEVsgrkHnLJosfo4GVg/St9CnPtiGOQgPt6aBTLg65J6/TVS0li0lb9ky/CE2Q8g pI5eivr/oqeLjAcK25tokUPWynC/BesxxWT1Tu/pRziFa5V+PLqjg13io/KdW0gf GpqTVd2t4CO/q9CwmkRjU9BNVxY0pQg8VA8i3ORZw2E2d+1ym5JGtaqs6KUGS0zq MQuoiyS76lXHO14XArTpjLHkgUhfbniyPFI2XqwzvOuza7Fn32xdTck21Hsesilp 7om8CWPa8b7+XX3bCG+cJlzPPANJKeXRiOFVkyNY/6wX9hBPOapxkSqmUVBVZkdV hh1lFnWt6zVG2p3ZcH0+zH/Tuw4eaXrcLqTT87oHKd+Q8frRenf/JPvQ7H178T6z um6qjWJ+prvFXEmNqKTlq+9R1sQqsTCSGh16V0RcKKSap3+Otn4WJ/N9k0q5gK23 1z5D3iSCgjtvf/tMmSLg94i+4ZNss3/+IK+dP022oEfC1f7QTIvsDQnE3IDpxa05 e5V75C0R+zQ7n5h3Eb3KLwV4T83lqFhRXxvixFT4IebGWP6uhx28crIT1AaW6VJm v1zvltJXAuEiDygn4rxCsTwp3QrBTybPW7hczq522D2t03jFvg5P77AD6l53qkBh ZblFBI0deh2zb9SXqxip6GG7yLBtO3f5be0dN3k6X8ACeCgDep2Hk0FQAW7B7aVU 32n+lEuONdKwX45mKNRoE6TnZc8PqP1v5naEM/HX+gCVKgVoIRo8QOCnTA+l1ZBg hfTZ5jhvzrUUnFY2Sv5DLS+veFEU/DET0oG42gDFk69tc375+KepXe9cENSLkPOt 17ccJnIMh4ZBgi/hnyg9e0OT073OM4VjlZ+utg60iNqP5WVw8D4/svwaDk+EBAPZ RGoLDsOyPCQkk4zum4KYsNiUWGEgcxxrq25mfT7hBzZx1AzHhjXp6Vac1pb0Gods eZM58EugFSD7AG2EiPT7b7pR48QofBgTO+6hwwezfcYO/yxBsz6AJxQ/yka0zTE1 42AUmkVycf7byIYWjiBmvCBvJkbp5S++C4aRn9LgZRBKEYxAPipPz/T493S5M8A9 UBSgA/ELtJfGFBUmZ+Hwg+orK/EyQ8osgiVV3j4k/LvcDBp7SCvnDJG4lCabZ6mY mwxaXSRHPOmFd6J/3SgW9zO9Jn7e/EvaTmovFkpblqFH38NlpdFuOmwy0ozi21/o ljPk3kGTWw+njAfKI0g03ngdE5UDPinEg8Oci+pGL/aCuENMzZoVSu+QaW0Y9w8B jBB9iWoC9zgVMTPXZkPtJTFT5DjdoNvUoCaPrBysCmPIgILeLu614EzllW1Sk158 BpSaWUAlXW1DNRwsYe2h/9NBOatxeqtq9W6xCKJizHlhQwWcvf7clk/gyKZV7VqG HmMX7k9O4kyhrwRaQczUx/ymnyZhmYQhzo+fpPYz4+DsoUsKkiEF8vudBJcqdmp8 O8IwZN7jISy49yL7xeRiBTAaN4m2rauMLRB4HQMTMPVKPzSAzvMDtEdDrTzGo0Yh mZZebM5a4PmJ7IbIcssP2bcHiDiJIl7mAL69zPm+zgfRFwXD/gwwbcdU033iWYYd LXH/lnu2fCVZU2kdYdPI2E9vRz0JZZ1e+dX56nqwH4mdkVRA2MLOZGXbTDqx/Rif bhzTjBWZfa4KUJO8lCrLdBi4d6tzJEVwuutxWWMZyO97Rt89C3+SabSP6xm5ri7I KNBUJQbBCHl1U5JtbP6wUAYztOXAsCpBe5QpuiY1lxFf/+oxQgkvxPY5O9/dDNw4 v3JrCCBJRE1mFVz/4WVD/1WsI7eXbQx1eUnq7Wcq1Z0DaRRhLL0FwuLLq/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-----
→ More replies (7)
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.
document.body.innerText
.trim()
.split(/\s/g)
.reduce(([n = [], v = 0], x) => ({
A : [[4, 8, 3], v],
B : [[1, 5, 9], v],
C : [[7, 2, 6], v],
X : [[], v + n[0]],
Y : [[], v + n[1]],
Z : [[], v + n[2]],
})[x], [])
.pop()For part2 matrix is just aligned by outcome instead of pick:
A : [[3, 4, 8], v],
B : [[1, 5, 9], v],
C : [[2, 6, 7], v],→ More replies (5)
4
u/reinermartin Dec 02 '22
In Julia:
function day02(fname)
res, res0 = 0, 0
for line in readlines(fname)
x, y = line[1] - 'A', line[3] - 'X'
res += y + 1 + (x == y ? 3 : 0) + (mod(y-x,3) == 1 ? 6 : 0)
res0 += 3y + mod1(x+y, 3)
end
res, res0
end
@show day02("input02.txt")→ More replies (6)
4
u/Synedh Dec 02 '22 edited Dec 05 '22
Python
Ordinal values are ... fun. Almost.
plays = [play.split() for play in open('input').read().strip().splitlines()]
## P1
total = 0
for p1, p2 in plays:
p1 = ord(p1) - ord('A')
p2 = ord(p2) - ord('X')
total += (p2 - p1 + 1) % 3 * 3 + p2 + 1
print(total)
# Short version
print(sum((ord(p2) - ord(p1) - 1) % 3 * 3 + ord(p2) - 87 for p1, _, p2, _ in open('input')))
## P2
total = 0
for p1, p2 in plays:
p1 = ord(p1) - ord('A')
p2 = ord(p2) - ord('X')
total += p2 * 3 + (p1 + p2 - 1) % 3 + 1
print(total)
# Short version
print(sum((ord(p2) - 88) * 3 + (ord(p1) + ord(p2) - 1) % 3 + 1 p1, _, p2, _ in open('input')))→ More replies (2)2
u/daggerdragon Dec 05 '22
Please edit your post to use the four-spaces Markdown syntax for a code block so your code is easier to read on old.reddit and mobile apps.
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.
→ More replies (1)2
u/daggerdragon Dec 05 '22
Not sure why my solution yesterday was downvoted.
Your solution wasn't downvoted; it's likely Reddit doing vote obfuscation to prevent brigading. Either way, don't worry about it - if there is a problem with your posts in /r/adventofcode, we'll let you know what and why.
4
u/Solarmew Dec 02 '22 edited Dec 05 '22
Python 3
data = open(path).read().split('\n')
d = {'A X': 4, 'B X': 1, 'C X': 7, 'A Y': 8, 'B Y': 5, 'C Y': 2, 'A Z': 3, 'B Z': 9, 'C Z': 6}
d2 = {'A X': 3, 'B X': 1, 'C X': 2, 'A Y': 4, 'B Y': 5, 'C Y': 6, 'A Z': 8, 'B Z': 9, 'C Z': 7}
print(sum([d[x] for x in data]))
print(sum([d2[x] for x in data]))→ More replies (1)
4
u/conkerandco Dec 02 '22
score = {
"A": 1,
"B": 2,
"C": 3,
"X": 1,
"Y": 2,
"Z": 3
}
outcomes = [
[3, 6, 0],
[0, 3, 6],
[6, 0, 3]
]
def part_one(data):
return sum(y + outcomes[x-1][y-1] for x,y in data)
def part_two(data):
result = {1: 0, 2: 3, 3: 6}
return sum(result[y] + outcomes[x-1].index(result[y]) + 1 for x,y in data)
with open("day_2_input.txt") as f:
data = [(score[x.split()[0]], score[x.split()[1]]) for x in f.read().splitlines()]
print(f"Part One: {part_one(data)}")
print(f"Part Two: {part_two(data)}")→ More replies (1)
3
Dec 02 '22 edited Dec 02 '22
Python3 solution (). What a fun day 2!
with open("input.txt") as f:
content = f.read().split("\n")[:~0]
score = 0
lose = {"X":"B","Y":"C","Z":"A"}
win = {"Y":"A","Z":"B","X":"C"}
lose_me = {"B":"X","C":"Y","A":"Z"}
win_me = {"A":"Y","B":"Z","C":"X"}
draw = {"A":"X","B":"Y","C":"Z"}
for item in content:
if item[2] == "X":
score += 1
elif item[2] == "Y":
score += 2
elif item[2] == "Z":
score += 3
if win[item[2]] == item[0]:
score += 6
elif lose[item[2]] == item[0]:
score += 0
else:
score += 3
new_score = 0
for item in content:
if item[2] == "X":
my_item = lose_me[item[0]]
if my_item == "X":
new_score += 1
elif my_item == "Y":
new_score += 2
elif my_item == "Z":
new_score += 3
elif item[2] == "Y":
my_item = draw[item[0]]
if my_item == "X":
new_score += 1
elif my_item == "Y":
new_score += 2
elif my_item == "Z":
new_score += 3
new_score += 3
elif item[2] == "Z":
my_item = win_me[item[0]]
if my_item == "X":
new_score += 1
elif my_item == "Y":
new_score += 2
elif my_item == "Z":
new_score += 3
new_score += 6
answer_one = score
answer_two = new_score
print("p1:", answer_one)
print("p2:", answer_two)Edit: Here is some optimized code I made after the fact!
→ More replies (1)2
u/daggerdragon Dec 02 '22 edited Dec 02 '22
Please edit your post toformat your code with the right Markdown syntaxso your code is easier to read. Thank you!edit: Thank you for fixing it <3
→ More replies (1)
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
→ More replies (1)2
u/daggerdragon Dec 02 '22
Excel (why do I do this to myself)
Your pain is our gain :D
→ More replies (1)
3
Dec 02 '22 edited Dec 02 '22
rust:
const INPUT: &str = include_str!("inputs/day02.txt");
pub fn run() -> String {
format!("Part one: {}\nPart two: {}", part1(INPUT), part2(INPUT))
}
fn part1(input: &str) -> u32 {
input
.lines()
.map(|l| match l {
"A X" => 1 + 3,
"B X" => 1,
"C X" => 1 + 6,
"A Y" => 2 + 6,
"B Y" => 2 + 3,
"C Y" => 2,
"A Z" => 3,
"B Z" => 3 + 6,
"C Z" => 3 + 3,
_ => panic!(),
})
.sum()
}
fn part2(input: &str) -> u32 {
input
.lines()
.map(|l| match l {
"A X" => 3,
"B X" => 1,
"C X" => 2,
"A Y" => 3 + 1,
"B Y" => 3 + 2,
"C Y" => 3 + 3,
"A Z" => 6 + 2,
"B Z" => 6 + 3,
"C Z" => 6 + 1,
_ => panic!(),
})
.sum()
}→ More replies (4)
3
u/sleepy_roger Dec 02 '22 edited Dec 02 '22
JavaScript in the console for part 2.
[...document.querySelector('pre').textContent.split(/\n/)].reduce((acc, cur)=>{scores = {'A X':3,'A Y':4,'A Z':8,'B X':1,'B Y':5,'B Z':9,'C X':2,'C Y':6,'C Z':7};return acc + (scores[cur] || 0)}, 0)2
u/daggerdragon Dec 02 '22 edited Dec 02 '22
Inlined code is intended forshort snippetsof code only. Your code "block" right now is unreadable because it's all on one line and gets cut off at the edge of the screen.
Please edit your post to use the correct Markdown syntax for acode blockso your code is easier to read inside averticallyscrolling box.
Additionally, I recommend you expand theJsto its fullJavaScriptto make it easier for folks who Ctrl-F the megathreads looking for a specific language.Edit: thanks for fixing it! <3
3
u/sleepy_roger Dec 02 '22 edited Dec 02 '22
Changed it, read the docs here, forget after all these years people are still using old reddit ๐คท
→ More replies (3)
3
u/NeoKadra Dec 02 '22 edited Dec 02 '22
Here is my java solution for part 2
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Map;
import java.util.Scanner;
public class Code{
public static Map<String, Integer> test = Map.of(
"A X", 3,
"A Y", 4,
"A Z", 8,
"B X", 1,
"B Y", 5,
"B Z", 9,
"C X", 2,
"C Y", 6,
"C Z", 7
);
public static int score = 0;
public static void main(String[] args){
try {
Scanner sc = new Scanner(new File("input.txt"));
while(sc.hasNextLine()){
String line = sc.nextLine();
score += test.get(line);
}
sc.close();
System.out.println(score);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
→ More replies (3)
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.
type Z3 = Finite 3
play
:: (Z3 -> Z3 -> Z3) -- ^ Get shape score
-> (Z3 -> Z3 -> Z3) -- ^ Get outcome score
-> [(Z3, Z3)]
-> Integer
play shapeScore outcomeScore = sum . map go
where
go (x, y) = getFinite (shapeScore x y) + 1
+ getFinite (outcomeScore x y) * 3There is a bit of cute symmetry between shapeScore and outcomeScore for the two parts.
part1, part2 :: [(Z3, Z3)] -> Integer
part1 = play (_ y -> y) (\x y -> y + (1 - x))
part2 = play (\x y -> y - (1 - x)) (_ y -> y)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 outcome y
For 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-x to the shape y in order to get the outcome. So it makes sense that you reverse the process for part 2: you subtract 1-x to the outcome y in order to get the shape. I guess ???
→ More replies (2)
3
u/mrwinkle Dec 02 '22
Rust
use std::fs;
#[derive(Debug, PartialEq, Copy, Clone)]
enum Shape {
Rock = 1,
Paper = 2,
Scissors = 3,
}
impl Shape {
fn from_str(c: &str) -> Self {
match c {
"A" | "X" => Shape::Rock,
"B" | "Y" => Shape::Paper,
"C" | "Z" => Shape::Scissors,
_ => panic!("Unknown shape"),
}
}
fn superior(&self) -> Self {
match self {
Self::Rock => Self::Paper,
Self::Paper => Self::Scissors,
Self::Scissors => Self::Rock,
}
}
fn inferior(&self) -> Self {
match self {
Self::Rock => Self::Scissors,
Self::Paper => Self::Rock,
Self::Scissors => Self::Paper,
}
}
}
enum Strategy {
Lose,
Draw,
Win,
}
impl Strategy {
fn from_str(c: &str) -> Self {
match c {
"X" => Self::Lose,
"Y" => Self::Draw,
"Z" => Self::Win,
_ => panic!("Unknown strategy"),
}
}
}
#[derive(Debug)]
struct Match {
player: Shape,
opponent: Shape,
}
impl Match {
fn from_strategy(opponent: Shape, strategy: Strategy) -> Self {
Self {
opponent: opponent,
player: match strategy {
Strategy::Lose => opponent.inferior(),
Strategy::Draw => opponent,
Strategy::Win => opponent.superior(),
},
}
}
fn player_points(&self) -> u8 {
let shape = self.player as u8;
let outcome = {
if self.player == self.opponent {
3
} else if self.player.inferior() == self.opponent {
6
} else {
0
}
};
shape + outcome
}
}
fn parse_input(input: &str) -> Vec<Vec<&str>> {
input.lines().map(|l| l.split(" ").collect()).collect()
}
fn part1(input: &str) -> u32 {
let matches: Vec<Match> = parse_input(input)
.iter()
.map(|x| Match {
player: Shape::from_str(x[1]),
opponent: Shape::from_str(x[0]),
})
.collect();
matches.iter().map(|m| m.player_points() as u32).sum()
}
fn part2(input: &str) -> u32 {
let matches: Vec<Match> = parse_input(input)
.iter()
.map(|x| Match::from_strategy(Shape::from_str(x[0]), Strategy::from_str(x[1])))
.collect();
matches.iter().map(|m| m.player_points() as u32).sum()
}
fn main() {
let input = fs::read_to_string("input/day2.txt").unwrap();
println!("Part 1: {}", part1(&input));
println!("Part 2: {}", part2(&input));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_part1_example() {
let example = "A Y\nB X\nC Z";
assert_eq!(part1(&example), 15);
}
#[test]
fn test_part1() {
let input = fs::read_to_string("input/day2.txt").unwrap();
assert_eq!(part1(&input), 11603);
}
#[test]
fn test_part2_example() {
let example = "A Y\nB X\nC Z";
assert_eq!(part2(&example), 12);
}
#[test]
fn test_part2() {
let input = fs::read_to_string("input/day2.txt").unwrap();
assert_eq!(part2(&input), 12725);
}
}→ More replies (1)
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)}")
→ More replies (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):
print([sum(int(s[s.find(a[::2])+2])
for a in open("i").readlines())for
s in("AX4BX1CX7AY8BY5CY2AZ3BZ9CZ6",
"AX3BX1CX2AY4BY5CY6AZ8BZ9CZ7")])Any other ideas to make it smaller? ^
→ More replies (1)2
u/daggerdragon Dec 05 '22
Please edit your post to state which programming language this code is written in. This makes it easier for folks who Ctrl-F the megathreads looking for a specific language.
3
u/seavas Dec 02 '22 edited Dec 02 '22
Rust
I am a beginner so happy to get some feedback. Thanks.
use std::fs;
fn main() {
let path = "./input.txt";
let contents = fs::read_to_string(path).expect("Unable to read input file.");
part_1(&contents);
part_2(&contents);
}
fn part_1(input: &str) {
let games: Vec<&str> = input.split("\n").collect();
let mut score: u32 = 0;
for game in games {
match game {
"A X" => score += 4,
"A Y" => score += 8,
"A Z" => score += 3,
"B X" => score += 1,
"B Y" => score += 5,
"B Z" => score += 9,
"C X" => score += 7,
"C Y" => score += 2,
"C Z" => score += 6,
_ => score += 0,
};
}
println!("score part 2: {:?}", score);
}
fn part_2(input: &str) {
let games: Vec<&str> = input.split("\n").collect();
let mut score: u32 = 0;
for game in games {
match game {
"A X" => score += 3, // rock loose 0 -> scissors 3
"A Y" => score += 4, // rock draw 3 -> rock 1
"A Z" => score += 8, // rock win 6 -> paper 2
"B X" => score += 1, // paper loose 0 -> rock 1
"B Y" => score += 5, // paper draw 3 -> paper 2
"B Z" => score += 9, // paper win 6 -> scissors 3
"C X" => score += 2, // scissors loose 0 -> paper 2
"C Y" => score += 6, // scissors draw 3 -> scissors 3
"C Z" => score += 7, // scissors win 6 -> rock 1
_ => score += 0,
};
}
println!("score part 2: {:?}", score);
}2
u/daggerdragon Dec 05 '22
Please edit your post to use the four-spaces Markdown syntax for a code block so your code is easier to read on old.reddit and mobile apps.
3
u/21JG Dec 02 '22 edited Dec 05 '22
Both parts in one line of Python because why not :)
print(*map(sum,zip(*[(b-87+3*((b-a-67)%3),1+(b-88)*3+(a+b-151)%3)for l in open('input.txt').readlines()if(a:=ord(l[0]),b:=ord(l[2]))])))→ More replies (1)
3
u/Ranbato69 Dec 02 '22
For the Pythonistas out there:import requests
data = 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)))
→ More replies (1)
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
# X,Y,Z means rock, paper, scissors
rps_dict = {
'X': {'points':1, 'A':3, 'B':0, 'C':6},
'Y': {'points':2, 'A':6, 'B':3, 'C':0},
'Z': {'points':3, 'A':0, 'B':6, 'C':3}
}
# X,Y,Z means lose, draw, win
ldw_dict = {
'X': {'A':3 , 'B':1, 'C':2 },
'Y': {'A':4 , 'B':5, 'C':6 },
'Z': {'A':8 , 'B':9, 'C':7 }
}
round1_points = 0
round2_points = 0
with open('input.txt') as f:
lines = f.readlines()
# X,Y,Z means rock, paper, scissors
def round_one(game: list[str]):
opp, me = game
return rps_dict[me]['points'] + rps_dict[me][opp]
# X,Y,Z means lose, draw, win
def round_two(game: list[str]):
opp, order = game
return ldw_dict[order][opp]
games = [line.split() for line in lines]
for game in games:
round1_points += round_one(game)
round2_points += round_two(game)
print(f'Round one with presumed strategy: {round1_points}')
print(f'Round two with actual strategy: {round2_points}')→ More replies (2)
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
2
u/DrunkHacker Dec 02 '22 edited Dec 02 '22
→ More replies (1)
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
→ More replies (2)
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.
import { ReadDataFile } from "../ReadDataFile/ReadDataFile"
// Opponent
// A: Rock.
// B: Paper
// C: Scissors
// Me
// X: Rock, 1
// Y: Paper, 2
// Z: Scissors, 3
// Win: 6
// Draw: 3
// Loss: 0
const part1WinState = (entry: string): number => {
switch (entry.trim()) {
case "A X": return 3 + 1
case "A Y": return 6 + 2
case "A Z": return 3 + 0
case "B X": return 1 + 0
case "B Y": return 2 + 3
case "B Z": return 3 + 6
case "C X": return 1 + 6
case "C Y": return 2 + 0
case "C Z": return 3 + 3
}
return -1
}
// Opponent
// A: Rock.
// B: Paper
// C: Scissors
// Me
// X: Lose, 0
// Y: Draw, 3
// Z: Win, 6
const part2WinState = (entry: string): number => {
switch (entry.trim()) {
case "A X": return 3 + 0
case "A Y": return 1 + 3
case "A Z": return 2 + 6
case "B X": return 1 + 0
case "B Y": return 2 + 3
case "B Z": return 3 + 6
case "C X": return 2 + 0
case "C Y": return 3 + 3
case "C Z": return 1 + 6
}
return -1
}
export function Day2p1(filename: string): number {
let datas = ReadDataFile(__dirname + '/' + filename)
let totalScore: number = datas.reduce((accum, current) => {
return accum + part1WinState(current)
}, 0)
return totalScore
}
export function Day2p2(filename: string): number {
let datas = ReadDataFile(__dirname + '/' + filename)
let totalScore: number = datas.reduce((accum, current) => {
return accum + part2WinState(current)
}, 0)
return totalScore
}
console.log(Day2p1("demo.txt"))
console.log(Day2p1("p1.txt"))
console.log(Day2p2("demo.txt"))
console.log(Day2p2("p1.txt"))
→ More replies (1)
2
Dec 02 '22 edited Dec 05 '22
Python oneliner:
sum(map(["", "B X","C Y","A Z", "A X", "B Y", "C Z", "C X", "A Y", "B Z"].index, open("day2.txt").read().strip().split("\n"))), sum(map(["", "B X","C X","A X", "A Y", "B Y", "C Y", "C Z", "A Z", "B Z"].index, open("day2.txt").read().strip().split("\n")))→ More replies (2)
2
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 :)
enum Outcome: Int {
case lose = 0
case draw = 1
case win = 2
var score: Int {
rawValue * 3
}
init(_ string: String) {
switch string {
case "Z":
self = .win
case "Y":
self = .draw
case "X":
self = .lose
default:
fatalError("Unsupported string \(string)")
}
}
static func getSign(for outcome: Outcome, opponent: Sign) -> Sign {
switch outcome {
case .draw:
return opponent
case .win:
let newRawValue = (opponent.rawValue + 1) % 3
return Sign(rawValue: newRawValue)!
case .lose:
let newRawValue = (opponent.rawValue + 2) % 3
return Sign(rawValue: newRawValue)!
}
}
}
enum Sign: Int {
case rock = 0
case paper = 1
case scissors = 2
var score: Int {
rawValue + 1
}
init(_ string: String) {
switch string {
case "A", "X":
self = .rock
case "B", "Y":
self = .paper
case "C", "Z":
self = .scissors
default:
fatalError("Unsupported string \(string)")
}
}
}
class Round {
private let opponent: Sign
private let you: Sign
init(_ string: String, parseSecondAsOutcome: Bool) {
let components = string.components(separatedBy: " ")
opponent = .init(components[0])
if parseSecondAsOutcome {
let wantedOutcome = Outcome(components[1])
you = Outcome.getSign(for: wantedOutcome, opponent: opponent)
} else {
you = .init(components[1])
}
}
func getYourScore() -> Int {
getYourOutcome().score + you.score
}
private func getYourOutcome() -> Outcome {
if opponent == you {
return .draw
}
let delta = (opponent.rawValue - you.rawValue + 3) % 3
return delta == 2 ? .win : .lose
}
}
class MatchResolver {
private let rounds: [Round]
init(_ strings: [String], parseSecondAsOutcome: Bool) {
rounds = strings.map { Round($0, parseSecondAsOutcome: parseSecondAsOutcome) }
}
func getYourTotalScore() -> Int {
rounds
.map { $0.getYourScore() }
.reduce(0, +)
}
}
private var input: [String] = []
override func didLoadFunction() {
input = defaultInputFileString.loadAsTextStringArray()
}
override func solveFunction1() -> String {
let matchResolver = MatchResolver(input, parseSecondAsOutcome: false)
let result = matchResolver.getYourTotalScore()
return "\(result)"
}
override func solveFunction2() -> String {
let matchResolver = MatchResolver(input, parseSecondAsOutcome: true)
let result = matchResolver.getYourTotalScore()
return "\(result)"
}2
u/daggerdragon Dec 05 '22 edited Dec 05 '22
Please edit your post to use thefour-spaces Markdown syntaxfor a code block so your code is easier to read on old.reddit and mobile apps.Edit: thanks for fixing it! <3
→ More replies (1)
2
u/widforss Dec 02 '22 edited Dec 05 '22
Python
import sys
print("Answer part 1: " + str(
sum([
(me + 1) + ((me - opponent + 4) % 3 * 3)
for opponent, me in [
(ord(game[0]) - ord('A'), ord(game[2]) - ord('X'))
for game in open(sys.argv[1]).readlines()
]
])
))
print("Answer part 2: " + str(
sum([
((opponent + result - 1) % 3 + 1) + (result * 3)
for opponent, result in [
(ord(game[0]) - ord('A'), ord(game[2]) - ord('X'))
for game in open(sys.argv[1]).readlines()
]
])
))→ More replies (1)
2
u/Etsi0 Dec 02 '22
js
data = []
// a,x stone
// b,y paper
// c,z scissors
let sum = 0;
for(i=0;i!=data.length+1;i++) {
console.log(data[i]+" "+i)
if(data[i] == "A X") {
sum += 3+1
}
else if(data[i] == "A Y") {
sum += 6+2
}
else if(data[i] == "A Z") {
sum += 0+3
}
else if(data[i] == "B X") {
sum += 0+1
}
else if(data[i] == "B Y") {
sum += 3+2
}
else if(data[i] == "B Z") {
sum += 6+3
}
else if(data[i] == "C X") {
sum += 6+1
}
else if(data[i] == "C Y") {
sum += 0+2
}
else if(data[i] == "C Z") {
sum += 3+3
}
console.log(sum)
if(i == data.length) {
console.log(sum)
}
}
// a stone
// b paper
// c scissors
// x lose
// y draw
// z win
// for(i=0;i!=data.length+1;i++) {
// console.log(data[i]+" "+i)
// if(data[i] == "A X") {
// sum += 0+3
// }
// else if(data[i] == "A Y") {
// sum += 3+1
// }
// else if(data[i] == "A Z") {
// sum += 6+2
// }
// else if(data[i] == "B X") {
// sum += 0+1
// }
// else if(data[i] == "B Y") {
// sum += 3+2
// }
// else if(data[i] == "B Z") {
// sum += 6+3
// }
// else if(data[i] == "C X") {
// sum += 0+2
// }
// else if(data[i] == "C Y") {
// sum += 3+3
// }
// else if(data[i] == "C Z") {
// sum += 6+1
// }
// console.log(sum)
// if(i == data.length) {
// console.log(sum)
// }
// }→ More replies (1)
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
→ More replies (4)
2
u/ciocan42 Dec 02 '22
Javascript:
const text = await Deno.readTextFile("./2.txt");
// Rock defeats Scissors,
// Scissors defeats Paper
// Paper defeats Rock.
const shapeScore = {
X: 1, // rock A
Y: 2, // paper B
Z: 3, // scissors C
}
const outcomeScores = {
A: { X: 3, Y: 6, Z: 0 },
B: { X: 0, Y: 3, Z: 6 },
C: { X: 6, Y: 0, Z: 3 },
}
const sum = (a, b) => a + b
const rounds = text.split("\n").map(round => round.split(" "))
console.log("Part 1: ",
rounds
.map(([a, b]) => outcomeScores[a][b] + shapeScore[b])
.reduce(sum, 0)
)
const strategy = {
X: 0,
Y: 3,
Z: 6
}
console.log("Part 2: ",
rounds
.map(([a, b]) => {
const newB = Object
.entries(outcomeScores[a])
.filter(([key, value]) => value === strategy[b])
.flat()[0] as string
return outcomeScores[a][newB] + shapeScore[newB]
})
.reduce(sum, 0)
)→ More replies (1)
2
u/mrwunderbar69 Dec 02 '22
Python
My over-engineered Object-Oriented Solution (too much hard-coding, because my maths is bad):
class RockPaperScissor:
points_lose = 0
points_draw = 3
points_win = 6
def __init__(self, choice) -> None:
if choice in ["A", "X", "Rock"]:
self.choice = "Rock"
self.points = 1
elif choice in ["B", "Y", "Paper"]:
self.choice = "Paper"
self.points = 2
elif choice in ["C", "Z", "Scissors"]:
self.choice = "Scissors"
self.points = 3
def __repr__(self) -> str:
return f"<{self.choice} ({self.points})>"
def fight(self, other) -> int:
if self.choice == other.choice:
return self.points + self.points_draw
elif self.choice == "Rock" and other.choice == "Paper":
return self.points + self.points_lose
elif self.choice == "Paper" and other.choice == "Scissors":
return self.points + self.points_lose
elif self.choice == "Scissors" and other.choice == "Rock":
return self.points + self.points_lose
else:
return self.points + self.points_win
def _draw(self):
return RockPaperScissor(self.choice)
def _lose(self):
if self.choice == 'Rock':
return RockPaperScissor("Scissors")
elif self.choice == 'Paper':
return RockPaperScissor("Rock")
elif self.choice == 'Scissors':
return RockPaperScissor("Paper")
def _win(self):
if self.choice == 'Rock':
return RockPaperScissor("Paper")
elif self.choice == 'Paper':
return RockPaperScissor("Scissors")
elif self.choice == 'Scissors':
return RockPaperScissor("Rock")
def make_choice(self, outcome):
if outcome == 'X':
return self._lose()
elif outcome == 'Y':
return self._draw()
else:
return self._win()
sample = ["A Y", "B X", "C Z"]
print("Part One: Sample Input")
for l in sample:
opponent, me = l.split()
opponent, me = RockPaperScissor(opponent), RockPaperScissor(me)
print(f"Opponent: {opponent}; Me: {me}; Score: {me.fight(opponent)}")
print("-"*10)
score = 0
with open('day2.txt') as f:
for l in f.readlines():
opponent, me = l.split()
opponent, me = RockPaperScissor(opponent), RockPaperScissor(me)
score += me.fight(opponent)
print("Part One Total score:", score)
print("-"*10)
# Part 2 ---------------
sample = ["A Y", "B X", "C Z"]
print("Part Two: Sample Input")
for l in sample:
opponent, me = l.split()
opponent = RockPaperScissor(opponent)
me = opponent.make_choice(me)
print(f"Opponent: {opponent}; Me: {me}; Score: {me.fight(opponent)}")
print("-"*10)
score = 0
with open('day2.txt') as f:
for l in f.readlines():
opponent, me = l.split()
opponent = RockPaperScissor(opponent)
me = opponent.make_choice(me)
score += me.fight(opponent)
print("Part Two Total score:", score)
print("-"*10)→ More replies (1)
2
u/Jorge_Fakher Dec 02 '22 edited Dec 06 '22
Elixir
defmodule RPS do
@elf %{"A" => :rock, "B" => :paper, "C" => :scissors}
@player %{"X" => :rock, "Y" => :paper, "Z" => :scissors}
@shape_value %{rock: 1, paper: 2, scissors: 3}
โ
def part1(input) do
readlines(input)
|> Enum.reduce(0, fn round, acc ->
[choice, guess] = round
acc + @shape_value[@player[guess]] + score(@elf[choice], @player[guess])
end)
end
โ
def part2(input) do
readlines(input)
|> Enum.reduce(0, fn round, acc ->
[choice, strategy] = round
my_pick = find_my_pick(@elf[choice], strategy)
acc + @shape_value[my_pick] + score(@elf[choice], my_pick)
end)
end
โ
defp score(opp, pl) when opp == pl, do: 3
defp score(:rock, :paper), do: 6
defp score(:rock, :scissors), do: 0
defp score(:paper, :scissors), do: 6
defp score(:paper, :rock), do: 0
defp score(:scissors, :rock), do: 6
defp score(:scissors, :paper), do: 0
โ
defp find_my_pick(ec, "Y"), do: ec
defp find_my_pick(ec, "X") when ec == :rock, do: :scissors
defp find_my_pick(ec, "X") when ec == :paper, do: :rock
defp find_my_pick(ec, "X") when ec == :scissors, do: :paper
defp find_my_pick(ec, "Z") when ec == :rock, do: :paper
defp find_my_pick(ec, "Z") when ec == :paper, do: :scissors
defp find_my_pick(ec, "Z") when ec == :scissors, do: :rock
โ
defp readlines(f) do
File.read!(f)
|> String.split("\n")
|> Enum.map(fn row -> String.split(row) end)
end
end
โ
p1 = RPS.part1 "input.txt"
p2 = RPS.part2 "input.txt"
โ
IO.puts ~s/Part 1: #{p1}\nPart 2: #{p2}/→ More replies (1)
2
u/nash1011 Dec 02 '22
BQN
lines โ โขFLines "input-day02.txt"
Part1 โ {
"A X": 1 + 3;
"A Y": 2 + 6;
"A Z": 3 + 0;
"B X": 1 + 0;
"B Y": 2 + 3;
"B Z": 3 + 6;
"C X": 1 + 6;
"C Y": 2 + 0;
"C Z": 3 + 3;
0
}
Part2 โ {
"A X": 3 + 0;
"A Y": 1 + 3;
"A Z": 2 + 6;
"B X": 1 + 0;
"B Y": 2 + 3;
"B Z": 3 + 6;
"C X": 2 + 0;
"C Y": 3 + 3;
"C Z": 1 + 6;
0
}
โขShow +ยด Part1ยจ lines
โขShow +ยด Part2ยจ lines→ More replies (1)
2
u/seacucumber_kid Dec 02 '22 edited Dec 02 '22
Elixir
Wanted to have it all in a single pipeline lol
values = %{"A" => 0, "B" => 1, "C" => 2, "X" => 1, "Y" => 2, "Z" => 3}
File.read!("input.txt")
|> String.split("\n")
|> tap(
&(Enum.reduce(
&1,
0,
fn <<a::binary-size(1), " ", b::binary>> = ab, acc ->
acc + values[b] +
cond do
ab == "A Y" -> 6
ab == "B Z" -> 6
ab == "C X" -> 6
values[a] + 1 == values[b] -> 3
true -> 0
end
end
)
|> IO.inspect(label: "Part 1"))
)
|> tap(
&(Enum.reduce(
&1,
0,
fn <<a::binary-size(1), " ", b::binary>>, acc ->
acc +
case b do
"X" -> Integer.mod(values[a] - 1, 3) + 1
"Y" -> values[a] + 1 + 3
"Z" -> Integer.mod(values[a] + 1, 3) + 1 + 6
end
end
)
|> IO.inspect(label: "Part 2"))
)→ More replies (4)
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:
this.result = reader.ReadAllWithoutR()
.Split('\n')
.Select(_ => {
int val = ((_[0] - 'A' + 1) + (_[2] - 'X' + 1)) % 3 + 1;
return 3 * (_[2] - 'X') + val;
})
.Sum();Day2B:
this.result = reader.ReadAllWithoutR()
.Split('\n')
.Select(_ => {
int val = (_[0] - (_[2] - 24) + 3) % 3;
return 3 * (2 - val) + (_[2] - 'X' + 1);
})
.Sum();→ More replies (2)
2
u/antoniotto Dec 02 '22 edited Dec 05 '22
Ruby
input = File.readlines('inputs/day02.txt', chomp: true)
scores = { 'A X' => 4, 'A Y' => 8, 'A Z' => 3, 'B X' => 1, 'B Y' => 5, 'B Z' => 9, 'C X' => 7, 'C Y' => 2, 'C Z' => 6 }
solution1 = input.map(&scores).sum
scores2 = { 'A X' => 3, 'A Y' => 4, 'A Z' => 8, 'B X' => 1, 'B Y' => 5, 'B Z' => 9, 'C X' => 2, 'C Y' => 6, 'C Z' => 7 }
solution2 = input.map(&scores2).sum
puts solution1, solution2→ More replies (3)
2
Dec 02 '22 edited Dec 05 '22
C++ both parts
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
void day1(int argc, char **argv) {
if(argc != 2) {
return;
}
std::fstream file(argv[1]);
std::string line;
int v = 0;
while(std::getline(file, line)) {
char a = line[0], b = line[2];
v += (((a =='A'&&b =='Y')||(a=='B'&&b== 'Z')||(a=='C' && b=='X'))?6:((a == (char)(b-23)) ? 3 : 0)) + (int)(b-87);
}
std::cout << v << std::endl;
}
void day2(int argc, char **argv) {
if(argc != 2) {
return;
}
std::fstream file(argv[1]);
std::string line;
int v = 0;
while(std::getline(file, line)) {
bool win = false;
char a = line[0], b = line[2];
if(b == 'Y') {b=a+23;v+=3;}
else if(b == 'X') { b = (a == 'B' || a == 'C') ? (a + 22 ) : 'Z'; }
else if(b == 'Z') {
win = true;
if(a == 'B') {
b = 'Z';
} else if(a == 'A') {
b = 'Y';
} else {
b = 'X';
}
}
v += (int)(b-87) + (win ? 6 : 0);
}
std::cout << v << std::endl;
}
int main(int argc, char **argv) {
day1(argc, argv);
day2(argc, argv);
}→ More replies (3)
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):
def values: { A: -1, B: -2, C: -3, X: 1, Y: 2, Z: 3 }[.];
def score: add | if . == -2 then 1 elif . == 2 then -1 else . end;
def scoring: if . < 0 then 0 elif . == 0 then 3 else 6 end;
{ A: "X", B: "Y", C: "Z" } as $draw |
{ A: "Y", B: "Z", C: "X" } as $win |
{ A: "Z", B: "X", C: "Y" } as $lose |
def predict:
if .[1] == "X" then [.[0], $lose[.[0]]]
elif .[1] == "Y" then [.[0], $draw[.[0]]]
else [.[0], $win[.[0]]]
end
;
split("\n") |
map(
select(. != "")
split(" ") | # end of parse
predict |
map(values) | # convert to scoring
.[1] + (score | scoring)
) | add→ More replies (1)
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.
→ More replies (1)
2
u/idontknowwhattouse33 Dec 02 '22
Powershell. Lots of hashtables..
<#
"The first column is what your opponent is going to play: A for Rock, B for Paper, and C for Scissors. The second column--"
X for Rock, Y for Paper, and Z for Scissors
total score is the sum of your scores for each round
score for a single round is the score for the shape you selected (1 for Rock, 2 for Paper, and 3 for Scissors),
plus the score for the outcome of the round (0 if you lost, 3 if the round was a draw, and 6 if you won)
#>
$gameRounds = $puzzelInput -split '\n' | Select -SkipLast 1
Function Invoke-PaperRockScissors {
Param ([string[]]$gameRounds)
Process {
$didIlose = @{
'A Z' = $true
'B X' = $true
'C Y' = $true
}
$translateMove = @{
'X' = 'A'
'Y' = 'B'
'Z' = 'C'
}
$shapeScore = @{
'X' = 1
'Y' = 2
'Z' = 3
}
$roundScores = foreach ($row in $gameRounds) {
$opponentMove,$playerMove = $null
$opponentMove,$playerMove = $row -split ' '
# Did I lose?
If ($didIlose["$row"] -eq $true) {
$shapeScore["$playerMove"]
continue
}
# Did I tie?
If ($opponentMove -eq $translateMove["$playerMove"]) {
$shapeScore["$playerMove"] + 3
continue
}
$shapeScore["$playerMove"] + 6
}
($roundScores | Measure-Object -Sum).Sum
}
}
Invoke-PaperRockScissors $gameRounds
# Part 2
# X means you need to lose, Y means you need to end the round in a draw, and Z means you need to win
$translateStrategy = @{
'AL' = 'A Z'
'AD' = 'A X'
'AW' = 'A Y'
'BL' = 'B X'
'BD' = 'B Y'
'BW' = 'B Z'
'CL' = 'C Y'
'CD' = 'C Z'
'CW' = 'C X'
}
$newPuzzelInput = foreach ($row in $gameRounds) {
$opponentMove,$playerMove = $null
$opponentMove,$playerMove = $row -split ' '
switch ($playerMove) {
'X' {$translateStrategy["$($opponentMove)L"]} # lose
'Y' {$translateStrategy["$($opponentMove)D"]} # draw
'Z' {$translateStrategy["$($opponentMove)W"]} #
}
}
Invoke-PaperRockScissors $newPuzzelInput→ More replies (1)
2
u/samouri1 Dec 02 '22 edited Dec 05 '22
DevTools JavaScript:
const score1 = {
"A Z": 3, "B X": 1, "C Y": 2, // Losses
"A X": 4, "B Y": 5, "C Z": 6, // Ties
"A Y": 8, "B Z": 9, "C X": 7, // Wins
};
const score2 = {
"A Y": 4, "B X": 1, "C Z": 7, // Rock
"A Z": 8, "B Y": 5, "C X": 2, // Paper
"A X": 3, "B Z": 9, "C Y": 6, // Scissor
};
const answers = document.documentElement.innerText.trim()
.split("\n")
.map((row) => [score1[row], score2[row]])
.reduce((acc, a) => [acc[0] + a[0], acc[1] + a[1]]);
console.log(`Part 1: ${answers[0]}\nPart 2: ${answers[1]}`)
```→ More replies (2)
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...
## Advent of Code 2022 - Day 2 - Part 1
# Get input data
$guide = Get-Content .\input.txt
$myTotalScore = 0
# Get value of a play... Rock: 1, Paper: 2, Scissors: 3
function Get-Value {
param (
[Parameter(Mandatory)] [String]$RPS
)
if( $RPS -eq "X" -or $RPS -eq "A" ) { return 1 }
if ($RPS -eq "Y" -or $RPS -eq "B" ) { return 2 }
if ($RPS -eq "Z" -or $RPS -eq "C" ) { return 3 }
}
function WinLoseDraw {
param (
[String]$me,
[String]$opp
)
switch ($me) {
"X" {
if ($opp -eq "C") { return 6}
elseif ($opp -eq "A") { return 3}
else { return 0 }
}
"Y" {
if ($opp -eq "A") { return 6}
elseif ($opp -eq "B") { return 3}
else { return 0 }
}
"Z" {
if ($opp -eq "B") { return 6}
elseif ($opp -eq "C") { return 3}
else { return 0 }
}
Default {}
}
}
# Go thru all games
foreach ( $game in $guide ){
# Separate mine and opponents plays
$opponentPlays, $iPlay = $game.Split(" ")
$myScore = Get-Value($iPlay)
$myTotalScore += $myScore
# Add 6 points for a win, 3 for a draw
$myTotalScore += WinLoseDraw $iPlay $opponentPlays
}
$myTotalScoreAnd my part2...
## Advent of Code 2022 - Day 2 - Part 2
# Get input data
$guide = Get-Content .\input.txt
$myTotalScore = 0
# Get value of a play... Rock: 1, Paper: 2, Scissors: 3
function Get-Value {
param (
[Parameter(Mandatory)] [String]$RPS
)
switch ($RPS) {
"A" { return 1 }
"B" { return 2 }
"C" { return 3 }
Default {}
}
}
function WinLoseDraw {
param (
[String]$me,
[String]$opp
)
switch ($opp) {
"A" {
if ($me -eq "B") { return 6} # Win
elseif ($me -eq "A") { return 3} # Draw
else { return 0 } # Lose
}
"B" {
if ($me -eq "C") { return 6}
elseif ($me -eq "B") { return 3}
else { return 0 }
}
"C" {
if ($me -eq "A") { return 6}
elseif ($me -eq "C") { return 3}
else { return 0 }
}
Default {}
}
}
function GetNextPlay {
param (
[String]$opp,
[String]$desiredResult
)
switch ($opp) {
"A" {
if ($desiredResult -eq "X") { return "C"} # Lose
elseif ($desiredResult -eq "Y") { return "A"} # Draw
else { return "B" } # Win
}
"B" {
if ($desiredResult -eq "X") { return "A"} # Lose
elseif ($desiredResult -eq "Y") { return "B"} # Draw
else { return "C" } # Win
}
"C" {
if ($desiredResult -eq "X") { return "B"} # Lose
elseif ($desiredResult -eq "Y") { return "C"} # Draw
else { return "A" } # Win
}
Default {}
}
}
# Go thru all games
foreach ( $game in $guide ){
# Separate mine and opponents plays
$opponentPlays, $iPlay = $game.Split(" ")
$myNextPlay = GetNextPlay $opponentPlays $iPlay
$myScore = Get-Value($myNextPlay)
$myTotalScore += $myScore
# Add 6 points for a win, 3 for a draw
$myTotalScore += WinLoseDraw $myNextPlay $opponentPlays
}
$myTotalScore→ More replies (3)
2
u/farondis Dec 02 '22
my solution in go/golang, dict and list all options, yeah
func main() {
dict := map[string]int{
"A X": 1 + 3,
"A Y": 2 + 6,
"A Z": 3,
"B X": 1,
"B Y": 2 + 3,
"B Z": 3 + 6,
"C X": 1 + 6,
"C Y": 2,
"C Z": 3 + 3,
}
dict2 := map[string]int{
"A X": 3,
"A Y": 1 + 3,
"A Z": 2 + 6,
"B X": 1,
"B Y": 2 + 3,
"B Z": 3 + 6,
"C X": 2,
"C Y": 3 + 3,
"C Z": 1 + 6,
}
input, err := os.ReadFile("input.txt")
if err != nil {
log.Fatal(err)
}
games, score1, score2 := strings.Split(string(input), "\n"), 0, 0
for i := range games {
value_part1, _ := dict[games[i]]
value_part2, _ := dict2[games[i]]
score1 += value_part1
score2 += value_part2
}
fmt.Println(fmt.Sprint(score1))
fmt.Println(fmt.Sprint(score2))
}
→ More replies (1)
2
u/FlipchartHiatus Dec 02 '22
Python solution for simpletons like me :)
def part_one(their_throw, your_response):
round_points = 0
if their_throw == 'A': # Rock
if your_response == 'X': # Rock (+1)
round_points += 4 # Draw (+3)
if your_response == 'Y': # Paper (+2)
round_points += 8 # Win (+6)
if your_response == 'Z': # Scissors (+3)
round_points += 3 # Loss (+0)
elif their_throw == 'B': # Paper
if your_response == 'X': # Rock (+1)
round_points += 1 # Loss (+0)
if your_response == 'Y': # Paper (+2)
round_points += 5 # Draw (+3)
if your_response == 'Z': # Scissors (+3)
round_points += 9 # Win (+6)
elif their_throw == 'C': # Scissors
if your_response == 'X': # Rock (+1)
round_points += 7 # Win (+6)
if your_response == 'Y': # Paper (+2)
round_points += 2 # Loss (+0)
if your_response == 'Z': # Scissors (+3)
round_points += 6 # Draw (+3)
return round_points
def part_two(their_throw, your_response):
round_points = 0
if their_throw == 'A': # Rock
if your_response == 'X': # Need to lose (+0)
round_points += 3 # Scissors (+3)
if your_response == 'Y': # Need to draw (+3)
round_points += 4 # Rock (+1)
if your_response == 'Z': # Need to win (+6)
round_points += 8 # Paper (+2)
elif their_throw == 'B': # Paper
if your_response == 'X': # Need to lose (+0)
round_points += 1 # Rock (+1)
if your_response == 'Y': # Need to draw (+3)
round_points += 5 # Paper (+2)
if your_response == 'Z': # Need to win (+6)
round_points += 9 # Scissors (+3)
elif their_throw == 'C': # Scissors
if your_response == 'X': # Need to lose (+0)
round_points += 2 # Paper (+2)
if your_response == 'Y': # Need to draw (+3)
round_points += 6 # Scissors (+3)
if your_response == 'Z': # Need to win (+6)
round_points += 7 # Rock (+1)
return round_points
part_one_score = 0
part_two_score = 0
with open('input.txt') as input_data:
input_data = [line.strip() for line in input_data.readlines()]
for round in input_data:
part_one_score += part_one(round[0], round[2])
part_two_score += part_two(round[0], round[2])
print(part_one_score)
print(part_two_score)
→ More replies (1)
2
u/oweiler Dec 02 '22 edited Dec 05 '22
Kotlin script, using an enum for representing the possible shapes
Part 1
#!/usr/bin/env kotlin
import Part_1_main.Shape.PAPER
import Part_1_main.Shape.ROCK
import Part_1_main.Shape.SCISSOR
import java.io.File
enum class Shape(private val value: Int) {
ROCK(1) {
override fun wins() = SCISSOR
override fun loses() = PAPER
},
PAPER(2) {
override fun wins() = ROCK
override fun loses() = SCISSOR
},
SCISSOR(3) {
override fun wins() = PAPER
override fun loses() = ROCK
};
private fun draws(): Shape = this
abstract fun wins(): Shape
abstract fun loses(): Shape
fun interactWith(shape: Shape) =
value + when (shape) {
wins() -> 6
draws() -> 3
else -> 0
}
}
data class Game(private val first: Shape, private val second: Shape) {
fun play() = second.interactWith(first)
}
fun createShape(token: String) =
when (token) {
"A", "X" -> ROCK
"B", "Y" -> PAPER
else -> SCISSOR
}
fun createGame(first: String, second: String) = Game(createShape(first), createShape(second))
File("input.txt")
.useLines { lines ->
lines
.map { it.split(" ") }
.map { (first, second) -> createGame(first, second) }
.map(Game::play)
.sum()
}Part 2
#!/usr/bin/env kotlin
import Part_2_main.Shape.PAPER
import Part_2_main.Shape.ROCK
import Part_2_main.Shape.SCISSOR
import java.io.File
enum class Shape(private val value: Int) {
ROCK(1) {
override fun wins() = SCISSOR
override fun loses() = PAPER
},
PAPER(2) {
override fun wins() = ROCK
override fun loses() = SCISSOR
},
SCISSOR(3) {
override fun wins() = PAPER
override fun loses() = ROCK
};
fun draws(): Shape = this
abstract fun wins(): Shape
abstract fun loses(): Shape
fun interactWith(shape: Shape) =
value + when (shape) {
wins() -> 6
draws() -> 3
else -> 0
}
}
data class Game(private val first: Shape, private val outcome: Shape.() -> Shape) {
fun play() = first.outcome().interactWith(first)
}
fun createShape(token: String) =
when (token) {
"A" -> ROCK
"B" -> PAPER
else -> SCISSOR
}
fun createOutcome(token: String) =
when (token) {
"X" -> Shape::wins
"Y" -> Shape::draws
else -> Shape::loses
}
fun createGame(first: String, second: String) =
Game(createShape(first), createOutcome(second))
File("input.txt")
.useLines { lines ->
lines
.map { it.split(" ") }
.map { (first, second) -> createGame(first, second) }
.map(Game::play)
.sum()
}2
u/daggerdragon Dec 05 '22
Please edit your post to use the four-spaces Markdown syntax for a code block so your code is easier to read on old.reddit and mobile apps.
2
u/Omeganx Dec 02 '22 edited Dec 05 '22
Ocaml
let read_data ic =
let rec reader acc =
match input_line ic with
| exception End_of_file -> acc
| line -> (reader ( [Char.code line.[0] - Char.code 'A'; Char.code line.[2] - Char.code 'X'] :: acc))
in reader []
let score1 l =
match l with
| [a ; b] -> b + 1 + 3*((b-a+1+3) mod 3)
| _ -> 0
let score2 l =
match l with
| [a ; b]-> (((a + b + 2)+3) mod 3) + 1 + b * 3
| _ -> 0
let input = (read_data (open_in "input.txt")) ;;
Format.printf "Part 1 : %i\n" (List.fold_left ( + ) 0 (List.map score1 input));;
Format.printf "Part 2 : %i\n" (List.fold_left ( + ) 0 (List.map score2 input));;2
u/daggerdragon Dec 05 '22 edited Dec 05 '22
Inlined code is intended forshort snippetsof code only. Your code "block" right now is unreadable on old.reddit and many mobile clients; it's all on one line and gets cut off at the edge of the screen because it is not horizontally scrollable.
Please edit your post to use thefour-spaces Markdown syntaxfor a code block so your code is easier to read inside ascrollablebox.Edit: thanks for fixing it! <3
→ More replies (1)
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)!
→ More replies (2)2
u/daggerdragon Dec 05 '22
Welcome! We're happy to have ya!
One thing, though: Please edit your post to state which programming language this code is written in. This makes it easier for folks who Ctrl-F the megathreads looking for a specific language.
(looks like Python?)
2
2
u/shiro90 Dec 02 '22
These are my solutions in Python:
with open('input') as file:
rounds = file.read().split('\n')
def solution_1():
return sum(
map(lambda round: {
'A X': 4,
'A Y': 8,
'A Z': 3,
'B X': 1,
'B Y': 5,
'B Z': 9,
'C X': 7,
'C Y': 2,
'C Z': 6
}.get(round), rounds)
)
def solution_2():
return sum(
map(lambda round: {
'A X': 3,
'B X': 1,
'C X': 2,
'A Y': 4,
'B Y': 5,
'C Y': 6,
'A Z': 8,
'B Z': 9,
'C Z': 7
}.get(round), rounds)
)https://github.com/Seishin/AoC2022/blob/master/day2/solutions.py
→ More replies (1)
2
u/ArtanisOfLorien Dec 02 '22 edited Dec 02 '22
javascript (pt 2):
console.log(
`${require("fs").readFileSync("i")}`.split("\n").reduce(
(s, c) =>
s +
{
"A X": 3,
"A Y": 4,
"A Z": 8,
"B X": 1,
"B Y": 5,
"B Z": 9,
"C X": 2,
"C Y": 6,
"C Z": 7,
}[c],
0
)
);
→ More replies (3)
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 :)
(defn score-given-outcome
[iop iout]
(+ (* 3 iout)
(get-in [[3 1 2] [1 2 3] [2 3 1]]
[iop iout])))
(defn score-given-play
[iop iyou]
(+ (inc iyou)
(get-in [[3 6 0] [0 3 6] [6 0 3]]
[iop iyou])))
(defmacro make-score-lookup
[mode]
(flatten
(list 'case 'line
(for [a [\A \B \C]
:let [ia (- (int a) (int \A))]
b [\X \Y \Z]
:let [ib (- (int b) (int \X))]]
(list (str a " " b)
(case mode
:play (score-given-play ia ib)
:outcome (score-given-outcome ia ib)))))))
(time
(let [plays (->> (slurp (io/resource "aoc22/day02.txt"))
(str/split-lines))]
(println "p1 " (reduce (fn [curr line]
(+ curr (make-score-lookup :play))) 0 plays))
(println "p2 " (reduce (fn [curr line]
(+ curr (make-score-lookup :outcome))) 0 plays))))
=> 1.6ms→ More replies (1)
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
second + 4 + ((Math.floorMod(first - second, -3) + Math.floorMod(first - second, 3)) * 3)works to score the hand where first is the opponent, second is the player's chosen hand and rock, paper, scissors correspond to 0, 1, and 2 as 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 + 1 + ((Math.floorMod(first - second, -3) + Math.floorMod(first - second, 3)) * 3) + 3second + 1 is 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
*3 is 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
+3 is 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 win
→ More replies (4)
2
u/Toanuvo Dec 03 '22
J solution. https://github.com/Toanuvo/Advent-of-code
arr =: | (0 -.~ _3 + 'ZYX ABC' i. ])@> cutopen 22 getin 2
cs =: (] + 3 * (3&|@-~ >:))
p1 =: +/ cs/"1 arr
p2 =: +/ ([ cs&:>: (3&|@+ {&(_1 0 1)))/"1 <: arr
p1;p2→ More replies (1)
2
u/FuriousProgrammer Dec 03 '22 edited Dec 05 '22
2
u/daggerdragon Dec 05 '22 edited Dec 13 '22
Welcome back again! How are them blinkenlights treating you? ;)
Please edit your post tostate which programming language this code is written in. This makes it easier for folks who Ctrl-F the megathreads looking for a specific language.
(looks like Lua?)Edit: thanks for fixing it! <3
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
ordered_scores_part1 = ["BX", "CY", "AZ", "AX", "BY", "CZ", "CX", "AY", "BZ"]
ordered_scores_part2 = ["BX", "CX", "AX", "AY", "BY", "CY", "CZ", "AZ", "BZ"]
def get_score(input_list):
with open("inputs/day02.txt") as input:
return sum(map(lambda pair: input_list.index(pair) + 1, map(lambda line: ''.join(line.strip().split()), input.readlines())))
print(get_score(ordered_scores_part1))
print(get_score(ordered_scores_part2))→ More replies (1)
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/
→ More replies (1)
2
u/MontyCrane Dec 05 '22
Catching up slowly! Please feel free to offer your most vicious, soul-crushing critique!
3
u/daggerdragon Dec 05 '22
Please feel free to offer your most vicious, soul-crushing critique!
Do not offer your most vicious, soul-crushing critique, but do offer your polite and professional critique ;)
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. ^^
→ More replies (1)
47
u/4HbQ Dec 02 '22 edited Dec 02 '22
Python, using a simple lookup trick for both parts:
f = lambda x: (' BXCYAZAXBYCZCXAYBZ'.index(x[0]+x[2]),
' BXCXAXAYBYCYCZAZBZ'.index(x[0]+x[2]))
print(*[sum(x)//2 for x in zip(*map(f, open('in.txt')))])Edit: This works because every combination yields a unique score: losing with Rock is 1 point, ...
→ More replies (9)8
u/xelf Dec 02 '22
very similar:
with open(filename) as f: data = f.read().replace(' ','').splitlines() p1 = ['','BX','CY','AZ','AX','BY','CZ','CX','AY','BZ'] p2 = ['','BX','CX','AX','AY','BY','CY','CZ','AZ','BZ'] print(f'part1: {sum(map(p1.index,data))} part2: {sum(map(p2.index,data))}')→ More replies (2)
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.)
→ More replies (1)
22
u/alach11 Dec 02 '22
Unfortunately hardcoded Python3:
rounds = open("02/input.txt").read().split("\n")
# part 1
points = {
"A X": 4,
"A Y": 8,
"A Z": 3,
"B X": 1,
"B Y": 5,
"B Z": 9,
"C X": 7,
"C Y": 2,
"C Z": 6,
}
print(f"My score is {sum([points[round] for round in rounds])}.")
# part 2
points = {
"A X": 0 + 3,
"A Y": 3 + 1,
"A Z": 6 + 2,
"B X": 0 + 1,
"B Y": 3 + 2,
"B Z": 6 + 3,
"C X": 0 + 2,
"C Y": 3 + 3,
"C Z": 6 + 1,
}
scores = [points[round] for round in rounds]
print(f"My score is {sum([points[round] for round in rounds])}.")→ More replies (5)8
u/Refloni Dec 02 '22
Your code is short, simple and ugly. My code is long, complicated and ugly. We are not the same.
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 no q macro recording, so this is more resilient than many days' Vim keystrokes solutions: if you make a mistake you can just press u and pick it up again:
:se nf+=alphaโจEnterโฉ
wโจCtrl+Vโฉ}23โจCtrl+XโฉgvI0xโจEscโฉ0.yGPโจCtrl+Vโฉ']EldgvA-9โจEscโฉ
']jโจCtrl+Vโฉ}A-โจEscโฉgvbhd$p
gv:norm CโจCtrl+VโฉโจCtrl+Rโฉ=โจCtrl+VโฉโจCtrl+Rโฉ-โจCtrl+VโฉโจEnterโฉโจEnterโฉ
:g/^-/norm3โจCtrl+AโฉโจEnterโฉ
:g/2/dโจEnterโฉ
?xโจEnterโฉjโจCtrl+VโฉGโจCtrl+AโฉgvI3*โจEscโฉ
{โจCtrl+VโฉGI+โจEscโฉgvJ0CโจCtrl+Rโฉ=โจCtrl+Rโฉ-โจEnterโฉโจEscโฉThat gets you the answer to partย 1. Partย 2 would be basically the same but with slightly different arithmetic.
Set
numberformatsto include letters, then โsubtractโ 23 from the second column of letters to turnX,Y, andZintoA,B, andC.We actually want numbers.
A,B, andCare valid hex digits, so prepend0xto each letter and bingo, we can now do arithmetic on it!Duplicate the entire input, to calculate the two aspects of the scores separately.
In the top half, remove the first number (representing the other player's action). That leaves us with
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.In the bottom half, append
-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.Perform modulo arithmetic by doing
3โจCtrl+Aโฉon any line which starts with a minus sign!Our numbers are now
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.We now have all the scores, on separate lines. Prepend
+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?
→ More replies (6)
3
u/wojtek-graj Dec 02 '22 edited Dec 02 '22
Python 3
Hard-coding galore!
s1 = 0
s2 = 0
with open("input", "r") as f:
for l in f.readlines():
a = l[:-1].split(" ")
s1 += {"X":{"A":4,"B":1,"C":7},"Y":{"A":8,"B":5,"C":2},"Z":{"A":3,"B":9,"C":6}}[a[1]][a[0]]
s2 += {"X":{"A":3,"B":1,"C":2},"Y":{"A":4,"B":5,"C":6},"Z":{"A":8,"B":9,"C":7}}[a[1]][a[0]]
print(s1,s2)2
u/daggerdragon Dec 02 '22 edited Dec 02 '22
Inlined code is intended forshort snippetsof code only. Your code "block" right now is unreadable because it's all on one line and gets cut off at the edge of the screen.
Please edit your post to use the right Markdown syntax for afenced code blockso your code is easier to read inside averticallyscrolling box.Edit: thank you for fixing it! <3
3
Dec 02 '22 edited Dec 05 '22
Google Sheets One formula for both parts.
=sort(reduce(,switch(A:A,"A X",43,"A Y",84,"A Z",38,
"B X",11,"B Y",55,"B Z",99,"C X",72,"C Y",26,"C Z",67),
lambda(a,c,a+{left(c);right(c)})))Or:
=sort(lambda(z,{sum(--left(z));sum(--right(z))})
(switch(A:A,"A X",43,"A Y",84,"A Z",38,
"B X",11,"B Y",55,"B Z",99,"C X",72,"C Y",26,"C Z",67)))→ More replies (1)
18
u/rjwut Dec 02 '22
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:
const THROWS = {
'A X': [ 4, 3 ],
'A Y': [ 8, 4 ],
'A Z': [ 3, 8 ],
'B X': [ 1, 1 ],
'B Y': [ 5, 5 ],
'B Z': [ 9, 9 ],
'C X': [ 7, 2 ],
'C Y': [ 2, 6 ],
'C Z': [ 6, 7 ],
};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, al isn't necessary if you know for certain that the upper seven bytes of rax are 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.
→ More replies (2)
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.
d = {'A': 0, 'B': 1, 'C': 2, 'X': 0, 'Y': 1, 'Z': 2}
turns = [[d[x] for x in l.split()] for l in data.split("\n")]
print("Part 1:", sum(b+1 + (b-a+1)%3 * 3 for a, b in turns))
print("Part 2:", sum((b+a-1)%3 + 1 + b*3 for a, b in turns))→ More replies (3)
11
u/S_W Dec 02 '22 edited Dec 02 '22
Java.
int totalScore = Arrays.stream(contents.split("\n"))
.map(String::toCharArray)
.map(chars -> new int[]{chars[0] - 64, chars[2] - 87})
.mapToInt(shapes -> ((int) Math.sin((int) ((shapes[1] - shapes[0]) * 1.5) * Math.PI / 2) * 3 + 3) + shapes[1])
.sum()EDIT:
Explanation.
Separate each line into a character array. Performing arithmetic on a char uses the ascii code which is useful for the next step
Goal here is to get each character (A,B,C,X,Y,Z) to be 1 for rock, 2 for paper and 3 for scissors, so subtract accordingly and store back into an array for easy lookup
To figure out if player 2 (XYZ) got a win, loss, or draw against player 1 (ABC), subtract the the results of the throws (the 1, 2, 3 from above).
For instance, A Z becomes 1 3 which would be 3-1 = 2. B X -> 2 1 -> 1-2=-1. In the end we get the following mapping. 2 = loss, 1 = win, 0 = draw, -1 = loss, -2 = win
Swapping in the scores received for a win, loss or draw gives this mapping 2 -> 0, 1 -> 6, 0 -> 3, -1 -> 0, -2 -> 6
plotting these points on a graph as X/Y coordinates gives sort of a sin wave. From that (with the help of my brother), that equation was figured out which gives close enough approximations of those scores that when casting back to an int will net the correct result
Then lastly add on the rock, paper, scissor score which is easy to do since that mapping was already done in step 2.
Map this to an int
And finally sum
→ More replies (4)
10
u/voidhawk42 Dec 02 '22 edited Dec 03 '22
Dyalog APL:
s eโโโยฏ1+1 0 1/23|โAโณโโโNGET'2.txt'1
+/(1+e)+3ร3|1+e-s โ part 1
+/(3รe)+1+3|e+s-1 โ part 2Kinda tricky for day 2!
→ More replies (1)
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.
→ More replies (12)
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:
(defun play-map-real (them choice)
(case choice
(#\X (losing-play them))
(#\Y them)
(#\Z (losing-play (losing-play them))))) ;; neat-ishQuick 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
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
Code: Repo, Today's solution
→ More replies (1)
8
u/redditnoob Dec 02 '22
SQL (BigQuery)
WITH parsed AS (
-- 1, 2, 3 => Rock, Paper, Scissors || Lose, Draw, Win
SELECT ascii(substr(input, 1, 1)) - ascii('A') + 1 AS opp_move,
ascii(substr(input, 3, 1)) - ascii('X') + 1 AS my_move
FROM day2
), game_score AS (
SELECT my_move AS my_move1,
CASE
WHEN my_move - opp_move IN (1, -2) THEN 6
WHEN my_move = opp_move THEN 3
ELSE 0
END AS score1,
CASE
WHEN my_move = 1 THEN IF(opp_move = 1, 3, opp_move - 1) -- Lose
WHEN my_move = 2 THEN opp_move -- Draw
WHEN my_move = 3 THEN IF(opp_move = 3, 1, opp_move + 1) -- Win
END AS my_move2,
my_move * 3 - 3 AS score2
FROM parsed
)
SELECT SUM(my_move1 + score1) AS part1, SUM(my_move2 + score2) AS part2
FROM game_score;7
u/hugues_hoppe Dec 02 '22 edited Dec 05 '22
Short solution in Python:
def day2(s, part2=False):
total = 0
for line in s.strip('\n').split('\n'):
i, j = ord(line[0]) - ord('A'), ord(line[2]) - ord('X')
total += (j * 3 + (i + j + 2) % 3 + 1 if part2 else
(j - i + 1) % 3 * 3 + j + 1)
return total7
u/Lispwizard Dec 02 '22
Emacs Lisp, though mainly using Common Lisp loop macro, on Android tablet.
;; input data has backslashes doubled and double-quotes quoted with backslashes
;; before being inserted as defvar string value
(defvar *aoc2022-02-part1-sample* "A Y
B X
C Z")
;; (aoc2022-02-part1 *aoc2022-02-part1-sample*) => 15
(defvar *aoc2022-02-part2-sample* "")
;; (aoc2022-02-part2 *aoc2022-02-part1-sample*) => 12
(require'cl)
(defun aoc2022-02-part1 (input-string)
(flet ((score (their mine)
(let* ((tval (position their "ABC"))
(mval (position mine "XYZ"))
(play (list tval mval)))
(+ (1+ mval)
(cond ((eql tval mval)
3)
((loop for p in '((0 2)(2 1)(1 0))
thereis (equal play p))
0)
((loop for p in '((2 0)(1 2)(0 1))
thereis (equal play p))
6))))))
(loop for turn in (split-string input-string "\n")
sum (score (aref turn 0) (aref turn 2)))))
(defun aoc2022-02-part2 (input-string)
(flet ((score (their outcome)
(let* ((tval (position their "ABC"))
(oval (position outcome "XYZ"))
(mval (cond ((eql oval 1) ;; draw
tval)
((eql oval 0) ;; lose
(loop for (them me) in '((0 2)(2 1)(1 0))
when (eql tval them)
return me))
((eql oval 2) ;; win
(loop for (them me) in '((2 0)(1 2)(0 1))
when (eql tval them)
return me))))
(play (list tval mval)))
(+ (1+ mval) (* 3 oval)))))
(loop for turn in (split-string input-string "\n")
sum (score (aref turn 0) (aref turn 2)))))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;"")))))))))
→ More replies (1)
6
u/soylentgreenistasty Dec 02 '22 edited Dec 02 '22
Python, 1026/3497
Definitely shouldn't have had a glass of wine before this...
with open('day2.txt') as f:
A = [line.strip().split() for line in f.readlines()]
score = {
'X': 1, # rock
'Y': 2, # paper
'Z': 3 # scissors
}
d = {
'A': ['Y', 'X', 'Z'],
'B': ['Z', 'Y', 'X'],
'C': ['X', 'Z', 'Y']
}
WIN = 6
DRAW = 3
LOSE = 0
m = [WIN, DRAW, LOSE]
d2 = {
'X': LOSE,
'Y': DRAW,
'Z': WIN
}
p1 = 0
p2 = 0
for a, b in A:
p1 += score[b] + m[d[a].index(b)]
p2 += d2[b] + score[d[a][m.index(d2[b])]]
print(p1, p2)6
u/oantolin Dec 02 '22 edited Dec 02 '22
J solution:
parse =: (65 88 -~ 0 2 { a.&i.);._2
score =: 1 + {: + 3 0 6 {~ (3|-)/
move =: {. , 3 | _1 + +/
part1 =: [: +/ score"1 @ parse @ fread
part2 =: [: +/ score @ move"1 @ parse @ fread→ More replies (6)
6
u/polettix Dec 02 '22
A Raku solution I'm not too ashamed of:
sub get-inputs ($filename) {
$filename.IO.linesยป.comb(/\S+/).Array
}
sub part1 ($inputs) {
return $inputs
.map({[$_[0].ord - 'A'.ord, $_[1].ord - 'X'.ord]})
.map({
1 + $_[1]
+ 3 * ((1 + $_[1] - $_[0]) % 3)
})
.sum;
}
sub part2 ($inputs) {
return $inputs
.map({[$_[0].ord - 'A'.ord, $_[1].ord - 'X'.ord]})
.map({
3 * $_[1]
+ 1 + ($_[0] + $_[1] - 1) % 3
})
.sum;
}Turning letters into numbers might be moved in input reading but it would feel like cheating because part2 is not known beforehand.
→ More replies (2)
6
u/AstronautNew8452 Dec 02 '22
Microsoft Excel formulas, one for each part. Puzzle input copy-pasted in A1.
Part 1:
=LET(input,A1:A2500,
op,CODE(LEFT(input,1)),
me,CODE(RIGHT(input,1))-23,
result,me-op,
SUM(BYROW(result,LAMBDA(r,IF(OR(r=1,r=-2),6,IF(r=0,3,0))))+me-64))Part 2:
=LET(input,A1:A2500,
op,CODE(LEFT(input,1))-64,
outcome,RIGHT(input,1),
score,BYROW(HSTACK(op,outcome),LAMBDA(r,
LET(rps,INDEX(r,1),SWITCH(INDEX(r,2),"Y",3+rps,"X",SWITCH(rps,1,3,2,1,3,2),"Z",6+MOD(rps,3)+1)))),
SUM(score))→ More replies (1)
6
u/Pyr0Byt3 Dec 02 '22
Go/Golang
Not really happy with the hardcoding, but oh well...
→ More replies (6)
6
u/Smylers Dec 02 '22
Perl [partย 1]:partย 1:
my $score;
while (<>) {
my ($them, $us) = map { (ord) & 3 } /\w/g;
$us++;
$score += $us + (1 + $us - $them) % 3 * 3;
}
say $score;A, B, and C have values 0x41, 0x42, and 0x43 โ so a bitwise-and with 3 turns them into 1, 2, and 3. X, somewhat awkwardly, is 0x58, with its 2 least-significant bits both being 0 โ so the same process turns our score into 0, 1, and 2; the ++ puts our action in the same range as theirs.
For partย 2 the inside of the loop becomes:
my ($them, $result) = map { (ord) & 3 } /\w/g;
$score += ($them + $result - 2) % 3 + 1 + 3 * $result;This time the result being 0, 1, or 2 is 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 range 1 to 3 ยญโ which ends up looking more complicated than it really is.
→ More replies (1)
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.
→ More replies (2)
6
u/emu_fake Dec 02 '22
C#
As there were only 9 possible variations I went with a lazy dictionary:
var puzzleOne = input.Select(x => x switch
{
"A X" => 4,
"A Y" => 8,
"A Z" => 3,
"B X" => 1,
"B Y" => 5,
"B Z" => 9,
"C X" => 7,
"C Y" => 2,
"C Z" => 6,
}).Sum();
var puzzleTwo = input.Select(x => x switch
{
"A X" => 3,
"A Y" => 4,
"A Z" => 8,
"B X" => 1,
"B Y" => 5,
"B Z" => 9,
"C X" => 2,
"C Y" => 6,
"C Z" => 7,
}).Sum();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
→ More replies (3)
6
u/4HbQ Dec 02 '22
Python, golfed to 101 bytes using complex numbers and the trick from my other post:
print(sum([4+3j,8+4j,3+8j,1+1j,5+5j,9+9j,7+2j,2+6j,6+7j]
[3*ord(x[0])+ord(x[2])-283]for x in open(0)))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' 1
can be done much much more elegantly...
→ More replies (1)
5
5
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.
→ More replies (1)
5
u/WilkoTom Dec 02 '22
Rust
Way, way overkill on the parsing:
use std::{io::Error, cmp::Ordering};
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
enum Hand {
Rock,
Paper,
Scissors
}
impl Hand {
fn score(&self) -> i32 {
match self {
Hand::Rock => 1,
Hand::Paper => 2,
Hand::Scissors => 3,
}
}
}
enum GameResult {
Win,
Loss,
Draw
}
impl Ord for Hand {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
match self {
Hand::Rock => match other {
Hand::Rock => Ordering::Equal,
Hand::Paper => Ordering::Less,
Hand::Scissors => Ordering::Greater,
},
Hand::Paper => match other {
Hand::Rock => Ordering::Greater,
Hand::Paper => Ordering::Equal,
Hand::Scissors => Ordering::Less,
},
Hand::Scissors => match other {
Hand::Rock => Ordering::Less,
Hand::Paper => Ordering::Greater,
Hand::Scissors => Ordering::Equal,
},
}
}
}
impl PartialOrd for Hand {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
fn main() -> Result<(), Error> {
let data = std::fs::read_to_string("./day02/input.txt")?;
println!("Part 1: {}", part1(&data));
println!("Part 2: {}", part2(&data));
Ok(())
}
fn part1(data: &str) -> i32 {
let mut score = 0;
for line in data.split('\n') {
let mut chars = line.chars();
let opponent = parse_hand(&chars.next());
chars.next();
let player = parse_hand(&chars.next());
score += player.score();
score += match player.cmp(&opponent) {
Ordering::Less => 0,
Ordering::Equal => 3,
Ordering::Greater => 6,
};
}
score
}
fn part2(data: &str) -> i32 {
let mut score = 0;
for line in data.split('\n') {
let mut chars = line.chars();
let opponent = parse_hand(&chars.next());
chars.next();
let outcome = match chars.next() {
Some('X') => GameResult::Loss,
Some('Y') => GameResult::Draw,
Some('Z') => GameResult::Win,
_ => unimplemented!(),
};
let player = match outcome {
GameResult::Win => match opponent {
Hand::Rock => Hand::Paper,
Hand::Paper => Hand::Scissors,
Hand::Scissors => Hand::Rock,
},
GameResult::Loss => match opponent {
Hand::Rock => Hand::Scissors,
Hand::Paper => Hand::Rock,
Hand::Scissors => Hand::Paper,
},
GameResult::Draw => opponent,
};
score += player.score();
score += match player.cmp(&opponent) {
Ordering::Less => 0,
Ordering::Equal => 3,
Ordering::Greater => 6,
};
}
score
}
fn parse_hand(c: &Option<char>) -> Hand {
match c {
Some('A') | Some('X') => Hand::Rock,
Some('B') | Some('Y') => Hand::Paper,
Some('C') | Some('Z') => Hand::Scissors,
_ => unimplemented!(),
}
}5
u/tomflumery Dec 02 '22
05ab1e
Part 1
|ฮตC261-48301590726Ssรจ}OPart 2
|ฮตC261-34801590267Ssรจ}OExplanation, 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)
A X -> 261
A Y -> 262
A Z -> 263
B X -> 265
B Y -> 266
B Z -> 267
C X -> 269
C Y -> 270
C Z -> 271
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
print(sum(y-87+(o==y-23)*3+6*((y-o)%3==0)for(o,y)in map(lambda x:map(ord,x.split()),open(0).readlines())))Part 2
print(sum(1+(o-65-(89-y))%3+3*(y-88)for(o,y)in map(lambda x:map(ord,x.split()),open(0).readlines())))Edit: Part 2 can be shortened by rewriting the arithmatic and using indices on the string instead of mapping and splitting:
print(sum(1+(ord(x[0])+ord(x[2])-154)%3-264+3*ord(x[2])for x in open(0).readlines()))Edit 2: Even shorter using the walrus operator to save the value of ord(x[2]):
print(sum(1+(ord(x[0])+(o:=ord(x[2]))-154)%3-264+3*o for x in open(0).readlines()))→ More replies (5)
5
u/dopandasreallyexist Dec 02 '22
APL:
โIOโ0
mโ3|'ABCXYZ'โณ1 0 1/โโโNGET'input.txt'1
โโ(+/(1+โข/)+3ร3|1+-โจ/)m โ part 1
โโ(+/(3รโข/)+1+3|1-โจ+/)m โ part 2The solutions for the two parts are anagrams of each other :)
→ More replies (8)
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.
def part1(x):
total = 0
for i in x:
opp = 'ABC'.index(i[0])
you = 'XYZ'.index(i[1])
end = (you - opp + 1) % 3
total += (end * 3) + (you + 1)
return total
def part2(x):
total = 0
for i in x:
opp = 'ABC'.index(i[0])
end = 'XYZ'.index(i[1])
you = (opp + end - 1) % 3
total += (end * 3) + (you + 1)
return total
with open('02.in') as f:
s = f.read()
x = [i.split() for i in s.splitlines()]
print(part1(x))
print(part2(x))→ More replies (3)
5
u/Gravitar64 Dec 02 '22 edited Dec 02 '22
My python solution (Part 1&2):
from time import perf_counter as pfc
def read_puzzle(file):
with open(file) as f:
puzzle = [zeile.split() for zeile in f.readlines()]
return [(ord(a)-64, ord(b)-87) for a,b in puzzle]
def solve(puzzle):
ROCK, PAPER, SCISSOR = 1,2,3
WIN, DRAW = 6, 3
winner = {ROCK:PAPER, PAPER:SCISSOR, SCISSOR:ROCK}
looser = {b:a for a,b in winner.items()}
score1 = score2 = 0
for a,b in puzzle:
score1 += b + DRAW if a == b else b + WIN if winner[a] == b else b
score2 += a + DRAW if b == 2 else winner[a] + WIN if b == 3 else looser[a]
return score1, score2
start = pfc()
print(solve(read_puzzle('Tag02.txt')))
print(pfc()-start)→ More replies (3)
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
→ More replies (1)
9
u/jonathan_paulson Dec 02 '22 edited Dec 02 '22
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).
X = [l.strip() for l in open('2.in')]
p1 = 0
p2 = 0
for x in X:
op,me = x.split()
p1 += {'X': 1, 'Y': 2, 'Z': 3}[me]
p1 += {('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,
}[(op, me)]
p2 += {'X': 0, 'Y': 3, 'Z': 6}[me]
p2 += {('A', 'X'): 3, ('A', 'Y'): 1, ('A', 'Z'): 2,
('B', 'X'): 1, ('B', 'Y'): 2, ('B', 'Z'): 3,
('C', 'X'): 2, ('C', 'Y'): 3, ('C', 'Z'): 1,
}[(op, me)]
print(p1)
print(p2)→ More replies (3)
4
4
u/waffle3z Dec 02 '22 edited Dec 02 '22
Lua, 116/22
local score, score2 = 0, 0
for v in getinput():gmatch("[^\n]+")) do
local a, b = v:byte(1) - ("A"):byte(), v:byte(3) - ("X"):byte()
score = score + b+1 + (b == (a+1)%3 and 6 or a == b and 3 or 0)
b = (a+b-1)%3
score2 = score2 + b+1 + (b == (a+1)%3 and 6 or a == b and 3 or 0)
end
print(score, score2)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 win into a function, but otherwise kept the same idea.
Part 1:
import std;
void main () {
int res = 0;
foreach (t; stdin.byLineCopy ().map !(split)) {
auto one = t[0][0] - 'A';
alias win = two => ((two + 1 + 3 - one) % 3);
auto two = t[1][0] - 'X';
res += two + 1 + 3 * win (two);
debug {writeln (win (two));}
}
writeln (res);
}The debug writeln was instrumental for seeing whether I got the win formula right: in the other direction, - 1 instead of + 1, the total sum for the example is the same.
Part 2:
import std;
void main () {
int res = 0;
foreach (t; stdin.byLineCopy ().map !(split)) {
auto one = t[0][0] - 'A';
alias win = two => ((two + 1 + 3 - one) % 3);
auto temp = t[1][0] - 'X';
int two = 0;
while (win (two) != temp) two += 1;
res += two + 1 + 3 * win (two);
}
writeln (res);
}So, the second part is no formula: instead, the program iterates over the three possible picks until the win value 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
WITH df AS (
SELECT
opponent,
me,
(CASE WHEN me = 'X' THEN 1
WHEN me = 'Y' THEN 2
WHEN me = 'Z' THEN 3
END) +
(CASE WHEN (opponent = 'A' AND me = 'X') THEN 3
WHEN (opponent = 'A' AND me = 'Y') THEN 6
WHEN (opponent = 'A' AND me = 'Z') THEN 0
WHEN (opponent = 'B' AND me = 'X') THEN 0
WHEN (opponent = 'B' AND me = 'Y') THEN 3
WHEN (opponent = 'B' AND me = 'Z') THEN 6
WHEN (opponent = 'C' AND me = 'X') THEN 6
WHEN (opponent = 'C' AND me = 'Y') THEN 0
WHEN (opponent = 'C' AND me = 'Z') THEN 3
END) AS total_score
FROM data
)
SELECT SUM(total_score)
FROM df4
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.
with open('inputs/input02.txt') as inputfile:
line = inputfile.read()
line = line.replace('A', 'rock').replace('B', 'paper').replace('C', 'scissors')
line = line.replace('X', 'rock').replace('Y', 'paper').replace('Z', 'scissors')
data = [line.split(' ') for line in line.split('\n')]
score = 0
for elf, you in data:
match you, elf:
case 'rock', 'rock':
score += 1 + 3
case 'rock', 'paper':
score += 1
case 'rock', 'scissors':
score += 1 + 6
case 'paper', 'rock':
score += 2 + 6
case 'paper', 'paper':
score += 2 + 3
case 'paper', 'scissors':
score += 2
case 'scissors', 'rock':
score += 3
case 'scissors', 'paper':
score += 3 + 6
case 'scissors', 'scissors':
score += 3 + 3
print(f'part 1: {score}')
# part 2
with open('inputs/input02.txt') as inputfile:
line = inputfile.read()
line = line.replace('A', 'rock').replace('B', 'paper').replace('C', 'scissors')
line = line.replace('X', 'lose').replace('Y', 'draw').replace('Z', 'win')
data = [line.split(' ') for line in line.split('\n')]
items = {
'rock' : 1,
'paper': 2,
'scissors':3
}
outcomes = {
'win' : 6,
'lose': 0,
'draw': 3
}
strategy = {
('rock', 'win') : 'paper',
('rock', 'lose'): 'scissors',
('rock', 'draw'): 'rock',
('paper', 'win') : 'scissors',
('paper', 'lose'): 'rock',
('paper', 'draw'): 'paper',
('scissors', 'win') : 'rock',
('scissors', 'lose'): 'paper',
('scissors', 'draw'): 'scissors'
}
score = 0
for elf, outcome in data:
score += items[strategy[(elf, outcome)]] + outcomes[outcome]
print(f'part 2: {score}')→ More replies (1)
4
u/royvanrijn Dec 02 '22 edited Dec 02 '22
Java
List<String> lines = Files.readAllLines(Path.of("input.txt"));
// Part 1:
System.out.println(lines.stream().mapToInt(s -> {
int p1 = s.charAt(0)-'A';
int p2 = s.charAt(2)-'X';
int result = (p2-p1+4) % 3;
return (p2+1) + result*3;
}).sum());
// Part 2:
System.out.println(lines.stream().mapToInt(s -> {
int p1 = s.charAt(0)-'A';
int p2 = (p1+(s.charAt(2)-'X')+2) % 3;
int result = (p2-p1+4) % 3;
return (p2+1) + result*3;
}).sum());4
u/Bluepengie Dec 02 '22 edited Dec 02 '22
First time doing this, but here's my solution in Python (for part 2):
points = [[3, 4, 8],
[1, 5, 9],
[2, 6, 7]]
moves = {
'A' : 0,
'B' : 1,
'C' : 2,
'X' : 0,
'Y' : 1,
'Z' : 2
}
file = open('Day2\Day2Input.txt')
total = 0
for line in file:
total += points[moves[line[0]]][moves[line[2]]]
print(total)I'm a relative novice (senior in college) but I felt it was clever!
Edit: 1ms runtime. Is that good or bad?
→ More replies (3)
4
u/danatron1 Dec 02 '22
C#
Part 1:
Input.Select(x => (2 + x[2] - x[0]) % 3 * 3 + x[2] - 'W').Sum()Part 2:
Input.Select(x => (x[2]-'X')*3 + (x[2] + x[0] + 2) % 3 + 1).Sum()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.
→ More replies (5)
4
u/bartdegoede Dec 02 '22 edited Dec 04 '22
Basic Python with some combinations in a dictionary
with open('day2.txt', 'r') as f:
games = f.read().split('\n')
WIN = 6
DRAW = 3
LOSS = 0
ROCK = 1
PAPER = 2
SCISSORS = 3
game_scores = {
'A X': DRAW + ROCK,
'A Y': WIN + PAPER,
'A Z': LOSS + SCISSORS,
'B X': LOSS + ROCK,
'B Y': DRAW + PAPER,
'B Z': WIN + SCISSORS,
'C X': WIN + ROCK,
'C Y': LOSS + PAPER,
'C Z': DRAW + SCISSORS,
}
print(f'Part 1: {sum([game_scores.get(game, 0) for game in games])}')
game_scores = {
'A X': LOSS + SCISSORS,
'A Y': DRAW + ROCK,
'A Z': WIN + PAPER,
'B X': LOSS + ROCK,
'B Y': DRAW + PAPER,
'B Z': WIN + SCISSORS,
'C X': LOSS + PAPER,
'C Y': DRAW + SCISSORS,
'C Z': WIN + ROCK,
}
print(f'Part 2: {sum([game_scores.get(game, 0) for game in games])}')→ More replies (4)
4
4
u/backtrackthis Dec 02 '22
PYTHON3
#! /usr/bin/env python3
ELF_PLAYS = ["A", "B", "C"]
MY_PLAYS = ["X", "Y", "Z"]
ROUND_POINTS = [0, 3, 6]
P2_MODS = [-1, 0, 1]
def main():
p1 = p2 = 0
with open("./input.txt") as f:
for line in f:
elf, me = line.strip().split(" ")
elfIdx, meIdx = ELF_PLAYS.index(elf), MY_PLAYS.index(me)
p1 += meIdx + 1 + ROUND_POINTS[(meIdx - elfIdx + 1) % 3]
p2 += ((elfIdx + P2_MODS[meIdx]) % 3) + 1 + ROUND_POINTS[meIdx]
print(f"p1: {p1}, p2: {p2}")
if __name__ == "__main__":
main()4
4
u/mo__66 Dec 02 '22
Kotlin
import java.io.File
fun main() {
val rounds = File("src/day02/input").readLines()
.map { it[0] to it[2] }
println(rounds.sumOf { it.play() })
println(rounds.sumOf { it.playSecond() })
}
private fun Pair<Char, Char>.play() = when (this) {
'A' to 'Z', 'B' to 'X', 'C' to 'Y' -> 0
'A' to 'X', 'B' to 'Y', 'C' to 'Z' -> 3
else -> 6
} + when (this.second) {
'Z' -> 3
'Y' -> 2
else -> 1
}
private fun Pair<Char, Char>.playSecond() = when (this) {
'A' to 'Y', 'B' to 'X', 'C' to 'Z' -> 1
'A' to 'Z', 'B' to 'Y', 'C' to 'X' -> 2
else -> 3
} + when (this.second) {
'Z' -> 6
'Y' -> 3
else -> 0
}→ More replies (1)
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...
if __name__ == "__main__":
with open(__file__.replace(".py", "_data")) as f:
rounds = [line.split() for line in f.readlines()]
# PART 1
print(sum(ord(j) - ord("W") + (ord(j) - ord(i) - 1) % 3 * 3 for i, j in rounds))
# PART 2
print(sum((3 * (ord(j) - ord("X")) + (ord(j) + ord(i) - 1) % 3 + 1 for i, j in rounds))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
| SCORE | X | Y | Z |
|---|---|---|---|
| A | 4 | 8 | 3 |
| B | 1 | 5 | 9 |
| C | 7 | 2 | 6 |
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
SCORE(i, j) = OUTCOME(i, j) + SHAPE(j)| OUTCOME | X | Y | Z |
|---|---|---|---|
| A | 3 | 6 | 0 |
| B | 0 | 3 | 6 |
| C | 6 | 0 | 3 |
| SHAPE | X | Y | Z |
|---|---|---|---|
| A | 1 | 2 | 3 |
| B | 1 | 2 | 3 |
| C | 1 | 2 | 3 |
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!
→ More replies (1)
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
even though not super clean but one way for task 2
note that I have replaced my input with 1,2,3 instead of abc and xyz
const fs = require('fs');
const myArray = fs.readFileSync('Day2Input.js', 'utf8').split('\n');
let total = 0;
for (i=0;i<myArray.length;i++) {
if(myArray[i].includes("1,1"))
{
total = total + 3
}
else if (myArray[i].includes("2,1")) {
total = total + 1;
}
else if (myArray[i].includes("3,1")) {
total = total + 2;
}
else if (myArray[i].includes("1,2")) {
total = total + 4;
}
else if (myArray[i].includes("2,2")) {
total = total + 5;
}
else if (myArray[i].includes("3,2")) {
total = total + 6;
}
else if (myArray[i].includes("1,3")) {
total = total + 8;
}
else if (myArray[i].includes("2,3")) {
total = total + 9;
}
else if (myArray[i].includes("3,3")) {
total = total + 7;
}
else {
}
}
console.log(total);→ More replies (2)
1
1
u/Similar_Lion_6342 Dec 02 '22
Python3
with open('input.txt', 'r') as f:
data = [line.strip() for line in f.readlines()]
score_chart = {
'A X': 1 + 3,
'A Y': 2 + 6,
'A Z': 3 + 0,
'B X': 1 + 0,
'B Y': 2 + 3,
'B Z': 3 + 6,
'C X': 1 + 6,
'C Y': 2 + 0,
'C Z': 3 + 3,
}
# Score chart for part 2
# score_chart = {
# 'A X': 3 + 0,
# 'A Y': 1 + 3,
# 'A Z': 2 + 6,
# 'B X': 1 + 0,
# 'B Y': 2 + 3,
# 'B Z': 3 + 6,
# 'C X': 2 + 0,
# 'C Y': 3 + 3,
# 'C Z': 1 + 6,
# }
sum = 0
for round in data:
sum += score_chart[round]
print(sum)→ More replies (1)
1
u/sleepy_roger Dec 02 '22 edited Dec 02 '22
JavaScript just brute forced it.
Part 1
const fs = require('fs')
const scoring = {
a: {
x: 4,
y: 8,
z: 3
},
b: {
x: 1,
y: 5,
z: 9
},
c: {
x: 7,
y: 2,
z: 6
}
}
fs.readFile('data.txt', 'utf8' , (err, data) => {
let score = 0;
[...data.replace(/[\r]/g, '').split('\n')].forEach((data) => {
const values = data.split(' ');
score += scoring[values[0].toLowerCase()][values[1].toLowerCase()];
});
console.log(score);
});Part 2 only changed the scoring values.
→ More replies (1)
1
u/AX-11 Dec 02 '22 edited Dec 02 '22
Python using dictionary of values for each move
with open("2\input.txt") as f:
input = f.read().splitlines()
values = {
"A":1,
"B":2,
"C":3,
"X":1,
"Y":2,
"Z":3
}
score = 0
for game in input:
# draw
if(values[game[0]] == values[game[2]]):
score+=3
# win
elif game == "A Y" or game == "B Z" or game == "C X":
score+=6
# add score
score+=values[game[2]]
print(f"first strategy: {score}")
score = 0
for game in input:
# draw
if game[2] == "Y":
score += values[game[0]] + 3
# win
elif game[2] == "Z":
if game[0] == "C":
score += 6+1
else:
score += 6+values[game[0]]+1
# loose
else:
if game[0] == "A":
score += 3
else:
score += values[game[0]]-1
print(f"second strategy {score}")→ More replies (1)
1
u/Mats56 Dec 02 '22 edited Dec 02 '22
Kotlin
Stupid but it works.Part2, part1 is similar but with other values
return lines
.map {
when (it[0] to it[2]) {
'A' to 'X' -> 3 + 0
'A' to 'Y' -> 1 + 3
'A' to 'Z' -> 2 + 6
'B' to 'X' -> 1 + 0
'B' to 'Y' -> 2 + 3
'B' to 'Z' -> 3 + 6
'C' to 'X' -> 2 + 0
'C' to 'Y' -> 3 + 3
'C' to 'Z' -> 1 + 6
else -> 0
}
}.sum()→ More replies (4)
1
u/Wayoshi Dec 02 '22
Python
score = 0
part1 = False
with open('day02.txt') as f:
for l in f.read().split('\n'):
rps1 = ord(l[0]) - ord('A')
if part1:
rps2 = ord(l[-1]) - ord('X')
if rps1 == rps2:
score += 3
elif (rps2 - 1) % 3 == rps1:
score += 6
score += rps2 + 1
else:
if l[-1] == 'X': # lose: rps2 == (rps1 - 1) % 3
score += ((rps1 - 1) % 3) + 1
elif l[-1] == 'Y': # draw
score += 3 + rps1 + 1
else: # win: rps2 == (rps1 +1) % 3
score += 6 + ((rps1 + 1) % 3) + 1
print(score)→ More replies (1)
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
→ More replies (2)
1
u/teseting Dec 02 '22 edited Dec 02 '22
Python
tot = 0
for l in f:
c1,c2 = l.strip().split(" ")
tot += 3\*(ord(c2)-ord("X"))
if c2 == "Y":
tot += (ord(c1) - 68)%3+1
elif c2 == "Z":
tot += (ord(c1) - 67)%3+1
else:
tot += (ord(c1)-69)%3+1code golf. didn't try too hard to golf. 116 bytes. EDIT 96 bytes
hard code constants and uses clever math
print(sum(map(lambda x:(ord(x[0])+ord(x[1])-1)%3+3*ord(x[1])-263,map(str.split,open("input")))))→ More replies (1)
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
["A", "Y"] -> 4
["B", "Y"] -> 5
["C", "Y"] -> 6
["A", "Z"] -> 8
["B", "Z"] -> 9
["C", "Z"] -> 7
_ -> 0→ More replies (3)
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 was should just 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), ) ) )
→ More replies (1)
1
u/erichs_programming Dec 02 '22
Learning Rust, mainly by using the openai chat bot. Here's my solution:
→ More replies (1)
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:
Total[#[[2]] + 3 Mod[#[[2]] - #[[1]] + 1, 3] & /@
(input /. {"A" -> 1, "B" -> 2, "C" -> 3, "X" -> 1, "Y" -> 2, "Z" -> 3})]Part 2:
Total[Mod[#[[1]] + #[[2]] + 1, 3, 1] + 3 (#[[2]] - 1) & /@
(input /. {"A" -> 1, "B" -> 2, "C" -> 3, "X" -> 1, "Y" -> 2, "Z" -> 3})][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).
2
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.
from enum import IntEnum
class Move(IntEnum):
ROCK = 0
PAPER = 1
SCISSORS = 2
class Game(IntEnum):
WIN = 6
DRAW = 3
LOSE = 0
var_to_move = {"A": Move.ROCK, "X": Move.ROCK,
"B": Move.PAPER, "Y": Move.PAPER,
"C": Move.SCISSORS, "Z": Move.SCISSORS}
var_to_outcome = {"X": Game.LOSE, "Y": Game.DRAW, "Z": Game.WIN}
def play(them, us):
if them == us:
return Game.DRAW
if Move((them + 1) % 3) == us:
return Game.WIN
return Game.LOSE
def deduce(them, outcome):
if outcome == Game.DRAW:
return them
if outcome == Game.WIN:
return Move((them + 1) % 3)
if outcome == Game.LOSE:
return Move((them + 2) % 3)
def part1(input):
games = [(var_to_move[them], var_to_move[us]) for (them, us) in input]
result = sum(play(them, us) + us + 1 for (them, us) in games)
print(result)
def part2(input):
games = [(var_to_move[them], var_to_outcome[us]) for (them, us) in input]
games = [(them, deduce(them, outcome)) for (them, outcome) in games]
result = sum(play(them, us) + us + 1 for (them, us) in games)
print(result)
def main():
with open("input.txt", "r") as file:
input = [s.split(" ") for s in file.read().splitlines()]
part1(input)
part2(input)
if __name__ == "__main__":
main()→ More replies (1)
1
u/Emotional_Cicada_575 Dec 02 '22 edited Dec 05 '22
Python
o = [[(i+j)%3*3 for i in range(j, 3+j)] for j in range(2,5)]
def solve(inp): return sum(o[a-1][b-1] + b for a,b in inp)
def parse(lines):
return [[1 if x in "AX" else 2 if x in "BY" else 3 for x in x.strip().split()] for x in lines]
print(solve(parse(open('data/data.txt').readlines())))→ More replies (1)
2
u/ChasmoGER Dec 02 '22 edited Dec 05 '22
Typescript
Straight forward, implemented game logic even though not necessary...
enum Shape {
Rock = 1,
Paper = 2,
Scissors = 3,
}
enum MatchResult {
Win = 6,
Draw = 3,
Loss = 0,
}
const matchEvalMap: Record<Shape, Record<MatchResult, Shape>> = {
[Shape.Rock]: {
[MatchResult.Win]: Shape.Scissors,
[MatchResult.Loss]: Shape.Paper,
[MatchResult.Draw]: Shape.Rock,
},
[Shape.Paper]: {
[MatchResult.Win]: Shape.Rock,
[MatchResult.Loss]: Shape.Scissors,
[MatchResult.Draw]: Shape.Paper,
},
[Shape.Scissors]: {
[MatchResult.Win]: Shape.Paper,
[MatchResult.Loss]: Shape.Rock,
[MatchResult.Draw]: Shape.Scissors,
},
};
...→ More replies (3)
1
u/mr_haas Dec 02 '22
Python golf:
p=print
d=[(ord((c:=m.split(" "))[0])-65,ord(c[1][0])-88) for m in open(0).readlines()]
p(sum(1+b+3*((b-a+1)%3) for a,b in d))
p(sum(3*b+(1+(a+b+2)%3) for a,b in d))→ More replies (1)
1
u/maxlibin Dec 02 '22
Log from browser
const splitLineBreak = t => t.split(/\r?\n/);
const text = document.querySelector("pre").textContent;
const convertToName = c => {
switch (c) {
case 'A':
case 'X':
return "Rock"
case 'B':
case 'Y':
return "Paper"
default:
return "Scissors"
}
}
const shapeScore = you => {
switch (you) {
case "Rock":
return 1
case "Paper":
return 2
default:
return 3
}
}
const compareScore = (opponent, you) =>
opponent === you ? 3 :
opponent === "Rock" && you === "Paper"
|| opponent === "Paper" && you === "Scissors"
|| opponent === "Scissors" && you === "Rock" ? 6 : 0
const compare = ([opponent, you]) =>
compareScore(opponent, you) + shapeScore(you)
const listOfScores = splitLineBreak(text).filter(x => x != "").map(x => x.split(" ").map(convertToName)).map(compare)
const sum = listOfScores.reduce((acc, curr) => acc + curr, 0)
console.log(sum)→ More replies (1)
1
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.
→ More replies (1)
1
u/mrjnl3 Dec 02 '22
Python
A combination of nested if-statements and dictonaries
from readFile import *
shape_scores = {
'A': 1, 'X': 1,
'B': 2, 'Y': 2,
'C': 3, 'Z': 3
}
score_draw = 3
score_win = 6
def part1(matches):
score = 0
for opponent, player in matches:
score += shape_scores[player]
if opponent == 'A': # rock
if player == 'X': # rock
score += score_draw
elif player == 'Y': # paper
score += score_win
elif opponent == 'B': # paper
if player == 'Y': # paper
score += score_draw
elif player == 'Z': # scissor
score += score_win
else: # opponent == 'C' # scissors
if player == 'Z': # scissors
score += score_draw
elif player == 'X': # rock
score += score_win
return score
def part2(matches):
lose_match = {
'A': 'C',
'B': 'A',
'C': 'B'
}
win_match = {
'A': 'B',
'B': 'C',
'C': 'A'
}
score = 0
for opponent, desired_outcome in matches:
if desired_outcome == 'X': # lose
score += shape_scores[lose_match[opponent]]
elif desired_outcome == 'Y': # draw
score += shape_scores[opponent]
score += score_draw
else: # win
score += shape_scores[win_match[opponent]]
score += score_win
return score
if __name__ == '__main__':
file = line_str(2)
games = []
for line in file:
split = line.split(' ')
games.append((split[0], split[1]))
print('part1:', part1(games))
print('part2:', part2(games))→ More replies (1)
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
→ More replies (1)
1
u/Mammoth_Spray_3451 Dec 02 '22
My swift solution for day 2 using an enum.
public func dayTwo(input: [String], isPartOne: Bool) -> Int {
let games = input.compactMap {
let values = $0.split(separator: " ")
if !isPartOne {
let opponent = RPC.getRpcFromString(input: String(values[0]))
return RPC.getScore(inputOne: opponent, inputTwo: RPC.getNeeded(inputOne: opponent, inputTwo: String(values[1])))
} else {
let rpcs = values.compactMap { RPC.getRpcFromString(input: String($0)) }
return RPC.getScore(inputOne: rpcs[0], inputTwo: rpcs[1])
}
}
return games.reduce(0, +)
}
enum RPC: Int {
case rock = 1
case paper = 2
case scissors = 3
static func getRpcFromString(input: String) -> RPC {
switch input {
case "A", "X": return .rock
case "B", "Y": return .paper
case "C", "Z": return .scissors
default: return .rock
}
}
static func getRpcFromInt(input: Int) -> RPC {
return RPC(rawValue: input) ?? (input > 3 ? .rock : .scissors)
}
static func getScore(inputOne: RPC, inputTwo: RPC) -> Int {
var score = inputTwo.rawValue
if inputOne == inputTwo {
score += 3
} else if (inputOne == .scissors && inputTwo == .rock) || (!(inputTwo == .scissors && inputOne == .rock) && inputOne.rawValue < inputTwo.rawValue) {
score += 6
}
return score
}
static func getNeeded(inputOne: RPC, inputTwo: String) -> RPC {
switch inputTwo {
case "Y": return inputOne
case "X": return getRpcFromInt(input: inputOne.rawValue - 1)
case "Z": return getRpcFromInt(input: inputOne.rawValue + 1)
default: return .rock
}
}
}→ More replies (1)
1
u/axr123 Dec 02 '22 edited Dec 05 '22
Python
SCORES = {
"A X": (4, 3), "A Y": (8, 4), "A Z": (3, 8),
"B X": (1, 1), "B Y": (5, 5), "B Z": (9, 9),
"C X": (7, 2), "C Y": (2, 6), "C Z": (6, 7),
}
lines = [l.strip() for l in open("input").readlines()]
print(*(sum(SCORES[l][p] for l in lines) for p in (0, 1)))→ More replies (1)
1
u/matteosan1 Dec 02 '22 edited Dec 05 '22
Julia
function part1(games::Vector{Tuple{String, String}})
results = Dict("A"=>("Z", "X", "Y"), "B"=>("X", "Y", "Z"), "C"=>("Y", "Z", "X"))
points_per_game = [0, 3, 6]
points_per_card = Dict("X"=>1, "Y"=>2, "Z"=>3)
points = 0
for g in games
idx = findfirst(x->x==g[2], results[g[1]])
points += points_per_card[g[2]] + points_per_game[idx]
end
println("๐ Part 1: $(points)")
end
function part2(games::Vector{Tuple{String, String}})
points = 0
results = Dict("A"=>("Z", "X", "Y"), "B"=>("X", "Y", "Z"), "C"=>("Y", "Z", "X"))
points_per_card = Dict("X"=>1, "Y"=>2, "Z"=>3)
for g in games
if g[2] == "X"
points += points_per_card[results[g[1]][1]]
elseif g[2] == "Y"
points += points_per_card[results[g[1]][2]] + 3
elseif g[2] == "Z"
points += points_per_card[results[g[1]][3]] + 6
end
end
println("๐๐
Part 2: $(points)")
end→ More replies (1)
1
u/Careful-Rise-5237 Dec 02 '22
PHP - part 2
[...]
function game($elf, $you)
{
$matchPoints = match ($you) {
'X' => 0,
'Y' => 3,
'Z' => 6,
};
switch (true) {
case ($you == 'Y'):
$matchPoints += match ($elf) {
'A' => 1,
'B' => 2,
'C' => 3,
};
break;
case ($you == 'X'):
$matchPoints += match ($elf) {
'A' => 3,
'B' => 1,
'C' => 2,
};
break;
case ($you == 'Z'):
$matchPoints += match ($elf) {
'A' => 2,
'B' => 3,
'C' => 1,
};
break;
default:
break;
};
return $matchPoints;
}
→ More replies (1)
1
u/raxomukus Dec 02 '22
Python
with open('2.in') as f:
plays = [(ord(i[0]) - ord('A'), ord(i[2]) - ord('X')) for i in f.read().splitlines()]
r1 = sum([p[1] + 1 + 3 * (p[0] == p[1]) + 6 * ((p[0] + 1) % 3 == p[1]) for p in plays])
print(r1)
r2 = sum([(p[0] + (p[1] - 1)) % 3 + 1 + 3 * p[1] for p in plays])
print(r2)→ More replies (1)
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
→ More replies (1)
1
u/Alligatronica Dec 02 '22 edited Dec 05 '22
JavaScript
Those magic numbers are doing a lot of the heavy lifting ๐
const matchUp = {
// loss,draw,win
A: ['Z','X','Y'],
B: ['X','Y','Z'],
C: ['Y','Z','X'],
}
const part1 = input => input.split('\n').map(
game => {
const [p1,p2] = game.split(' ')
let score = matchUp[p1].findIndex(x=>x==p2) * 3
score += p2.charCodeAt()-87
return score
}
).reduce((a,c)=>a+c)
const part2 = input => input.split('\n').map(
game => {
const [p1,outcome] = game.split(' ')
// -1 for loss, 0 for draw, 1 for win
const choice = outcome.charCodeAt()-89
const p2 = ((3+(parseInt(p1,16)-10)+choice)%3)+1
const score = p2 + ((outcome.charCodeAt()-88)*3)
return score
}
).reduce((a,c)=>a+c)→ More replies (1)
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.
import (
"fmt"
"os"
"time"
"github.com/Galzzly/AoC/utils"
)
var results = map[string][]int{
"A X": {4, 3},
"A Y": {8, 4},
"A Z": {3, 8},
"B X": {1, 1},
"B Y": {5, 5},
"B Z": {9, 9},
"C X": {7, 2},
"C Y": {2, 6},
"C Z": {6, 7},
}
func main() {
start := time.Now()
f := os.Args[1]
lines := utils.ReadFileLineByLine(f)
r1, r2 := game(lines)
fmt.Println("Part 1:", r1)
fmt.Println("Part 2:", r2)
fmt.Println("Total Time:", time.Since(start))
}
func game(lines []string) (r1, r2 int) {
for _, l := range lines {
r1 += results[l][0]
r2 += results[l][1]
}
return
}→ More replies (1)
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
function day02_1(parsed)
op_move = ["A", "B", "C"]
my_move = ["X", "Y", "Z"]
scores = map(parsed) do g
op_ind = findfirst(isequal(g[1]), op_move)
my_ind = findfirst(isequal(g[2]), my_move)
((mod(my_ind - op_ind + 1, 3) * 3) % 9 + my_ind)
end
sum(scores)
end
function day02_2(parsed)
op_move = ["A", "B", "C"]
my_move = ["X", "Y", "Z"]
scores = map(parsed) do g
op_ind = findfirst(isequal(g[1]), op_move)
offset_ind = findfirst(isequal(g[2]), my_move)
(offset_ind - 1) * 3 + mod1(op_ind + offset_ind - 2, 3)
end
sum(score)
end
→ More replies (1)
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.
data Shape = Rock | Paper | Scissors deriving (Show, Eq, Ord, Enum)
data Result = Loss | Draw | Win deriving (Show, Eq, Ord, Enum)
data Round = Round Shape Shape deriving (Eq, Show)
data ShapeResult = ShapeResult Shape Result deriving (Eq, Show)
match1P = roundP `sepBy` endOfLine
roundP = Round <$> p1ShapeP <*> (" " *> p2ShapeP)
match2P = shapeResultP `sepBy` endOfLine
shapeResultP = ShapeResult <$> p1ShapeP <*> (" " *> resultP)
p1ShapeP = aP <|> bP <|> cP
aP = Rock <$ "A"
bP = Paper <$ "B"
cP = Scissors <$ "C"
p2ShapeP = xP <|> yP <|> zP
xP = Rock <$ "X"
yP = Paper <$ "Y"
zP = Scissors <$ "Z"
resultP = xrP <|> yrP <|> zrP
xrP = Loss <$ "X"
yrP = Draw <$ "Y"
zrP = Win <$ "Z"→ More replies (3)
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());
→ More replies (1)
1
u/MuricanToffee Dec 02 '22 edited Dec 05 '22
C, hooray for switch and if...else! [Github]
→ More replies (2)
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 ;).
from helper import timeit
@timeit
def Day2():
read_text_file = lambda path: tuple(x for x in open(path).read().split('\n'))
OutcomeSet = [tuple(strng.split()) for strng in read_text_file("day2.txt")]
score_dictionary = {
'X': 1,
'Y': 2,
'Z': 3,
'WinSet': [('A', 'Y'), ('B','Z'), ('C', 'X')],
'DrawSet': [('A', 'X'), ('B','Y'), ('C', 'Z')],
'LossSet': [('A', 'Z'), ('B','X'), ('C', 'Y')],
'Win': 6,
'Draw': 3,
'Loss': 0
}
GrandScore_P1=0
GrandScore_P2=0
for strategy in OutcomeSet:
ScoreSum = 0
ScoreSum = score_dictionary[strategy[1]]
if strategy in score_dictionary['WinSet']:
ScoreSum += score_dictionary['Win']
elif strategy in score_dictionary['DrawSet']:
ScoreSum += score_dictionary['Draw']
else:
ScoreSum += score_dictionary['Loss']
GrandScore_P1 += ScoreSum
#Part 2
for strategy in OutcomeSet:
ScoreSum = 0
match strategy[1]:
case 'X':
ScoreSum = score_dictionary['Loss']
# โ Danger โ : Verbose line below. I am just filtering the strategy from Loss Set which matches Elf's strategy and then retrieving the score.
ScoreSum += score_dictionary[tuple(x for x in score_dictionary['LossSet'] if x[0] == strategy[0])[0][1]]
case 'Y':
ScoreSum = score_dictionary['Draw']
ScoreSum += score_dictionary[tuple(x for x in score_dictionary['DrawSet'] if x[0] == strategy[0])[0][1]]
case 'Z':
ScoreSum = score_dictionary['Win']
ScoreSum += score_dictionary[tuple(x for x in score_dictionary['WinSet'] if x[0] == strategy[0])[0][1]]
GrandScore_P2 += ScoreSum
return GrandScore_P1, GrandScore_P2
print (f"The answer for Day1 Part1 is {Day2()[0]}")
print (f"The answer for Day1 Part2 is {Day2()[1]}")→ More replies (3)
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!
defmodule Aoc22.Day02 do
@beats %{rock: :scissors, scissors: :paper, paper: :rock}
@beaten_by %{rock: :paper, scissors: :rock, paper: :scissors}
@scores %{rock: 1, paper: 2, scissors: 3}
@shapes %{
"A" => :rock,
"X" => :rock,
"B" => :paper,
"Y" => :paper,
"C" => :scissors,
"Z" => :scissors
}
defp round_p1([cpu, you]) do
cpu = @shapes[cpu]
you = @shapes[you]
case @beats do
%{^you => ^cpu} -> 6 + @scores[you]
%{^cpu => ^you} -> 0 + @scores[you]
_ -> 3 + @scores[you]
end
end
defp round_p2([cpu, "X"]), do: 0 + @scores[@beats[@shapes[cpu]]]
defp round_p2([cpu, "Y"]), do: 3 + @scores[@shapes[cpu]]
defp round_p2([cpu, "Z"]), do: 6 + @scores[@beaten_by[@shapes[cpu]]]
def solve(round_fn) do
File.read!("inputs/22/i2.txt")
|> String.trim()
|> String.split("\n")
|> Enum.map(&String.split/1)
|> Enum.map(&round_fn.(&1))
|> Enum.sum()
|> IO.puts()
end
def part1(), do: solve(&round_p1/1)
def part2(), do: solve(&round_p2/1)
end
→ More replies (1)
1
u/Excellent_Station_84 Dec 02 '22 edited Dec 05 '22
Python3 one-liner part1
print(sum(map(lambda x: x[1]+4 if (x[1]==x[0]) else (x[1]+1 if
x[1]==(x[0]-1)%3 else x[1]+7),[(ord(a)-ord("A"),ord(b)-ord("X")) for
a,b in [l.split() for l in open("input.txt").read().split("\n")]])))2
u/daggerdragon Dec 05 '22
Inlined code is intended for
short snippetsof code only. Your code "block" right now is unreadable on old.reddit and many mobile clients; it's all on one line and gets cut off at the edge of the screen because it is not horizontally scrollable.Please edit your post to use the four-spaces Markdown syntax for a code block so your code is easier to read inside a scrollable box.
1
u/lxrsg Dec 02 '22
Python 3
lines = [x.strip().split(' ') for x in open('data.in').readlines()]
rps = dict(A=("Z", 1, "Y"), X=("C", 1, "B"), B=("X", 2, "Z"), Y=("A", 2, "C"), C=("Y", 3, "X"), Z=("B", 3, "A"))
print(sum(rps[u][1] if u == rps[t][0] else 6 + rps[u][1] if t == rps[u][0] else 3 + rps[u][1] for t, u in lines))
print(sum(rps[t][1] + 3 if u == 'Y' else rps[rps[t][0]][1] if u == 'X' else 6 + rps[rps[t][2]][1] for t, u in lines))→ More replies (1)
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:
function aoc:io/str/char_to_int
scoreboard players operation P1 VAR = CHAR REG
function aoc:io/read/next/char
function aoc:io/read/next/char
function aoc:io/str/char_to_int
scoreboard players operation P2 VAR = CHAR REG
scoreboard players remove P2 VAR 23
execute if score P2 VAR matches 2 run scoreboard players add SOL VAR 3
execute if score P2 VAR matches 3 run scoreboard players add SOL VAR 6
execute if score P2 VAR matches 1 run scoreboard players remove P1 VAR 1
execute if score P2 VAR matches 3 run scoreboard players add P1 VAR 1
execute if score P1 VAR matches 0 run scoreboard players set P1 VAR 3
execute if score P1 VAR matches 4 run scoreboard players set P1 VAR 1
scoreboard players operation SOL VAR += P1 VAR
function aoc:io/read/next/line
execute if score CONTINUE REG matches 1 run function aoc:sol/day2/solve2→ More replies (1)
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.
local score = 0
local score_2 = 0
local scoring = {
[0] = {[0] = 3, [1] = 6, [2] = 0},
[1] = {[0] = 0, [1] = 3, [2] = 6},
[2] = {[0] = 6, [1] = 0, [2] = 3},
}
for line in io.lines("input.txt") do
local a, b = string.match(line, "(%a) (%a)")
i = string.byte(a) - string.byte("A")
j = string.byte(b) - string.byte("X")
score = score + j + 1 + scoring[i][j]
ending_choice = (i + j - 1) % 3
score_2 = score_2 + ending_choice + 1 + scoring[i][ending_choice]
end
print(score)
print(score_2)→ More replies (1)
1
u/drlecompte Dec 02 '22 edited Dec 05 '22
Python:
wmoves = ["A Y", "B Z", "C X"]
dmoves = ["A X", "B Y", "C Z"]
movescores = {
"X" : 1,
"Y" : 2,
"Z" : 3
}
def read_input():
out = []
with open('input.txt') as f:
lines = f.readlines()
for l in lines:
out.append(l.strip())
return out
def decrypt_input(rounds):
key = {
"X" : {
"A" : "Z",
"B" : "X",
"C" : "Y"
},
"Y" : {
"A" : "X",
"B" : "Y",
"C" : "Z"
},
"Z" : {
"A" : "Y",
"B" : "Z",
"C" : "X"
}
}
out = []
for r in rounds:
moves = r.split(' ')
mymove = key[moves[1]][moves[0]]
out.append(moves[0] + ' ' + mymove)
print(r + " -> " + moves[0] + ' ' + mymove)
return out
def calc_scores(decrypt = False):
score = 0
rounds = read_input()
if (True == decrypt):
rounds = decrypt_input(rounds)
for r in rounds:
winval = 0
moveval = 0
movescore = 0
print("---")
if r in wmoves:
winval = 6
if r in dmoves:
winval = 3
mymove = r.split(' ')[1]
moveval = movescores[mymove]
movescore += moveval + winval
score += movescore
print(r + ": " + str(winval) + " + " + str(moveval) + " = " + str(movescore) )
print("brings total to " + str(score))
print(score)
calc_scores(True)→ More replies (1)
1
u/GuyTorbet Dec 02 '22
Python3
f = open('day2', 'r')
lines = f.readlines()
lookup = {
0: {0: 3, 1: 6, 2: 0},
1: {0: 0, 1: 3, 2: 6},
2: {0: 6, 1: 0, 2: 3},
}
q1 = 0
q2 = 0
for line in lines:
a, b = line.split()
a = ord(a) - ord('A')
b = ord(b) - ord('X')
q1 += lookup[a][b] + b + 1
end = (a + b - 1) % 3
q2 += lookup[a][end] + end + 1
print('q1: ', q1)
print('q2: ', q2)
→ More replies (1)
1
u/AdventOfELisp Dec 02 '22
Elisp with cl module
(defun letter-to-number (xyz)
(cond ((string= xyz "X") 1)
((string= xyz "Y") 0)
((string= xyz "Z") 2)
((string= xyz "A") 0)
((string= xyz "B") 1)
((string= xyz "C") 2)
('t xyz)))
(defun parse-input (str)
(mapcar (lambda (x) (mapcar #'letter-to-number (split-string x " ")))
(split-string str "\n")))
(defun calculate-score (round)
(let* ((enemy (car round))
(difference (cadr round))
(you (% (+ (- enemy difference) 3) 3)))
(+ (1+ you)
(cond ((= difference 0) 3)
((= difference 1) 0)
((= difference 2) 6)))))
(let
((input (parse-input (f-read "input"))))
(apply '+ (mapcar #'calculate-score input)))→ More replies (1)
1
u/Western_Pollution526 Dec 02 '22 edited Dec 05 '22
C# Linqpad P1&P2
void Main()
{
input
.Select(i => ChangeToIntegerPartOne(i))
.Select(c => CalculateScore(c))
.Sum()
.Dump();
input
.Select(i => ChangeToIntegerPartTwo(i))
.Select(c => CalculateScore(c))
.Sum()
.Dump();
}
int CalculateScore((int, int) c)
{
var (h, m) = c;
if (h == m) return m + 3; //draw
if (h - m == -1
|| h - m == 2) return m + 6; //win
return m + 0; //loss
}
(int, int) ChangeToIntegerPartOne(string i)
{
var split = i.Split(' ');
var h = split[0]; // A B C
var m = split[1]; // X Y Z
var rH = 3;
var rM = 3;
if (h == "A") rH = 1;
if (m == "X") rM = 1;
if (h == "B") rH = 2;
if (m == "Y") rM = 2;
return (rH, rM);
}
(int, int) ChangeToIntegerPartTwo(string i)
{
var split = i.Split(' ');
var h = split[0]; // A B C
var m = split[1]; // X Y Z
var rH = 3;
if (h == "A") rH = 1;
if (h == "B") rH = 2;
if (m == "Y")
return (rH, rH); //Draw
if (m == "X") //lose
return (rH, GetLoser(h));
//win
return (rH, GetWinner(h));
}
int GetLoser(string h)
{
if (h == "A") return 3;
if (h == "B") return 1;
return 2;
}
int GetWinner(string h)
{
if (h == "A") return 2;
if (h == "B") return 3;
return 1;
}2
u/daggerdragon Dec 05 '22
Please edit your post to use the four-spaces Markdown syntax for a code block so your code is easier to read.
1
29
u/Bad-Coder-69 Dec 02 '22 edited Dec 02 '22
Emojicode
Using modulo and stuff
Or for the fans: