r/adventofcode • u/daggerdragon • Dec 07 '23
SOLUTION MEGATHREAD -❄️- 2023 Day 7 Solutions -❄️-
THE USUAL REMINDERS
- All of our rules, FAQs, resources, etc. are in our community wiki.
Outstanding moderator challenges:
Community fun event 2023: ALLEZ CUISINE!
- Submissions megathread is now unlocked!
- 15 DAYS remaining until the submissions deadline on December 22 at 23:59 EST!
AoC Community Fun 2023: ALLEZ CUISINE!
Today's secret ingredient is… *whips off cloth covering and gestures grandly*
Poetry
For many people, the craftschefship of food is akin to poetry for our senses. For today's challenge, engage our eyes with a heavenly masterpiece of art, our noses with alluring aromas, our ears with the most satisfying of crunches, and our taste buds with exquisite flavors!
- Make your code rhyme
- Write your comments in limerick form
Craft a poem about today's puzzle
Upping the Antechallenge: iambic pentameter
- We're looking directly at you, Shakespeare bards and Rockstars
ALLEZ CUISINE!
Request from the mods: When you include a dish entry alongside your solution, please label it with [Allez Cuisine!] so we can find it easily!
--- Day 7: Camel Cards ---
Post your code solution in this megathread.
- Read the full posting rules in our community wiki before you post!
- State which language(s) your solution uses with
[LANGUAGE: xyz] - Format code blocks using the four-spaces Markdown syntax!
- Quick link to Topaz's
pasteif you need it for longer code blocks
8
u/CCC_037 Dec 07 '23
[Language: Rockstar]
[Allez cuisine!]
Have you heard the whispers in the cracks at the edge of reality?
Have you looked into that which lies beyond?
(There were a lot of finicky little details to get right with this one, but the basic algorithm was straightforward to arrange)
4
u/DFreiberg Dec 08 '23 edited Dec 08 '23
[LANGUAGE: Mathematica] Mathematica, 742 / 1673
Not too bad of a problem; part 2 was easier than I expected, even if it initially took multiple seconds for my program to run (I tested every possible substitution of every joker in each hand, having not convinced myself that the solution was sustainable.
Part 1:
Part 2:
And okay, I suppose I can't resist writing one poem...
[Allez Cuisine!]: Poker? I Hardly Know Her!
In a desert, you're playing some poker
With a camel, an elf, and a joker,
And if you're so inclined,
With a five of a kind,
You can conquer (or maybe get broker).
6
u/Symbroson Dec 07 '23 edited Dec 07 '23
[Language: Ruby]
Update to my previous solution, applying shannons entropy as suggested by u/sinsworth here
The strength value is now calculated by this function, which sums the squares of the counts of every character. Previously my sorting function appended the strength as digit 0-6. The squares are larger so I just use
chrto convert the number to a single characterApplying this to my golfed code I can get sub 400 bytes, 395 to be exact
What bugs me is that I can't quite fulfill the
5x80punch card limitation. The best I could get is reordering and format it to5x81.3
u/Regex22 Dec 07 '23
[LANGUAGE: Rust] I wrote custom types for cards and hand types just for readability, left this out here. Here is the relevant bit:
3
u/crazy0750 Dec 07 '23 edited Dec 08 '23
[LANGUAGE: Rust]
Easy task, but quite laborious do implement.
I took a direct approach, modelling the problem using two Enums (Card and HandType) and one struct (Hand). Most of the heavy lifting is done by implementing the traits
FromStrandOrd.For part 2, at first glance, I thought in creating wrappers and implementing the
Ordtrait again. However, the solution turned to be much simpler: adding Joker to theCardsenum, converting all J cards into Joker, and then mapping the hand types with pattern matching.For both parts, the solution is given by sorting a
VecofHandss and iterating over to calculate the winnings.Link to Solution
3
u/xavdid Dec 08 '23 edited Dec 10 '23
[LANGUAGE: Python]
Step-by-step explanation | full code
This was a fun one! The key piece for me was representing a hand as a sortable
tuple. I scored hands based on the values in aCounterand used pattern matching to find the correct shape for the hand.For part 2, I adjusted the card counts based on the jokers joining the rightmost (e.g. most frequently occuring) card, which was the most advantageous move when scoring.
Very pleased with the cleanliness on this one!
2
u/kevinwangg Dec 07 '23
[LANGUAGE: python]
I'm guessing I wasn't the only one to read too fast and waste time on part 1 sorting the hands from strongest to weakest card.
Countercame in handy today!2
u/darkfm Dec 07 '23 edited Dec 07 '23
[LANGUAGE: python] 515/352
Paste
I took way too long for part 1 due to a very dumb bug in my code (
hand.count(a) or hand.count(b) == 4instead ofhand.count(a) == 4 or hand.count(b) == 4). Luckily I'd already seen a challenge last (?) year using cmp_to_key so I knew where to go lol2
u/rayhond2000 Dec 07 '23 edited Dec 07 '23
[LANGUAGE: Python 3] 655/264
Created a list of lists for python to sort. The first element in the inner list is the hand strength, then 2nd through 6th elements are the card strengths.
topaz link
2
u/InternetArgument-er Dec 07 '23 edited Dec 08 '23
[LANGUAGE: C++]
I was too stupid so I just tested all possible values for the jacks in part 2. Still runs under 2 seconds.
https://github.com/ANormalProgrammer/AdventOfCode/blob/main/2023/2023_day7.cpp
2
u/NailOk2475 Dec 07 '23 edited Dec 07 '23
[Language: QuickBasic]
Feast your eyes on this spaghetti monster, nerds.
2
u/aimada Dec 07 '23 edited Dec 07 '23
[LANGUAGE: Python]
Reading through the challenge descriptio there were 7 types of hand listed in the description. My first order of business was to write a function that would determine the type of a hand. Each type was identified by a sorted tuple of the card value counts.
Ordering the tuples by increasing strength of the hand gave a means of determining the relative strength of a pair of hands. The strength of the hand type was used as a dictionary key and hands of the same strength were stored together in a list. I reasoned that sorting the seven smaller lists would be more efficient than sorting one large list.
Comparing two hands was relatively simple, the value of each card was determined by finding the index of its position in the string, "23456789TJQKA". The first required change for part two was to move "J" to the front of the string, "J23456789TQKA".
Determining the best joker hand was the second required change for part two. It was a straight forward process, the best card was determined by sorting the cards in the hand using their count value.
The final step was to iterate through the dictionary keys in order of strength, low to high, and multiplying each hand's bid by the increasing rank value.
Because there were only minor changes to the functionality between the two parts, a single function served for both and a Boolean parameter value determined which was executed.
A very straight forward challenge with no surprises.
2
u/mvorber Dec 07 '23 edited Dec 07 '23
[LANGUAGE: F#]
https://github.com/vorber/AOC2023/blob/main/src/day7/Program.fs
Day 7 of using F#
2
u/MuffinHydra Dec 07 '23 edited Dec 07 '23
[LANGUAGE: GO]
got one nasty edge case with 5 jokers which was then just an if statement at the right place. Other than that smooth saling
https://github.com/muffinhydra/Advent-of-Code-2023-GO/tree/main/day7
2
u/MizKyosia Dec 07 '23 edited Dec 16 '23
[LANGUAGE: JavaScript]
Pretty easy challenge today, here's my code
I gave each letter a numerical value for the sorting, and the one of J changes between 11 for part 1 and 1 for part 2.Used a
Mapto keep track of the number of cards in a hand, then added the number of jokers to whatever card was present the most in the hand.Used the good old
Array.sort()method to order a list of hands and their bids, then just a simple sum loop2
u/TheLayeredMind Dec 07 '23 edited Dec 09 '23
[LANGUAGE: Elm]My solution in Elm, with an additional Rank visualizer runs surprisingly fast.I found a pretty cool solution (I think) through pattern matching which enabled to adapt to the "Jack wildcard" rule very easily, allthough a bit verbose.
Link to the Solution
Link to my Blog post (Day 7)
2
u/pclinger Dec 08 '23 edited Dec 08 '23
[LANGUAGE: Perl]
Golf
Part 1
Part 2
2
u/East_Intention_7542 Dec 08 '23 edited Dec 08 '23
[LANGUAGE: Python]
Perhaps the most straight forward solution to day 7 part 2?
Each hand is scored by determining first with all jokers removed, and then enhancing that hand adding the jokers back one at a time. For example, if you have 1 pair (without jokers), adding back a joker will give three of a kind. Adding another, will give 4 of a kind.
This score is used to prefix the hand with one of TUVWXYZ, before sorting.
26
u/4HbQ Dec 07 '23 edited Dec 07 '23
[LANGUAGE: Python] Code (10 lines)
For part 2, I simply replace J with all possible values and take the best one.
Update: inspired by /u/sinsworth's brilliant idea to use [entropy](https://en.wikipedia.org/wiki/Entropy_(information_theory)) to rank the hands, I came up with a simpler measure:
For example:
Today's Python trick: using
translate()andmaketrans()to replace the face cards values with A, ..., E:16
u/gemdude46 Dec 07 '23 edited Dec 07 '23
[LANGUAGE: Python]
Both parts
<Replaced with paste>
14
u/pred Dec 07 '23
[LANGUAGE: Python] GitHub
The only real trick here is to realize that the most efficient use of a joker is as the most common non-joker card (if any). Together with a bit of Python matchic for condensing all the possible cases.
14
u/Zweedeend Dec 07 '23 edited Dec 09 '23
[LANGUAGE: Python]
[Allez Cuisine]
Part 1:
12
u/jonathan_paulson Dec 07 '23 edited Dec 07 '23
[LANGUAGE: Python 3] 4/61. Solution. Video.
Part 1 went great; I've actually coded up "sort poker hands by strength" before so that was helpful. Part 2 was a buggy mess :( There must be an elegant way of doing it?
12
u/Goues Dec 07 '23
[LANGUAGE: JavaScript] 85/189
I missed JJJJJ hand for second part and that slowed me down below global leaderboard :(
12
u/sinsworth Dec 07 '23
[LANGUAGE: Python]
'Twas joyful to realise that one could order the cards by entropy instead of tediously typing out the ruleset, but spent a little while on figuring out what went wrong when I'd implemented the normal poker rules where the index of the high card does not matter... A lesson in reading problems thoroughly.
code
7
u/Polaric_Spiral Dec 07 '23 edited Dec 07 '23
[LANGUAGE: Typescript]
Advent of Node, Day 7
For each hand, cards are counted into buckets, then the hand is scored by the formula
3 * s1 + s2(see edit), wheres1ands2are the sizes of the largest and second largest group. The same hand type will always give the same score, and the 3x factor ensures that a full house or two pair doesn't overlap with the next highest score. Then it's a matter of comparing cards sequentially and callingsort()with the resulting function.The trick with the jokers is that the best move is always to include them in
s1.Edit: actually,
2 * s1 + s2works just as well for the scoring formula. I forgot that the next score up from the full house and two pair still both have a second group size of 1, so the scores are still distinct.7
u/flwyd Dec 07 '23
[Language: Julia] (on GitHub)
[ALLEZ CUISINE!]
There was a coder from Kent
Who puzzled each night of advent
They played modified poker
Swapped cards with a joker
And that's how December 7th went
I originally had
struct Card value::Char endand switched to defining a new primitive type and it didn't seem to affect CPU or RAM usage at all, so Julia does an impressive job of optimizing simple structs. (The reason it's a custom type at all is to overrideislessby indexing intoORDERS.) Benchmarks suggest that changing ORDERS from a linear scan of a String to a Dict lookup maybe cuts two milliseconds off a 27 millisecond time. Rob Pike has observed that O(n) can beat O(1) algorithms when n is small.7
u/Smylers Dec 07 '23 edited Dec 07 '23
[LANGUAGE: Vim keystrokes]
Part 1 keystrokes, starts with 7 lines that classify hands, prepending a number from
7to1based on their strength, such as this which prepends5on each line with a full house:Then it sorts and add up the total winnings with:
For more explanation, see this help post, where I almost had it working. A massive thanks to u/Cue_23 for trying out my keystrokes, understanding what I was trying to do, and spotting where I'd gone wrong.
Unfortunately debugging that took up the time I was going to spend on part 2 ‒but after a couple of days off, it's nice to be back with a Vim solution at all.Update: part 2 keystrokes This begins (and ends) exactly the same as part 1, initially classifying the hands as though
Jwere a normal card. Then it ‘upgrades’ hand strengths based on the jokers:Js take on the other value, all 5 will be identical.The substitutions are made in that order to prevent anything from being wrongly double-upgraded.
Then it's just a case of making a joker sort correctly by changing its label:
:%s/J/0/g, then the rest exactly as for part 1 to get the total winnings.7
u/[deleted] Dec 07 '23 edited Dec 07 '23
[LANGUAGE: Google Sheets]
Assuming the input is in A:A
One formula for both parts
6
u/azzal07 Dec 07 '23
[LANGUAGE: Awk] Took a few tries to get the jokers working correctly.
I encode the hands as
TTTTHHHHH, whereTs encode the type andHs are the hand. I made the type encoding lexicographically sortable and replace couple characters from the hand to make it also lexicographical (tr AKT SRB, which is bit more verbose in awk).The type is encoded as four digits, which count the number of 5, 4, 3 and 2 of a kind respectively. For example five of a kind is
1000, two pairs is0002and full house is0011. I don't count the jokers yet.Then for each joker, I replace the first
01with a10to get the highest possible hand. I've first added a1at the end to account for two edge cases: high card + joker and 5 jokers. Lastly I need to check the case of two pairs + joker, which becomes a full house.5
u/EViLeleven Dec 07 '23 edited Dec 07 '23
[LANGUAGE: Python]
Instantly reminded me of Problem 54 of Project Euler, which I... ehm.. skipped at the time.
Wasn't as bad as I first feared and while my code isn't smart it does what it needs to^^
Paste
Don't ask me why I list()-ed the strings before I set()-ed them. I don't know.
5
u/EffectivePriority986 Dec 07 '23 edited Dec 07 '23
[LANGUAGE: Perl5] 76/123 Solution Video
The neat trick is to translate TJKQA to different letters that do sort lexicographically. Counting the different cards is accomplished by filling a hash.
Jokers are implemented by just trying all possible cards. Since we have no straights the jokers can always be the same.
I figured out after coding that the poker ranks are exactly a lex order on the sorted histogram of cards, giving this code:
5
u/phord Dec 07 '23
[LANGUAGE: Python]
I realized I could easily rank the hands by sorting the counts of each card found in the hand. Then I used an exhaustive replacement of each J and found the best score among the alternatives. Finally I appended the "values" for each card to this list only for tie-breakers.
5
u/brtastic Dec 07 '23
[Language: Perl] 6602/4285
Github
Happy with code quality. Completes in about 8ms.
5
u/j_ault Dec 07 '23 edited Dec 07 '23
[Language: Swift]
Part 1 Code
Took me a while to figure out how to identify poker hands. Only made one mistake in the code comparing hands, got the right answer after fixing that. Gonna have to make significant changes to get part 2, so I'm punting on that until morning.
Edit: Good thing I slept on it, part 2 turned out to be much simpler once I realized I don't actually need to know which card the joker is turning into. Add the joker to the Card enum, change how input character "J" is interpreted, and after determining the hand type look to see if there are any jokers and if so run this bit of code to upgrade the hand:
5
u/WilkoTom Dec 07 '23 edited Dec 07 '23
[Language: Rust][Allez Cuisine!]
Camel Cards: A sonnet
An airship brought me to this dusty land
To be met by an elf all clothed in white
She says I must give her a helping hand;
I’m yet to recover from my short flight!
Jump on a camel, we make quite a sight -
To pass the time, a quick game played with cards?
At least until the failing of the light
To play the game, it seems, is not so hard.
(Unlike this emulation of the bard!)
The cards,it seems, played in this gambling game
Need players’ keen eyes to remain on guard.
Else Jack, or Joker, wins; I’ve lost again!
I hope our search finds the broken machine
Before my wallet has been emptied clean!
5
u/davidkn Dec 07 '23
[LANGUAGE: Rust]
I ended up handling the jokers by adding their count to the most frequent non-joker item.
Solution on GitHub
5
u/sojumaster Dec 07 '23 edited Dec 07 '23
[LANGUAGE: PowerShell][Allez Cuisine!]
Wrote a limerick where the lines of the poem line up with particular lines of code. Here is the limerick:
As with the code. Did some simple text substitutions - Replaced A,K,Q,J,T with E,D,C,B,A; Making the hands sortable. The prepended the hand with the strength of the hand - 5 of a Kind (7) down to High Card (1). Part 2: Changed J to 1; counted the Jacks seperately and added them to most frequent card in the hand.
5
u/Fyvaproldje Dec 07 '23
[LANGUAGE: Raku] [Allez Cuisine!]
https://github.com/DarthGandalf/advent-of-code/blob/master/2023/Day07.rakumod
A bunch of regexes after sorting the hand.
5
u/ManaTee1103 Dec 07 '23 edited Dec 07 '23
[LANGUAGE: Python] I just made tuples of the card counts and translated values and let python order them for me… I’m a bit frustrated about how ugly it is to get and reset the joker count, any tips are welcome…
5
u/dzecniv Dec 07 '23
[LANGUAGE: Common Lisp]
https://github.com/vindarel/bacalisp/blob/master/advent/advent2023-12-07.lisp
not the shortest, but I decompose the steps as I try things incrementally, and I like to have kinda inline tests. I would use
frequenciesfrom Serapeum in retrospect. I used hash-tables, which by default don't print readably (showing their inner content and being able to be "read" back in), but they do with serapeum'sdict. This helper is included in the meta-librarycielthat I use.4
u/abnew123 Dec 07 '23
[LANGUAGE: Java]
Solution: https://github.com/abnew123/aoc2023/blob/main/src/solutions/Day07.java
Not too bad, although I had to fight against my poker instincts for how to classify hands as better than each other. I'm curious how people represented strength of hand, I went with 2x frequency of most common card + 1 if frequency of second most common was 2.
4
u/bucketz76 Dec 07 '23
[Language: Python]
All about the comparison function for sorting! Python's Counter came in handy for determining the types. For part 2, just change the jokers to the card that occurs the most (or "A" if they're all jokers).
paste
4
u/Hungry_Mix_4263 Dec 07 '23
[LANGUAGE: Haskell]
https://github.com/alexjercan/aoc-2023/blob/master/src/Day07.hs
Only kept here the part where I ranked the cards (code is kinda long). But this method of doing it was really fun
4
u/NohusB Dec 07 '23
[LANGUAGE: Kotlin]
Part 1
Part 2
4
u/quodponb Dec 07 '23 edited Dec 08 '23
[LANGUAGE: Python3]
Python3
Full solution
The way I went about it was to still have the card-hand be represented as a string, only replacing
TJQKAwithABCDE, and prefixing the string with one of012345, depending on which type of hand it was, in increasing order of strength.This let me sort the
(hand, bid)tuples using the built insorted, which was very convenient!I reasoned about the hand type by looking at its shape, or how large the different groups were within the hand:
This let me define a function
get_hand_type,and for the joker-case could simply do
Edit: Here is a simplified version
I realised that, since sorting tuples works no problem, the tuple describing the hand's card frequencies can be used directly in the sorting, and doesn't need to be converted into a prefix for a string representation of the hand. I was also inspired by the way /u/4HbQ implemented Jokers, as well as their use of
str.maketrans. The simplification therefore now distinguish between the cardJACK="B",JOKER="1", and I use a cardEMPTY="0"for the corner case when a hand consists of only jokers.4
u/bucketz76 Dec 07 '23
[Language: Python]
Refactored my solution, turns out pattern matching and Python's nested list sorting are very useful!
paste
4
u/POGtastic Dec 07 '23
[LANGUAGE: F#]
There's a way to do this efficiently, but I realized that it's way easier to brute-force all of the possible cards that a Joker can be.
Subtle bug with how I was treating the cards, grumble grumble grumble. I was performing the substitution, meaning that a KTJJT actually became a KTTTT. That's not correct! It's quads, but you have to substitute back in the Joker card after you're done.
As always, write the types! Types types types, types, types types types types. Types. In Haskell terms, F#'s record types automatically derive
Ord! That's incredibly useful here!https://github.com/mbottini/AOC2023/blob/master/Day7/Program.fs
4
u/delventhalz Dec 07 '23
[LANGUAGE: JavaScript]
4871/3721
Came up with the idea of converting every hand to a unique score by separating the different aspects into different orders of magnitude. Your last card gets multiplied by 1, your fourth by 10, etc. Your hand type is an order of magnitude more than any of the individual cards. Then you can just sort by the number value all at once.
I was feeling very clever until it took me 20 minutes of debugging to realize that there are 13 different card and their scores do not fit into one order of magnitude.
4
u/YenyaKas Dec 07 '23
[LANGUAGE: Perl]
Part 1 Part 2
Not bad. Implemented card rank as histogram-of-histogram and then
y/AKQJT98765432/ABCDEFGHIJKLM/to be able to sort the$rank.$cardlexicographically.In part 2 tried
s/J/$card/gfor every card in a given set.As always, All my AoC solutions in Perl
4
u/Cue_23 Dec 07 '23
[LANGUAGE: C++] [Allez Cuisine!]
There's nothing fancy in this code,
Just a little sorting note,
The spaceship <=> can sort every kind
Of Hands in classes well defined.
I'll keep 2 programs now around
For every part one, and I found
The changes to be very low.
Thus merging them I will not bow.
Try rhyming in a foreign language
or see my diff for welcome change!
4
u/khoriuma Dec 07 '23
[Language: Zote] 1323/1548
My first solution to part 2 was really messy due to being scared of the jokers. In hindsight I see that you can just add them to the highest frequency... Oh well, my code ignores that will a relatively simple if statement: paste
4
u/Kangei Dec 07 '23 edited Dec 07 '23
[LANGUAGE: Python]
Solution
Very nice that the hand type just falls into the correct order for sorting when determined this way.
4
u/thekwoka Dec 07 '23
[Language: TypeScript]
This is in d.ts, Type Level TypeScript
https://github.com/ekwoka/advent-of-code/blob/main/2023/07/index.d.ts
This only does the example, and with reduced bids, since the recursion level to handle multiplication of higher numbers is EXTREME.
It's very messy, but it works :)
Here's just the Type that handles taking a Hand and getting it's Type
4
u/vino250 Dec 07 '23 edited Dec 07 '23
A short python solution
4
u/newtondev Dec 07 '23
[Language: Rust]
https://github.com/newtondev/advent-of-code/blob/main/2023/src/bin/07.rs
4
u/veydar_ Dec 07 '23
[LANGUAGE: lua]
Lua
81 lines of code according to
tokeiwhen formatted withstylua.My personal Vietnam for this year. I knew this would be straight forward as long as you implement the rules correctly. I then spent 2h trying to figure out why my program wouldn't give me the correct answer. Well... take a look at how I defined the order of things:
Lesson learned! Don't do this manually, but generate the positions from a list, so this error becomes impossible.
4
u/lbm364dl Dec 07 '23
[LANGUAGE: Python] Code (13 lines)
Just my weird Python with some use of Counter
4
u/chubbc Dec 07 '23 edited Dec 07 '23
[LANGUAGE: Julia]
Pretty happy with how concise this ended up. Not short, but not bad.
4
u/greycat70 Dec 07 '23
[LANGUAGE: Tcl]
Part 1, part 2.
My approach was to assign a score to each hand. Each card has a value less than 16, so it fits in a hex digit. So I decided to use a base 16 number for the score. The 5 lowest digits are the cards, in order. The high digit is based on the hand type ("two pair" etc.), with five of a kind being highest. This also means I can use bit operators to build up the score.
For part 1, just assign a score to each hand, sort the hands by score, and calculate the winnings.
For part 2, I decided the easiest approach would be to iterate over every possible card value for the Jokers, and find the best hand type out of all those. If there are 4 or 5 jokers then it's always 5 of a kind so there's no need to iterate. If there are 3 or fewer, then I iterate. I handled each "number of jokers" case separately, so I could set up the appropriate number of nested for loops.
4
u/Backwards_Reddit Dec 07 '23
[LANGUAGE: Rust]
Part 1
https://github.com/RansomTime/aoc2023/blob/main/day_7/src/main.rs
Implemented Ord, used sort()
Part 2
https://github.com/RansomTime/aoc2023/blob/main/day_7_2/src/main.rs
New file due to needing to adjust the value of J. Otherwise nice easy part 2.
4
u/DrunkHacker Dec 07 '23 edited Dec 07 '23
[LANGUAGE: Python]
I wrote a poker bot a while ago and basically used the same strategy of creating a unique ordered "score" for every possible hand. After that, sorting and multiplying by bets is trivial.
4
u/dehan-jl Dec 07 '23
[Language: Rust]
Code (Github) - 109 sloc
Part 1 = 239.75µs; Part 2 = 258.25µs
Wow did I go on an adventure in optimisation today. Down from 80ms on a 10-core M2 Pro down to 260us for Part 2.
So just some type definitions:
Now where do those numbers come from?
Well, as a lot of people did, we can parse our hands as a hex number, and 0xEEEEE is just under 1 million. One little trick here is to do the string replacement on the whole input at once, instead of each hand individually.
Then we can get to my favourite part
We don't actually have to do any Joker replacements! We simply have to find how many jokers we had and add that to the card with the most occurrences. Just that one little change took me from 80ms to 4ms (without even caching the result).
4
u/horsecontainer Dec 07 '23 edited Dec 07 '23
[LANGUAGE: Python]
I got part one in five minutes then spent all day with answers very slightly off for part two. But okay, fine, the code is still fun.
4
u/sr66 Dec 07 '23
[LANGUAGE: Mathematica]
Part 1:
Part 2:
4
u/Salad-Extension Dec 07 '23 edited Dec 07 '23
[Language: C#]
Using some 'new' syntactic sugar from C#. Tried to strike a balance between readability and speed so people trying to learn coding, in C# and its new features in particular, could take something from the code.
Code
4
u/axsk Dec 07 '23 edited Dec 07 '23
[Language: Julia] (on GitHub)
[ALLEZ CUISINE!]
I liked how simple the card multiplicities became with Julias broadcasting.
Also `findfirst` beats manually constructing a card-value lookup :)
Taking care of JJJJJ correctly costed me ages (I was looking at my sorted hands, with JJJJJ at the top (lowest rank) and thought it actually is the weakest hand for 30 minutes)
4
u/Sbgodin Dec 07 '23
[LANGUAGE: Python3]
The goal is to build the key function for sorting. Once it's done, it's only a matter of summing the scores. The key function is made of two parts. The first one sets the hand type : Five of a kind: "50000" Four of a kind: "41000" Full house: "32000" Three of a kind: "31100" Two pair: "22100" One pair: "21110" High card: "11111" The number fits the need to sort the hand types!
For the hands of the same time, each card is turned into a two-position number. '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A'] 1 2 3 4 5 6 7 8 9 10 11 12 13 aka index+1 QQQ3Q 410001111110211 QQQ7Q 410001111110611
The "41000" means "Four of a kind". The "11" repeated three times correspond to 'Q'. So the hands of the same type are comparable. The higher the score, the higher the key number.
4
u/CelestialDestroyer Dec 07 '23
[Language: Chicken Scheme]
Phew... "Finished" day 7 in a literate programming style: https://gitea.lyrion.ch/zilti/Advent-of-Code-2023#headline-76
I am stumped, however - it works for the example given, but for the full input, I apparently get a too small result. I'll investigate tomorrow.
4
u/AJMansfield_ Dec 08 '23 edited Dec 11 '23
[LANGUAGE: Fortran]
https://github.com/AJMansfield/aoc/blob/master/2023-fortran/src/07/camel.f90
Not gonna lie, Fortran has a lot of features that make challenges like this more convenient than you would expect.
It does, though, have one glaring weakness, and that's the way it hates reading variable-width inputs. This tripped me up significantly here: When I'd originally scrolled through the input file to check how many digits the bid could be, I didn't spot the 1000 and assumed that an
I3input field would be enough. Silly me, this one mistake cost me hours.I also didn't read the question properly at first, and initially had it do slightly more work to sort the hands into the conventional "highest count first" poker order.
On the plus side, being stuck there for so long, did motivate me to compile about a bajillion different test cases to try to find the issue. And once I fixed the issue and solved part 1, my attempt at part 2 worked perfectly the first time.
4
u/chubbc Dec 08 '23
[LANGUAGE: Uiua]
This one was more fun than I thought it was going to be. A lot of black magic when it comes to massaging the arrays into the right sizes, but solution is surprisingly concise. Pad if you want to play with the code.
4
u/soylentgreenistasty Dec 08 '23
[LANGUAGE: PYTHON]
paste
Used cmp_to_key to sort the cardsets. Had an annoying bug for ages where I forgot to return the actual best hand when replacing jokers!
4
u/bofstein Dec 09 '23 edited Dec 11 '23
[LANGUAGE: Google Sheets]
This one was fun!
https://docs.google.com/spreadsheets/d/1_UpBEZes-L2Vtr146gDPUtaBHrTU8V2vQ2t3k4dZ_VI/edit?usp=sharing
For Part 2 I made a table of how each hand would change if there are X jokers; there were only 7 changes total so I initially did it with a bunch for IFs but then made it better by just actually searching the table I made. Then sort again but J is a 1 now.
1
u/messedupwindows123 Dec 07 '23 edited Dec 08 '23
[LANGUAGE: Haskell]
I made heavy use of
deriving (Ord), which gives me a lot of sorting stuff "for free". The "ScoreableHand" objects are sortable "for free", because tuples sort according to their contents, etc.https://pastebin.com/JTmf5fTY
1
u/AKSrandom Dec 07 '23
[LANGUAGE: Python3]
1
u/stribor14 Dec 07 '23 edited Dec 08 '23
[Language: C++] Range-v3
Once again good task to train C++ with ranges. Character replacement for sort. 'J' is either 'B' or '1' depending if we want it to be a joker or not. If-block for hand strength evaluation (same eval for both parts).
LINK TO THE CODE
edit: wanted to test fellow redditors approach for ranking without if-else, and I really like it
1
u/Knudson95 Dec 07 '23 edited Dec 08 '23
[Language: C#]
Only 2nd part cause I don't work the code to fit both. That took me way longer than it should have. I had the right solution for a long time but used the wrong variable in a comparison. Fun challenge.
paste
1
u/growing_trex Dec 07 '23
[Language: python]
today was fun but I was going for speed so my code is a hot mess. you can try to understand it if you want but I would not recommend it(I wrote it and I do not). if you want to use it put your data in the variable at the beginning called data and run. all hashed print statements were for some debugging
https://github.com/E-J-bl/advent-of-code/blob/main/day_7.py
1
u/flammschild Dec 07 '23 edited Dec 08 '23
[LANGUAGE: PowerShell]
The Sort-Object cmdlet in PowerShell was very useful today.
AoC Day 7
1
u/malobebote Dec 07 '23 edited Dec 07 '23
[Language: Typescript]
My code isn't cute nor clever but it's simple.
My part 2 solution introduces a
bestScorefunction that replaces all jokers with the most common card in hand. I originally brute-forced all combos but figured out later that this worked.Here's the full code:
1
u/fullmetalalch Dec 07 '23
[Language: Python] Gitlab
Today wasn't too bad! Just took some time to think through the hand evaluation logic. Going to peruse other solutions to see if there is a better way to handle jokers than hard-coded conditionals everywhere.
1
u/backdoorman9 Dec 07 '23 edited Dec 07 '23
[LANGUAGE: python]
OOP has really been growing on me this AoC.
I found
\StrEnum`` useful:Using a class with an attribute
card_rankingsallowed me to sort in a way that was new to me, and the__repr__method made debugging so much easier:Here's the class:
1
u/tclent Dec 07 '23 edited Dec 07 '23
[LANGUAGE: Rust]
Link
Benchmark times with criterion:
year_2023_day_07::parse_input time: [54.210 µs 54.531 µs 54.875 µs]
year_2023_day_07::part_one time: [1.5245 µs 1.5255 µs 1.5270 µs]
year_2023_day_07::part_two time: [2.9996 µs 3.1925 µs 3.4546 µs]
1
u/CarrotBusiness2380 Dec 07 '23
[Language: Powershell]
I used
Sort-Objectand an enum to do the heavy lifting. I also cheekily converted the hands into a different string to sort when the matched.For Part 2 I made the switch statement slightly more complex:
1
u/ForScale Dec 07 '23 edited Dec 07 '23
[LANGUAGE: JavaScript]
Part 1
1
u/chicagocode Dec 07 '23 edited Dec 07 '23
[LANGUAGE: kotlin]
I put all of the hands in a natural order by assigning them each an integer based off of the category and the strength of each card. Bit shifting to the rescue! I don't usually write a lot of bit shifting code in kotlin, so this was fun. Also got to use
groupingBywhich is always good.My code can be found on GitHub, I've written this up on my blog, and here are my 2023 Solutions so far.
1
u/Markavian Dec 07 '23
[LANGUAGE: JavaScript]
Had help from here: https://www.reddit.com/r/adventofcode/comments/18cr4xr/2023_day_7_better_example_input_not_a_spoiler/
My original (intended) solution for part two was correct... but I'd sorted the lowest common card to add jokers to instead of the the highest common cardand that was enough to get the wrong answer after fixing all the other bugs that I spotted myself.
Part 1 went pretty smoothly. I was disappointed that I couldn't think of / find any standard datastructures for counting occurances; but I was glad to implement my own version - because that meant I could make a second one for counting occurances with jokers... which seems like a really clean way to solve for the second star if I may say so myself... also descriptive classifications in my output.json was really helpful in debugging, so +1 for over-engineering.
https://github.com/johnbeech/advent-of-code-2023/blob/main/solutions/day7/solution.js
https://github.com/johnbeech/advent-of-code-2023/blob/main/solutions/day7/output-part1.json
https://github.com/johnbeech/advent-of-code-2023/blob/main/solutions/day7/output-part2.json
1
u/aleks31414 Dec 08 '23 edited Dec 08 '23
[LANGUAGE: rust]
1
u/alix_not_alex Dec 08 '23
[LANGUAGE: Python]
https://github.com/alixlm19/Advent-of-Code/blob/main/day_7.py
3
u/rogual Dec 07 '23 edited Dec 07 '23
[LANGUAGE: python]
401 / 337
My solution for part 2.
Might have been in with a chance had I not missed that rank 1 should be the worst hand. Sigh.
Edit: Another insight I missed is that, because there are no straights, it's always better to have more of a card, so you don't need to iterate all the permutations of each joker. You can just iterate once and set all jokers to each value in turn.
3
u/davidsharick Dec 07 '23
[LANGUAGE: Python 3] 94 / 184
Gitlab
Another easy one, and my second global leaderboard of the year!
3
u/seligman99 Dec 07 '23
[LANGUAGE: Python] 869 / 1136
github
Huh. Finding jokers under pressure. Interesting skill I didn't know I didn't have.
3
u/Sourish17 Dec 07 '23
[LANGUAGE: Python3]
#931/#490
p1: https://github.com/SourishS17/aoc2023/blob/main/seven-a.py
p2: https://github.com/SourishS17/aoc2023/blob/main/seven-b.py
sucky rank, sucky code, sucky day for me... should be interesting to see how other people did it!
Enjoy your Thursday folks :)
3
u/PlugAdapter_ Dec 07 '23
[LANGUAGE: Python] The problem becomes trivial once you realise you can represent the values of a hand by treating it like a number in base 13. solution
3
u/Sharparam Dec 07 '23
[LANGUAGE: Ruby]
A wordy one today, and a bit big to paste here: https://github.com/Sharparam/advent-of-code/blob/main/src/2023/07/solve.rb
Not very difficult for an odd day :)
3
u/xoronth Dec 07 '23
[LANGUAGE: Python]
paste.
I was dumb and tripped up on some of the part 2 joker implementation for longer than I would have liked, and I also wasted some time on part 1 remembering how to write a function for
sortto handle the letter card values.3
u/morgoth1145 Dec 07 '23 edited Dec 07 '23
[LANGUAGE: Python 3] Embarrassing/Embarrassing Ugly raw solution code
I lost soooooooooooo much time, in fact at least 20 minutes. (Likely more as I was trying to get the sample input working before I submitted my first answer.) I had two errors:
collections.Counter.most_common()would handle the type order properly too. (It does not!) Thankfully I already had a classification function written.I was secretly hoping that the Part 2 twist would be ordering in a more poker-like manner since I was already prepped for that, but J's being wild wasn't too bad.
Advent of Reading Comprehension got to me today. Time to go clean up my dumpster fire of a solution...
Edit: Cleaned up code
Edit 2: Now that it's morning, I'm thinking that part of my issues this year has been the quality of the example inputs. It feels to me like they're worse this year, not covering very easy misconceptions. I know that input trickery sometimes comes up later in the event, but at least the two examples that come to my mind (
oneightfrom day 1 and and33445beating22KKTtoday) feel like cases the example inputs should have clarified/caught. (Especiallyoneight, that was day 1!)3
u/RiotNu Dec 07 '23
[LANGUAGE: C++20]
1234/757
Had to work through a few bugs, but otherwise this one felt straightforward!
3
u/michaelgallagher Dec 07 '23
[Language: Python]
Who wants spaghetti?
3
u/FCBStar-of-the-South Dec 07 '23
[LANGUAGE: python3]
Making a class with a custom comparator seems to be the most straightforward implementation since the built-in sort can then be used.
paste
3
u/Wayoshi Dec 07 '23 edited Dec 07 '23
[LANGUAGE: Python3]
All the edge cases on part 2 were somewhat tedious for me to work through, that left to right tiebreaker provision is certainly the twist on a regular poker hand. I bet looking at my long chain of if/else for that section, a lot of code condensing can be done now.
paste
EDIT: Yep, I see it now, if the unique number of counts in the non-joker portion is just 1, you replace with the highest rank to break that tie, otherwise you replace with the card that has the highest existing count. I really couldn't see this without coding every case out first, oh well.
revised paste
EDIT2: More succinctly one overall sort by count then rank. Now it seems so obvious... I just couldn't quite grasp it myself.
final revision paste
3
u/msschmitt Dec 07 '23
[LANGUAGE: Python 3]
Part 1
Part 2
I got lucky, Part 2 was only a few lines different than part 1.
The basic idea was to create a sort key that was the type (arranged so they were in a collating sequence), followed by the cards but with characters changed so they were also in the same collating sequence.
For jokers, all was needed to to change them to 0 for sorting. For forming a hand, just add the number of jokers to whatever's the most frequent card. But watch out for JJJJJ!
3
u/mattbillenstein Dec 07 '23 edited Dec 07 '23
[LANGUAGE: Python]
Pretty simple; was able to simplify quite a bit after getting the answers.
3
u/emceewit Dec 07 '23
[LANGUAGE: Haskell]
https://github.com/mcwitt/puzzles/blob/main/aoc/app/Y2023/D07/Main.hs
3
u/JustinHuPrime Dec 07 '23
[LANGUAGE: x86_64 assembly with Linux syscalls]
Part 1 and part 2 were surprisingly similar - for both, I parsed the cards, mapping letter cards to their rank ordering (so for part 1, t = 10, j = 11, and so on, and for part 2, t = 10, j = 1, q = 11, and so on (although I could have just modified j = 1, I guess...), and recording the bid, as a word - I decided that I would pack the input data into a qword per hand so that I could apply my
qsortfunction that I'd already written with minimal modifications.So about that minimal modification to
qsort- I modified it so that it compared hands instead of integers; first, if the rank was the same, then I actually did compare the hands integer-wise (why implement your own byte-by-byte comparison when you can do it using x86_64'scmp?). If the ranks were different, then I just returned the difference of the ranks. To compare the ranks, I converted each hand into a numeric value such that the value of a hand of each rank was properly sorted. I did this by counting the number of cards (2 to ace), then adding one to each count, squaring the counts, and summing the resulting squares. This let me sort the ranks of the cards without any fiddling around with branching. (Ah, don't you just love branchless code?)This needed only a minimal modification for part 2 - I separated out the jokers from the count, and then added it to the largest current count (breaking ties in favour of the first count encountered, not that it mattered). I could do this since
nof a kind is always better than any combination with at mostn - 1of a kind.Part 1 and part 2 run in 2 milliseconds; part 1 is 9072 bytes long and part 2 is 9128 bytes long.
3
u/encse Dec 07 '23
[LANGUAGE: C#]
I found a nice and compact way to calculate the 'points' for each hand. Code is commented.
https://github.com/encse/adventofcode/blob/master/2023/Day07/Solution.cs
3
u/TankLivsMatr Dec 07 '23
[LANGUAGE: Go]
I was particularly proud of this one due to the fact that I could use Go's sort.Slice() method from the "sort" package. Allowing me to create a custom sorting method that would get the "hand type", and if they were equal, then map the letters to numbers and then compare each pair of cards. This was also surprisingly fast.
To figure out the hand type, I literally just mapped the number of each card in the hand, and then made an assumption of the type of hand based on how much of each was in the hand. (i.e. if there was one of each then its a high card. If there was only 4 unique cards then we know its a 1 pair, if there were 3 unique cards then we know it's a two pair, and so on.)
For the Jack part, this is as simple as finding the most re-occurring card besides the jacks, and then adding that number to that cards map entry.
I was dreading this, but honestly this was a really fun one.
Day 7
3
u/aviral-goel Dec 07 '23 edited Dec 07 '23
[LANGUAGE: F#]
https://github.com/aviralg/advent-of-code/blob/main/2023/07/solution.fsx
3
u/nitekat1124 Dec 07 '23
[LANGUAGE: Python]
GitHub
I assign a score to each type, such as:
50 for 'Five of a Kind',
40 for 'Four of a Kind',
32 for 'Full House',
30 for 'Three of a Kind',
22 for 'Two Pair',
20 for 'One Pair',
10 for 'High Card'.
easy to sort later and convenient when working with jokers.
3
u/wimglenn Dec 07 '23 edited Dec 07 '23
[LANGUAGE: Python]
I had these two sort keys:
Then the parsing + scoring is trivial:
Full code here
3
u/bld-googler Dec 07 '23
[LANGUAGE: Julia]
Solution on My Website
I first implemented the
islessfunction in Julia to use theBase.sortmethod. That worked but was slower than I wanted (since I was reevaluating the hands each time I compared them). So instead, I defined a scoring system (bits 24:21 describing hand type, 20:1 describing backup ordering), and defined a mapping from the scores to the hands, sorted the integers, and did the winning calculation using the mapping.The final version runs in 2.4ms - there's probably more room for improvement if I really care, but I'm pretty ok with it.
3
u/A-Marko Dec 07 '23
[LANGUAGE: Uiua 0.6.0]
Link
The rise ⍏ function really shines here for getting a secondary order and ranking.
3
u/molarmanful Dec 07 '23
[LANGUAGE: sclin]
Link
This challenge was perfect for sclin!
Part 1
For each hand...
Get hand's type and pair with the hand
Use sclin's built-in comparison capabilities to sort the hands
[5] > [4 1] > [3 2] > [3 1 1] > [2 2 1] > [2 1 1 1] > [1 1 1 1 1]Part 2
No big modifications, just an extra line for the Joker. The changes:
When getting each hand's type:
3
u/34rthw0rm Dec 07 '23
[language: tcl]
part1
part2
3
u/NimbyDagda Dec 07 '23
[Language: Python]
Hardly seems worth posting it, but I guess I will keep the streak going.
Day 7
3
u/DaveRecurses Dec 07 '23 edited Dec 07 '23
[LANGUAGE: rust]
I am always pleased with myself when I can solve the problem using a single statement.
3
u/AlexAegis Dec 07 '23
[Language: TypeScript]
I wrote a poker style comparator first, calculating the strength of the pairs/triples etc first and them comparing in order of the importance: HandType (Flush/Pair etc) -> Power of the most significant portion of the hand (eg: Triple of a full house) -> Remaining cards as high cards (sum of their power) but I didn't get a star out of that so I read the task properly and saw that comparing within a HandType is different..
part1
part2
3
u/cranil Dec 07 '23
[Language: Rust]
This one was a bit tedious. Not really hard. I had a bit of a hard time with part 2 because I missed a small check.
Day 7
3
u/bakibol Dec 07 '23 edited Dec 07 '23
[Language: Python]
two edge cases for part two: All J's and no J's.
completes in < 10 ms
code
3
u/simpleauthority Dec 07 '23
[LANGUAGE: Java]
My solution is pretty gross. But, that's okay. Had some fun figuring out the cases for card promotion in part 2 and left myself comments. IDE really wants me to clean it up, but I'm ignoring it because the comments are helpful to me.
Link to GitHub
(most of the work is in Hand.java, the link goes to the solution class.)
3
u/aamKaPed Dec 07 '23 edited Dec 07 '23
[Language: Rust]
This was something different and quite interesting! I ended up implementing custom ordering functions for the hands and the individual cards. The second part took way too long because of silly mistakes I made in upgrading the hands.
Both parts run in ~7ms each on my computer.
Part 1, Part 2
3
u/plusminus1 Dec 07 '23
[LANGUAGE: C#]
Pretty straightforward. Could probably be 50% shorter but this is very readable at least.
Not the feared "odd" difficulty.
paste
3
u/trevdak2 Dec 07 '23 edited Dec 07 '23
[Language: Javascript Golf]
Part 1, 296 Chars:
Part 2, 335 Chars:
One thing I noticed missing from other people's solutions... You never need to know what kind of hand someone has, you just need to know if it is better than others. If you figure out how to rank hands, it simplifies the problem significantly
For scoring hands, I used this method:
3
u/Tagonist42 Dec 07 '23
[Language: Rust]
Writing the
hand_typefunction was my favorite bit from today. Snippet:3
u/chkas Dec 07 '23
[Language: Easylang]
Solution
3
u/MikTheVegan Dec 07 '23
[Language: Python]
Part 1 & 2 were so different so no reason to wrap them to one file:
Part 1
Part_2
3
u/Kintelligence Dec 07 '23
[Language: rust]
https://github.com/Kintelligence/advent-of-code-2023/blob/master/day-07/src/lib.rs
Optimizing for speed. Calculating the strength of a hand when parsing it and storing it in a single u32. Then just letting the built in sorting handle the rest.
Also started adding tests to ensure the solutions keeps running after refactoring and optimizing. Each part takes ~80µs.
Benchmarks Part 1 Part 2
3
u/voidhawk42 Dec 07 '23 edited Dec 08 '23
[LANGUAGE: Dyalog APL]
Video walkthrough
Main interesting thing is that if you look at the lengths of the groups of cards, sort descending, take the first two elements and make them into a 2-digit number, that's a sufficient key to sort on for all the hand rankings.
So
342QK->1 1 1 1 1-> 11,AAAQQ->3 2-> 32,KKKKK->5-> 50, etc.Didn't do anything special for the jokers, just tried all possible values and took the maximum number from the above rule. Runs more or less instantly anyway.
3
u/G_de_Volpiano Dec 07 '23 edited Dec 07 '23
[LANGUAGE: Haskell]
Today should have been pretty straightforward. Define a data type, deriving Show, Eq and Ord, and there you go. A little added complexity by the fact that the low cards were digits, which don't make for great constructor names. I hesitated to create a data type for hands too, with a custom Ordering, but as it turned out, that would have been detrimental for part two. I might still toy with it to see if it improves performance.
Part two was pretty straightforward too, design new comparison algorithms for hand types and hands of equal type taking in account the new values of J. Which should have been pretty much straightforward, had it not been for one line where I forgot to take out the Js in one of my early guards which ended up with me having more Two pairs and less Fulls than I should have.
Edit: original execution times.
part 1CPU time: 0.047spart 2CPU time: 0.032s
Edit : I ended up doing creating separate data types for part one and part two hands, instantiating the same class. Actually halved the execution time.
part 1CPU time: 0.021spart 2CPU time: 0.019s
Overall, a pretty nice, straight shooting day 7.
https://github.com/GuillaumedeVolpiano/adventOfCode/blob/master/2023/days/Day7.hs
3
u/4HbQ Dec 07 '23 edited Dec 07 '23
[LANGUAGE: Python]
Anyone up for a round of golf?
Part 2, 218 bytes:
3
u/s3aker Dec 07 '23
[LANGUAGE: Raku]
solution
3
u/Piggelinmannen Dec 07 '23 edited Dec 07 '23
[Language: Ruby]
Struggled a bit with base case (all jokers etc) in part b.
Link to file in github
3
u/comforttiger Dec 07 '23
[LANGUAGE: Ruby]
https://github.com/comforttiger/advent_of_code/blob/main/2023/ruby/day7.rb
this one was fun to solve :)
i didnt think super hard about my part 2 solution, i just kind of assumed that you'll get the best type possible by putting all the jokers in the biggest stack. its very satisfying when an assumption like that turns out correct!
3
u/timvisee Dec 07 '23
[Language: Rust]
Quite fast, though, slowest day by far until now.
3
u/Desthiny Dec 07 '23
[LANGUAGE: Rust]
Implemented Ord for hands, and used enum's derived Ord in order for the solution to be just sorting after parsing.
https://github.com/AloizioMacedo/aoc2023/blob/master/Rust/day7/src/main.rs
A LOT of time spent in debugging in part two. The provided test case is not very extensive in terms of potential problems : /
3
u/Particular-Hornet107 Dec 07 '23
[Language: Python]
Did this by sorting hands into "buckets" and then sorting within each bucket.
Part 2 was easy assuming that its always optimal to replace all the jokers with the same card. I made a list of scenarios and it seems to be the case, but does anyone know if there's a way to prove this nicely?
Github
3
u/royvanrijn Dec 07 '23 edited Dec 07 '23
[Language: Java]
I quickly realized that counting the cards and sorting the result will give you a unique mapping to either "11111","1112","122","3","23","4" or "5". This can be used to sort all the hands.
In the end, with the jokers, you can just remove those first and adding them to the largest amount. This change was thankfully trivial.
Here is the complete code:
3
u/glebm Dec 07 '23 edited Dec 07 '23
[Language: Ruby]
Part 1:
Part 2:
All solutions: https://github.com/glebm/advent-of-code
3
u/darkpouet Dec 07 '23
[Language: Typescript]
Why sort numbers when everything is a string?
3
u/damnian Dec 07 '23 edited Dec 08 '23
[LANGUAGE: C#]
GitHub
A hand's sorting key is calculated in three stages:
the
getTypedelegate (changes between Part1 and Part2) is invoked and shifted by 20:each card is mapped to its index and added with 4-bit shifts:
Edit: I reshuffled those Camel Cards to make them much simpler and faster.
getTypefor Part 2 becameEdit 2: Found a very simple formula for
GetType():Edit 3: Simplified stages into a one-liner:
3
u/SpaceHonk Dec 07 '23
[Language: Swift] (code)
Pretty much straightforward and easy.
In part 1, ranks are determined based on a dictionary of counts per card, ties in sorting are broken using a simple Character -> Score map.
For part 2, Jokers are removed from the dictionary which made the switch statement slightly more convoluted and nested, and the tie breaking map needed to change.
3
u/[deleted] Dec 07 '23
[Language: Python]
github
A highlight of this solution is calculating the "signature" of a hand as a tuple, and using that to compare.
scores = [(1, 1, 1, 1, 1), (1, 1, 1, 2), (1, 2, 2), (1, 1, 3), (2, 3), (1, 4), (5,)]The order of winning hands is a lexicographic ordering of the signatures, which makes dealing with the jokers nice and easy.
3
u/HealYouDown Dec 07 '23
[LANGUAGE: Python]
A bit overkill, but understandable I hope
https://github.com/HealYouDown/advent-of-code-2023/blob/main/day_07.py
3
u/Radiadorineitor Dec 07 '23
[LANGUAGE: Dyalog APL]
3
u/Dullstar Dec 07 '23
[LANGUAGE: D]
https://github.com/Dullstar/Advent_Of_Code/blob/main/D/source/year2023/day07.d
Today was a lot more about fighting the language than about fighting the problem itself. The problem was easy. The language, however, decided that today was template purgatory today. In case you want to know if D is any better at producing comprehensible template errors than C++... no it is not. If anything, it might actually be (slightly) worse.
opCmp was also annoying to overload thanks to bizarre examples and a chart that at first glance looks like it's technical details about compiler de-sugaring intricacies that you probably don't care about but is actually about the semantics. Fun! (They really could have explained it in like 2 sentences, too. It's exactly like strcmp in C).
3
u/zniperr Dec 07 '23 edited Dec 07 '23
[LANGUAGE: Python]
3
u/clouddjr Dec 07 '23
[LANGUAGE: Kotlin]
For part 2, I simply added jokers count to the most frequent char.
Solution
3
u/Mammoth_Spray_3451 Dec 07 '23
[LANGUAGE: Swift]
Today was fairly easy compared to earlier days. Had to fiddle around to make part 2 work for input "JJJJJ" but in the end it wasn't that hard.
Solution
3
u/Pyr0Byt3 Dec 07 '23 edited Dec 07 '23
[LANGUAGE: Go] [LANGUAGE: Golang]
https://github.com/mnml/aoc/blob/main/2023/07/1.go
I'm kinda proud of this one.
For determining the hand type, simply going char by char and adding up the
strings.Counts together turns out to be sufficient to differentiate. i.e. adding up all the individual character counts for a high card gives 5 (1+1+1+1+1). For pair, since there's two chars that appear twice in the string, it gives 7 (2+2+1+1+1). Two pair = 9, three of a kind = 11, full house = 13, four of a kind = 17, five of a kind = 25.For breaking ties, I essentially convert the string's characters from 2-A into a base-13 string (0-C) using strings.Replacer. I then use strconv.ParseInt (which luckily takes a base) to convert that string into an int.To combine both parts, I multiply the type portion by 13^5 ("shift left 5" in base-13) and add it together with the tiebreaker value. This results in a single "score" for each hand, which can be used to sort the list and get the result.Very fun problem overall!
EDIT: I simplified my code a bit and got rid of the base-13 stuff in favor of a simple
strings.Compare. The approach is largely the same: I get the "hash" I mentioned for the hand type, replace the problematic TJQKA values with ABCDE so they sort nicely, and then just concatenate them and compare.3
u/ash30342 Dec 07 '23
[Language: Java]
Code: Day07
Both parts run ~ 5ms. The logic for finding the best possible hand can probably be more concise but at least now it is relatively readable and understandable. For me at least ;-)
3
u/Cyclotheme Dec 07 '23
[LANGUAGE: QuickBASIC]
Github link
3
u/Tipa16384 Dec 07 '23
[LANGUAGE: Python 3.11]
Converts the hands to hexadecimal -- first digit is the rank of the hand, followed by five hex digits encoding the hand (differently in P1 and P2). Then it's just a matter of sorting the list and printing the answer.
Github
3
u/lboshuizen Dec 07 '23 edited Dec 11 '23
[LANGUAGE: F#]
Github
Was bit tricky to find the missing edge case, but all in all straigth forward
Poker game in 40 lines :-)
3
u/p88h Dec 07 '23 edited Dec 19 '23
[LANGUAGE: Mojo] vs [LANGUAGE: Python]
https://github.com/p88h/aoc2023/blob/main/day07.mojo
https://github.com/p88h/aoc2023/blob/main/day07.py
This was as good time as any to completely rewrite the string parsing code, and implement proper string slice handling that is desperately missing in Mojo. Which helped in this problem, but also resolved most of the performance gaps in previous days, making Mojo faster than Python. Well, at the cost of having to use ASCII character codes directly, since Mojo doesn't have a character type and ord(str) is frustratingly slow. At least no new Mojo bugs today.
Oh, and well, had to implement heapsort, since that seems to be missing as well.
Benchmarks for the last day, the rest is updated on GitHub
3
u/tymscar Dec 07 '23 edited Dec 07 '23
[LANGUAGE: Rust]
I really enjoyed todays puzzle.
I like how I solved part1, I would maybe only improve it by making the cards their own type and then having the functions related to that implemented on it, but it's fine either way.
For part2 I have used recursion, and theres a lot of sorting going on anyways, which makes it run in around a second and a bit, which is quite a lot.
Edit: changed up part2. I am not generating all the card decks anymore and now I am matching on number of jokers. Got it down to 6ms runtime.
Part1 and part2
3
u/TheZigerionScammer Dec 07 '23
[LANGUAGE: Python]
Alright, this was a fun one. I first considered writing a function that would compare two hands and say which one was better, then use that as the basis for implementing of the sorting algorithms I've learned about over the last year or so, but I decided against that. Instead I wrote a function that would return the characteristics of the hand, the hand type as an integer and the reworked string of the hand, and then Python could sort the list on it's own.
The way it works is it turns the hand into a set. If the set has 1, 4, or 5 characters in it, we already know what type of hand it is. If it has 2 or 3 then there a couple more if statements to determine the hand type, but after this each hand will be identified. Then it takes the hand string and replaces each face card with a letter, B through F. (I wanted to avoid A since that represents the Ace.) Luckily Python considers all letters to be "higher" than numbers when sorting so this will work fine. When all of the hands are placed in a single list represented by a tuple of the hand type, the modified string, and the bid, Python's own sort function will sort all of the hands correctly.
For Part 2 I figured that replacing the Joker with the value of whatever other card already appears the most will always be the optimal solution, so I added another section to do that before running the aforementioned code if it's Part 2. But here I ran into some bugs. What if he card that appears the most is the Joker? Had to tell it to skip counting Jokers. What if the hand is all Jokers? Had to make a special exception for that. Of course it also replaces the Jokers with a "1" in the string to account for the rule that Jokers are now the least valued card. Same basic sorting again based on the new rules, got the right answer. I moved both of those parts into a loop to clean up the code a bit too.
Very interesting problem team!
Code
3
u/CainKellye Dec 07 '23 edited Dec 07 '23
[LANGUAGE: Rust]
https://github.com/cainkellye/advent_of_code/blob/main/src/y2023/day07.rs
Part 2 was only a slight modification, so I merged the code and branched on a Part enum where needed.
My scoring is like: count the card faces into an array, sort the array, get the last two (biggest counts), and swap them. This results in an array like [most_copies, second_most_copies]. They can be compared by the std cmp() function.
When they score equal, find the first different character, get the face value and return which is greater.
3
u/AdmirableUse2453 Dec 07 '23
[LANGUAGE: Golang]
New to golang.
What I did is Calculate card strength in hexadecimal T =A, J =B, Q = C... etc.
Add 1 to the left for a high card, 2 for a pair, etc., then convert the value back to an integer sort by value calculate the total in ascending order and (index + 1) * bet amount.
I had a little bit of trouble with part 2.
My code is ugly but it works:
https://github.com/maximepinard/AoC2023/blob/main/day7/main.go
3
u/astro_wonk Dec 07 '23
[Language: Python]
Ooof, made a little
Handclass and defined__lt__and then for part 2, aHand2class that substitutes the Joker with the most common (non-Joker) card. BUT, I didn't read the Part 2 instruction about Jokers being the worst card for tiebreakers. Spent ages trying to figure out what I was doing wrong, when I was just implementing the wrong idea, correctly.Code here
3
u/Embarrassed-Hawk2395 Dec 07 '23 edited Dec 07 '23
[Language: Rust]
The idea was to use iterators as much as possible (except for parsing).
Code
3
u/FlockOnFire Dec 07 '23 edited Dec 07 '23
[LANGUAGE: Elixir] Day 07
Thought pattern matching would work great, but didn't realize Elixir requires an explicit check
a != bandb != nfor a match on[a, a, b, b, n]. Without it[1, 1, 0, 0, 0]matches and returns the wrong result!In hindsight it makes sense and I reckon it can be very useful. Just not for this puzzle. :D
3
u/evans88 Dec 07 '23
[Language: Python] p2 solution (paste)
Made heavy use of
Counteras well as using match/case to define all the games. I created my own class with custom__lt__and__eq__for sorting.3
u/hrunt Dec 07 '23
[LANGUAGE: Python]
Code
Part 1 was very straightforward. I setup a class for bundling up the card comparison and rank calculation. Python's standard library Counter class is very useful for retrieving a list of occurrences ordered by count. The class made Part 2 relatively straightforward as well. Count the jokers, count the occurrences without the jokers, then replace the jokers with the most common remaining card. Since my rank calculator was based on Counter's
most_common()method and you can add Counters to each other, I just used Counters to add the replacements and submitted the result to the ranking method.Originally, when I did Part 2, I wasn't sure if replacing all of the jokers with the most commonly occurring card yield the highest rank in every situation, so my original solution (not in the code paste) used
combinations_with_replacement()to try every possible combination of the non-joker cards. That ran just as quick as the final solution, but after thinking about it a bit, I realized that based on the ranking rules (joker is always the lowest, ties settled by first best card), there's no situation where the jokers replacing the most common remaining card wouldn't net the best rank.3
u/Lars-Kristian91 Dec 07 '23
[LANGUAGE: C#]
Code: Github
I had fun solving today's puzzle. Started off by creating a struct that contained the hand data. Got into problems when trying to define a fixed size array inside the struct (unsafe in C#). I did not want to allocate multiple small arrays on the heap. So I ended up packing all the cards inside a u64 type. This leads to a lot of logic in the sort/compare function. Most of the time was spent sorting and I wanted to improve this. Ended up packing the entire hand inside a u64 type. This and some clever arrangement of the different parts, made it so no special code was needed for sorting. :)
I find it funny that Part 2 is faster for 1 of the computers I tested on. No idea why that happens, so I had to test multiple times. Maybe it has something to do with the sorting function.
I run benchmarks on 2 computers:
[search tag: ms]
Part 1
Part 2
3
u/Lakret Dec 07 '23
[LANGUAGE: Elixir]
Really liked this day's challenge and it was easy enough with the Elixir's term sorting.
Code
Writeup
3
u/xHyroM Dec 07 '23 edited Dec 11 '23
[LANGUAGE: Python]
w/ class, enum, counter
part 1 part 2
3
u/cbh66 Dec 07 '23
[LANGUAGE: Pickcode]
I had a lot of fun with this one. For scoring, I computed an 11-digit number for each hand by concatenating a number for the type (0 to 6) plus the strength for each card in order (00 to 12 each). I stored them as strings since they're big numbers, but that meant I could just use string comparisons on the score and didn't have to hand-code the logic for tie-breaking. I had to implement my own selection sort, and it's not very speedy, but luckily the input size isn't too big.
When it came time for part 2, I didn't know what else to do but to copy the bulk of the part 1 code and make a few adjustments. I just enumerated all the wildcard cases, I'll be interested to look at others' code to see if you can do something smarter.
https://app.pickcode.io/project/clpv8z35t7782op01oiv5zfln
3
u/HoooooWHO Dec 07 '23
[LANGUAGE: Python]
No imports
Part 1: https://github.com/PetchyAL/AoC2023/blob/main/solutions/day07/day7_part1.py
Part 2: https://github.com/PetchyAL/AoC2023/blob/main/solutions/day07/day7_part2.py
Separate files because it looks ugly as a single file lol, but most things are the identical between the 2
3
u/grendel-khan Dec 07 '23
[Language: Python3]
Part 1:
collections.Counterwas extremely useful here, and a simple translation table allowed construction of very legible keys, e.g,handsort(QQQJA) = 4.CCCDA.Part 2:
Only very minor changes; it turns out that adding the joker count to the highest current card-count is the optimal strategy. Handle the
JJJJJedge case, edit the high-card lookup table, and you're done.3
u/mathsaey Dec 07 '23
[Language: Elixir] https://github.com/mathsaey/adventofcode/blob/master/lib/2023/7.ex
Fun day today. Spent some time cleaning up my solution to be fairly generic. The "JJJJJ" edge case bit me for a bit, but that's the kind of thing pattern matching is useful for!
3
u/Afkadrian Dec 07 '23
[LANGUAGE: Rust]
I'm very proud of this solution. I found a discriminant that lets me recognize the type of hand with a single check. Each part takes less than 150 microseconds to run. Almost zero allocations (only 1 vec).
https://github.com/adriandelgado/advent-of-code/blob/main/src/y2023/d07.rs
3
u/LumpySurprise Dec 07 '23 edited Dec 07 '23
[LANGUAGE: Javascript]
https://github.com/charliebeckstrand/aoc/blob/main/2023/day07/part1.js
https://github.com/charliebeckstrand/aoc/blob/main/2023/day07/part2.js
Not much to say. This one was fun and still easier than day 5.
I originally tracked cards and card types using key-value pairs but the hand evaluation is more pleasant to read using arrays and .includes().
I was worried that I would have to gut the evaluation function for part 2 but using .map() substitution proved to be efficient and easy to read imo.
3
u/pavel1269 Dec 07 '23
[LANGUAGE: rust]
https://github.com/pavel1269/advent-of-code/blob/main/2023/day07/src/main.rs
Nice challenge to handle all the cases correctly.
3
u/CachooCoo Dec 07 '23
[LANGUAGE: C]
https://pastebin.com/xua7Ukxh
I guess the only interesting thing about today was determining the strength of the hand. Keeping track of the top 2 number of copies of a card you have lets you easily determine the strength. Then, for part 2 you don't count the jokers as part of the top 2 number of copies, but instead add them to the most copies of a card you have.
3
u/__Abigail__ Dec 07 '23
[LANGUAGE: Perl]
Full program and Blog post.
3
u/N-R-K Dec 07 '23
[LANGUAGE: Tcl]
Link to code (~20 lines).
The goal for me was to do it in as few lines as possible. The main trick was to build up a hex string which contains both the hand strength and the hand itself (to resolve ties).
First it collects the frequency of each char and sorts it (
AAK11 -> 2,2,1). Then the frequencies are joined and 0 padded (2,2,1 -> 22100) so they can work with standard relational operators. For part 2, I simply removed the joker from the frequency map and then added the joker count to the highest frequency - the rest was pretty much the same.Also surprised to see many others using Tcl here this year.
3
u/Derailed_Dash Dec 07 '23 edited Dec 11 '23
[LANGUAGE: Python]
Solution in Jupyter notebook
3
u/thousandsongs Dec 07 '23 edited Dec 07 '23
[LANGUAGE: English][Allez Cuisine!]
On a camel’s back,
In a faraway land
An Elf at my front
A card in her hand.
For each hand
An int described
An int was bet
A rank was fied
Sorting algorithms
Amortised ran
In dusty dunes
Of Elvish Lands
For long we played
Amok the Jokers ran
Camel Cards
In a faraway land
(ps: my code solution)
3
u/bo-tato Dec 07 '23
[LANGUAGE: Common Lisp]
No fancy tricks, just a big case statement to find the type of the hand: https://github.com/bo-tato/advent-of-code-2023/blob/main/day7/day7.lisp
3
u/Singing-In-The-Storm Dec 07 '23
[LANGUAGE: JavaScript]
Parts 1 & 2 (under 33ms each)
code on github
3
u/-Hiroshi-0001 Dec 07 '23 edited Dec 07 '23
[LANGUAGE: rust]
Part1 is finished, part2 is beeing worked on
https://github.com/LukasHuth/aoc23/blob/master/src/days/day7.rs
3
u/ren1by Dec 07 '23
[LANGUAGE: Python]
Part 1 and 2
First day I've used recursion. Part 2 was pretty simple, just added Jack count to the most common card.
3
u/Ok-Group4131 Dec 07 '23
[LANGUAGE: Python]
github
3
u/prendradjaja Dec 07 '23
[LANGUAGE: Python]
a.py (part 1) / b.py (part 2)
Here's one way to do part 2. This function is nice and easy to write using generators (
yield)!One minor optimization possible in part 2: b.faster.py (compare
resolve_jokers()in b.py)3
u/Jadarma Dec 07 '23
[LANGUAGE: Kotlin]
This was my favorite day so far this year, by far! I got to model a nice domain, both parts solvable through the exact same codepath, and the rules were pretty nice to us, given they did not make us consider Straights, just amount of pairs.
For part two, before parsing the input, I swap out all
Js with*(wildcards, get it?), and count them separately from the other pairs. Given the number and size of pairs of normal cards, you can manuallywhencase that to also account for the existence of jokers. Since there's only 5 maximum cards, it's pretty easy to write all possibilities in an almost concise way.AocKt Y2023D07
3
u/HaiUit Dec 07 '23 edited Dec 07 '23
[LANGUAGE: Ocaml]
2023 - D8 - OCaml
Using language with good support for pattern matching is such an enjoyment for today's problem.
3
u/silverarky Dec 07 '23
[LANGUAGE: Go]
Had to write some tests for part 2!
https://github.com/silverark/advent-of-code-2023/tree/master/day7
3
u/EvolvedPik Dec 07 '23
[LANGUAGE: Kotlin]
To determine hand type, I counted the number of distinct characters, and then further distinguished between full house and four kind, and between two pair and three kind.
To handle jokers, I replaced them with one of the most frequently used cards in the hand. Two edge cases:
Solution on GitHub
3
u/_rabbitfarm_ Dec 07 '23
[Language: Perl]
Solutions to both parts in Perl. I believe that Perl's easily customized sort function made this easier than it would have been in other languages.
Part 1: https://adamcrussell.livejournal.com/49525.html
Part 2: https://adamcrussell.livejournal.com/49693.html
3
u/chrismo80 Dec 07 '23
[LANGUAGE: Rust]
Github
3
u/thinnerthinker Dec 07 '23
[LANGUAGE: OCaml]
https://github.com/thinnerthinker/aoc2023/blob/main/bin/day07.ml
Just mapped out all configurations of (amount of jokers, groupings of cards) and that was it lol
3
u/Handsomefoxhf Dec 07 '23
[Language: Go]
Got both parts on the first try, once again a very nice challenge
GitHub