r/adventofcode • • Dec 02 '22

SOLUTION MEGATHREAD -🎄- 2022 Day 2 Solutions -🎄-

NEW AND NOTEWORTHY


--- Day 2: Rock Paper Scissors ---


Post your code solution in this megathread.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:06:16, megathread unlocked!

103 Upvotes

1.5k comments sorted by

View all comments

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) + 3

second + 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

1

u/daggerdragon Dec 05 '22 edited 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.

Edit: my bad, I overlooked it! Thank you for adding it up front, though <3

1

u/jderp7 Dec 05 '22

Oh sorry I had put it a bit far into the first sentence. Updated to start with it

1

u/daggerdragon Dec 05 '22

I overlooked it originally, my bad! My eyes start to glaze over after moderating 1,000+ submissions per day, lol... Thank you for putting it up front, though; that makes things easier for me to scan quickly.

1

u/jderp7 Dec 05 '22

No worries, makes sense to just include it at the top! Keep up the good work!!!