r/adventofcode • u/Afkadrian • Dec 07 '23
Spoilers [2023 Day 7] An interesting algorithm
I found out that if we find the count of the card that appears the most times and subtract the amount of different cards, the result is unique for each type of hand.
In other words... max_count - different_cards is a discriminant.
For a Rust implementation, check the from_cards function in my repo.
Has anyone else found this pattern?
48
Upvotes
View all comments
Show parent comment
5
u/somebodddy Dec 07 '23
You could always pad it with zeroes!
Even better - you only ever need the two highest counts - all the others will be either 1 or 0, and that choice between 1 and 0 is determine by the first two numbers anyway. So you can throw away the rest, and remain with
[5, 0] > [4, 1] > [3, 2] > [3, 1] > [2, 2] > [1, 1] > [1, 1].And if your language does not support comparison between same-sized arrays they way you need it to (or if it does and you want to be extra efficient) - there are only two numbers, and 5 is the highest value, so you can just map
[a, b] -> 8 * a + band store it in a single byte. As long as it's unsigned. Or utilize the fact thatb's highest possible value is 2 and use4 * a + bso it'd work even if the byte is signed.I'm a genius. I'm going to try my solution now and see if it improves performance.