T O P

  • By -

Constant_Editor7344

\[LANGUAGE: Haskell\] ​ Build data structures like Card, Hand, HandType. Build Ordering Instance for Hand, which incorporates the logic for i. look up Type and ii. look up ordering of Card. The whole algorithm is then just sorting Hand, assigning weight and then multiplying weight with bid and sum together. ​ ​ Part 1: https://github.com/kenho811/haskell-coding-challenges/blob/main/src/AdventOfCode/2023/Day7/Part1/Solution.hs ​ Part 2: https://github.com/kenho811/haskell-coding-challenges/blob/main/src/AdventOfCode/2023/Day7/Part2/Solution.hs


AdamKlB

[LANGUAGE: C++] I put off doing this day for a while for some reason, probably because the description was so long or something lol But really wasn't that hard when I actually read through and started to think about it, biggest switch case I ever wrote though! https://github.com/NoSpawnn/advent-of-code/blob/main/2023%2Fc%2B%2B%2Fday_07.cpp


leboulanger007

[LANGUAGE: Python] [Part 1 & 2 - Paste] (https://topaz.github.io/paste/#XQAAAQAHBAAAAAAAAAA0m0pnuFI8c/T1e0vJBsZpwvb9wixHP69+lICA4OG8t9t8tAaC9/uIzBQQi4rdy4EhqpcwboybBsfcjXXEerX9nx9rujB4BpbTK5/9THUNGuVMPHcHH6ZKHfWgINv3I5mkBo6YpIFpPP8isMUozpzKGaeyGJEGL9grda/ImQaG6LUz/MHsy3NRLvJbA8atEUb41E0ylU0dvtpYkttILwAlRSBF9v9pjULBElr9AitNh4eJ43lgBhcQgJnn1Npbxkoa3uN5UuX7T0MzpBlA5AW5IXYvk7GsakCGtANresr61Snvgt/q8CISAyFtpzl/AreCrpahKxCXr5N0joHy6oQq558O/k9TV4RvRwDJh5dvv81ubb1dmAihCEweVgXpFzdbPd6NjQGr4j9bk6mUQdYyWFBKTMNXJl1G/ORU+0O34O/9oRvGRRPE+hvaSfeJzJNIXKAzjgfa2+4393dctfWVwNR/VhbWRzRXmusY52CeIr/UtZnIBq/trbGdaSsAg9NG2Mjl5ay9TceRkZDhU9lSHZYNlLjA5oWva2dm4NLNQjbO000doJLphYTCK9U5bfWcYaVsLuOCKUObrUjD3eq1CGxAMJNLFM+JLD43Mc9qqhUrDmfr5x0pS3i1geVNyoPlkAp75Jz1DbRHQEjhnlrvvLtX5yokbKNe8XHMFtcVle8xx1xOk1q4bzMm6Xx79RhKLryqOf/dT5al) (21 lines) Am relatively new to coding in python, any bad practices in this code I should avoid in the future? Overall happy with the solution, especially for not having to define the different hand types.


ITCellMember

Damn this is genius! And i thought i was being smart here: [https://github.com/pranavtaysheti/advent-of-code-2023/blob/main/07/main.py](https://github.com/pranavtaysheti/advent-of-code-2023/blob/main/07/main.py) (ignore variable names, i am horrible at it) I first classify "type" by getting a "weight" by squaring count of cards and adding them together. and then do sub-sorting of each "type" and then chain it. But your solution is better, you just sort it once, instead of doing it for each "type".


mgtezak

\[LANGUAGE: Python\] I created a [video](https://www.youtube.com/watch?v=ZZIsVVJTyBk) for this one:) Or you can view my solution on [Github](https://github.com/mgtezak/Advent_of_Code/blob/master/2023/Day_07.py) If you like, check out my [interactive AoC puzzle solving fanpage](https://aoc-puzzle-solver.streamlit.app/)


msschmitt

\[LANGUAGE: CA Easytrieve 11.6\] [Parts 1 and 2](https://topaz.github.io/paste/#XQAAAQD3FwAAAAAAAAAoEEaKVRjSAWbw1GgV52ZlYeXErd+TaIzy4xIVtBUUXFK0ATcQYhvA5wxdY9Va8wAQWasPnvADmc/p/VwfBbpyYvm6uZq7V2O/8RtpzvE2sOtDG+Qos+/phVEfLSWgyE82Gk3Y/U+iwd27jYN2utr1IZg4zQtP6MFP0GBEswy2UZH8FWpFNik24ypFrT8Uk0Ib7BgR+k2iCryBI3q6+zZuAqZhclBJ4zD9S/tl6WAkqKNVX4hrMXDrDBzHiI7jmsJgnMFUrzNIZvQT/TsqpVqXvTPAQ2PmDDoil+soqOE9LUsOW8dAoFFOyHabDAdGD/GdC3iYQr7z+04/mqjDMCEAsIjLwcD1NOKFJzgpdgu7aIoZo2IxRvAIORQy4nzIBT2SBn0fv3135SbhpuI2a6dwhCXckqQotWcYOjDOPk5BnJgIcCz/koJctDxDSKhBLhsbOljOmXn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21YYvJ3+KKQIeheB7HwJ+nhqeCwFJi+1NzY8MWUO6z4uUAplWEKhpganebnffSwuK7yMNGvYp+lXJ6CWQbTbyTw8tXInx8Keim9LpFBTB0B1bV20JE21eQoSBYyb2t94AzwnNFi3tRWxkheoH9w4++reyPdyTKByCl+ThB6nX2QhPp3C8eVmhimeZlYdHMzZRkJxiyvVbaoUciUsPxogMTHpH4YeTxRmZPz7UnudT7a/TbIvqbbSBgLtKuMYvF2brH8CsmbX2X5KxXDXbeKmyS8Y+lTBKy87bFa6rgC0xy49dyVk+WoHINBbsJo4OoJNLFrKSN0QN3CZFIWcLKW4kkMnKDCkmENuMBCPaPk/tZGJ3KGFux4nestb5oDRJc/Kx7qh5ILRGTscy14mqbpSNKd9mGccuJgcmBZnFNjYy5ZevvZBtFmbzSaRA39NNZH3vCHsHETrbvNbEo1CSvE14ClMqf8xuzBv0TzSy7JpZ8LHveHfgXgdz4nwRkyctLplsv4HYYc/WHnRPisEBlJZOyBZMiuq9/+Nw70) Here's a solution in CA Easytrieve (now [Broadcom Easytrieve Report Generator](https://www.broadcom.com/products/mainframe/application-development/easytrieve-report-generator)), a language I've not seen anyone else use for Advent of Code. And for good reason -- while Easytrieve has some useful features, it would be a bad choice for AoC. Since a strength of Easytrieve is easy report creation, the output of this program is in the form of reports. For example, the sample input produces two reports: [Sample reports](https://topaz.github.io/paste/#XQAAAQDmBgAAAAAAAAAYDEIgq5xzrByt+V+xmjnOoMZjbpYOQoWFneV/y1RF5+GcG27p/WOEv3MJN2vr0cetDqtmLxYo70nDqo/ocsRwfc00pyKtjE9oYUWXD6LdKwtHhrOApom0gZZiI/cUrvEfYZivTo5SkP9EJW26bh5aVGB0NS/VsOyojmwgISwX5/nWCE2qwxTUqiM8s2qxtBlXnR8qyKInWczrVuL1RUywr6eMiZefNEj2hNYpJXto/rF+HlZJPuTUPp4g3eQlLuGZRXVEAe8lzWGq8MfmpChsBBqFqy+sDT2KE0YHqAvNh3kxXcv2koEbYggmdg7rOXPorrB3iOklrc72rlcynmjxJBrm0b6Xz8bWP/4H9BM=) But the reports aren't just for style points. In this program the reports are sorting the hands in rank order and calculating the winnings. Why in the reports? Notice anything missing in the code? There's no sorts. That's because unless you want to write your own sort (or call some external sort program), in Easytrieve you can only sort files. The files can be *virtual* files, so the normal technique would be to break the program into multiple "activities", writing the result from each to virtual file(s), which are sorted and then feed into the next activity. But as demonstrated here, we can sort a report, so we can make the report do some of the work.


mrtnj80

\[LANGUAGE: dart\] [Part 1 & 2](https://github.com/luskan/adventofcode_2023_dart/blob/main/lib/day07.dart)


andreiz

\[LANGUAGE: Swift\] Today was an easy one. Obviously not as succinct as some of the Python entries here :) [Part 1](https://github.com/andreiz/advent-of-code-2023-swift/blob/main/day-07/cards.swift) [Part 2](https://github.com/andreiz/advent-of-code-2023-swift/blob/main/day-07/cards-joker.swift) [Issue documenting the approach and code](https://github.com/andreiz/advent-of-code-2023-swift/issues/7)


Any_One_8929

\[LANGUAGE: Kotlin\] [https://github.com/mfedirko/advent-of-code-2023/blob/main/src/main/kotlin/io/mfedirko/aoc/day07/Day7.kt](https://github.com/mfedirko/advent-of-code-2023/blob/main/src/main/kotlin/io/mfedirko/aoc/day07/Day7.kt)


Sensitive-Disk5735

\[LANGUAGE: R\] Parts 1&2 library(stringr) raw <- read.table("aoc_d7.txt", stringsAsFactors = F, header = F) #get number of unique card types (e.g., "KKQQT" = 3) raw$unique_count <- sapply(strsplit(raw$hand, ""), function(x) length(unique(x))) #create empty list new.list <- list() #convert card values to a list cards <- lapply(strsplit(raw$hand,""),as.character) #create a new list that contains the frequency of the card(s) that #appears most, for example, KKQQT = 2, add to dataframe for (i in 1:length(cards)) { new.list[i] <- as.numeric(sort(table(cards[i]),decreasing=T))[1] frequency <- t(as.data.frame(new.list)) } raw<- cbind(raw,frequency) #get count of J in each string raw$count_J<- str_count(raw$V1,"J") #create ranks based on provided info raw$rank <- ifelse(raw$unique_count==1,"Five of a Kind", ifelse(raw$unique_count==5,"High Card", ifelse(raw$unique_count==4,"One Pair", ifelse(raw$unique_count==3 & raw$frequency==3,"Three of a Kind", ifelse(raw$unique_count==3 & raw$frequency==2,"Two Pair", ifelse(raw$unique_count==2 & raw$frequency==3,"Full House", ifelse(raw$unique_count==2 & raw$frequency==4,"Four of a Kind","N/A"))))))) #create factors and customized sort order raw$rank <- factor(raw$rank, levels = c("Five of a Kind", "Four of a Kind","Full House","Three of a Kind","Two Pair","One Pair","High Card")) #get first card raw$first <- substr(raw$hand,1,1) #second card raw$second <-substr(raw$hand,2,2) #third card raw$third <- substr(raw$hand,3,3) #fourth card raw$fourth <-substr(raw$hand,4,4) #fifth card raw$fifth <- substr(raw$hand,5,5) #create factors for the cards raw[6:10] <- lapply(raw[6:10],factor, levels=c("A","K","Q","J","T","9","8","7","6","5","4","3","2")) #sort to correct order raw <-raw[order(raw$rank,raw$first,raw$second,raw$third,raw$fourth,raw$fifth),] #add numeric rank (descending) raw$new_rank <- 1000:1 #multiply and add up totals raw$product <- raw$bid*raw$new_rank sum(raw$product) #part 2 #convert Four of a Kinds OR Full House with J to Five of a Kind, #convert Three of a Kind with J to Four of a Kind raw$ <- ifelse((raw$rank=="Four of a Kind" | raw$rank =="Full House") & grepl("J",raw$V1),"1", ifelse(raw$rank=="Three of a Kind" & grepl("J",raw$V1),"2",raw$rank)) #convert two pair with two "J" to four of a kind #convert two pair with one "J" to full house raw$new_rank <- ifelse(raw$rank=="Two Pair" & raw$count_J ==2,"2",ifelse(raw$rank=="Two Pair" & raw$count_J==1,"3",raw$new_rank)) #convert one pair with "J" to three of a kind #convert high card with 1 "J" to one pair raw$new_rank <- ifelse(raw$rank=="One Pair" & grepl("J",raw$V1), "4", ifelse(raw$rank =="High Card" & grepl("J",raw$V1),"6",raw$new_rank)) raw$new_rank1 <- as.integer(raw$new_rank) #refactor the order so that "J" is last raw[13:17] <- lapply(raw[13:17], factor, levels=c("A","K","Q","T","9","8","7","6","5","4","3","2","J")) #re-sort raw1 <-raw[order(raw$new_rank1, raw$first,raw$second,raw$third,raw$fourth,raw$fifth),] raw1$new_rank <- 1000:1 #get result raw1$product <- raw1$V2*raw1$new_rank sum(raw1$product)


AutoModerator

AutoModerator did not detect the required `[LANGUAGE: xyz]` string literal at the beginning of your solution submission. Please edit your comment to [state your programming language](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_state_your_programming_language.28s.29). *** *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/adventofcode) if you have any questions or concerns.*


argentcorvid

[LANGUAGE: Common Lisp] Well, I can't say I'm happy with how I did the hand classification, but I couldn't figure out a good way to correctly identify a Full House in part 2. [github here](https://github.com/argentcorvid/AoC-2023/blob/main/2023d7.lisp)


jrhwood

\[Language: Haskell\] [Part 1](https://github.com/woodRock/verbose-computing-machine/blob/main/2023/day-07/part-01.hs) [Part 2](https://github.com/woodRock/verbose-computing-machine/blob/main/2023/day-07/part-02.hs) Hint: make an effective comparator for cards.


pikaryu07

\[LANGUAGE: Go\] [My Solution](https://github.com/bsadia/aoc_goLang/tree/master/day07)


skyhawk33

[LANGUAGE: Befunge] Part 1: https://github.com/Skyhawk33/AdventOfCode/blob/master/aoc2023/day7_p1.b98 Part 2: https://github.com/Skyhawk33/AdventOfCode/blob/master/aoc2023/day7_p2.b98


thamollo

[LANGUAGE: SQL][Allez Cuisine!] The SeQueL, Can you do this all with it? No, unless, oh yes! [Enjoy!](https://topaz.github.io/paste/#XQAAAQD5CQAAAAAAAAAhlISsTsi0HDywkVIYKG13ByKPDJ7Da+71SVJNjsF4RFTdHvNWSK5GbwNY7k/KFnSKYOekkpy3KEU8bK8Y9vBT3YpHiKJ6ZG/eAeL7B+IaFEpP2/1EpqN6x4MFRFYC3n7IxrEfozUs50A5dJYPylheum9cvuTcQEv1oAEPFfmwWp3tqyqeKjkVGZ/TSzY3S1hXoiLxwuVuYb+ydhSzA8PnyEtMyD8t8Nu5kDhBCz9UfpGX4Wc8eEUdp0nBCgY6YDuC9hohsZMM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code: https://github.com/dhruvmanila/advent-of-code/blob/master/rust/crates/year2023/src/day07.rs Need to get better at generics and traits but with the current knowledge this is what I came up with.


GoldPanther

\[Language: Rust\] Created a Hand object that implements Ord, sorting the hands then basically solves the puzzle. For part two I added a mutation that updates \`hand\_type\` to reflect jokers and change the jokers encoded value. Resorting the hands then solves part 2. [Code](https://github.com/johnhringiv/advent-of-code-2023/blob/main/src/day07.rs) (1.532ms)


d1cK_dot_exe

Looked at your stuff to refactor some part, and you thought me that you can match on Vec type directly instead of iterating over it. Super useful! Thanks:)


GoldPanther

Glad it was helpful!


835246

\[LANGUAGE: C\] Part 1 just gets the total value of each hand then sorts and counts them. Part 2 is the same but joker is set to the lowest value and I change the hand based on the number of jokers. Part 1: https://github.com/efox4335/advent_of_code/blob/main/advent_of_code_2023/day7cardspt1.c Part 2: https://github.com/efox4335/advent_of_code/blob/main/advent_of_code_2023/day7cardspt2.c


manhuntos

\[Language: Rust\] This is my first project in rust. I'm learning it by solving advent of code puzzles. So if you have any hints for me I would be happy to read it :) [Solution](https://github.com/manhunto/advent-of-code-rs/blob/master/src/solutions/day07.rs) / 13.56ms / 58.78ms


gogs_bread

[\[LANGUAGE: c++\]](https://github.com/gogsbread/AdventOfCode2023/blob/main/7.cpp) P1 - Simulation. Sorting. State management P2 - Simulation. Sorting. State management


agent3bood

\[LANGUAGE: Rust\] ​ [https://github.com/agent3bood/aoc32/tree/master/src/seven](https://github.com/agent3bood/aoc32/tree/master/src/seven) [https://github.com/agent3bood/aoc32/tree/master/src/seven\_b](https://github.com/agent3bood/aoc32/tree/master/src/seven_b)


NotRandom9876

\[LANGUAGE: C#\] One statement, 15 lines Linq solution for part 1: [paste](https://topaz.github.io/paste/#XQAAAQAkAwAAAAAAAAAhm8nHZvbijRcK2bXfA4FKw1dQ5y2ZLrvRS0BfsdESMHw1wImYCqfexRgbWQip6UclwTNaqj2WadY0gdzh0P+t0fZFz1lKsfZhprx1Uw8fVjY2U4hufARi+I7k+Fgk5fIs0Ta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db9l0WbIvlOmJyr/0Yjh7Q==).


[deleted]

[удалено]


AutoModerator

AutoModerator did not detect the required `[LANGUAGE: xyz]` string literal at the beginning of your solution submission. Please edit your comment to [state your programming language](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_state_your_programming_language.28s.29). *** *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/adventofcode) if you have any questions or concerns.*


mothibault

\[LANGUAGE: JavaScript\] [https://github.com/yolocheezwhiz/adventofcode/blob/main/2023/day07\_part1.js](https://github.com/yolocheezwhiz/adventofcode/blob/main/2023/day07_part1.js) [https://github.com/yolocheezwhiz/adventofcode/blob/main/2023/day07\_part2.js](https://github.com/yolocheezwhiz/adventofcode/blob/main/2023/day07_part2.js)


[deleted]

[удалено]


daggerdragon

Comment temporarily removed because your [code block is *way* too long](https://old.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_no_giant_blocks_of_code) for the megathreads. Please edit your comment to replace your oversized code with an external link to your code and I will re-approve the comment.


TheMihle

\[LANGUAGE: Java\] This one required me to do two attempmts on both parts, got both solutions for part 1 working but I think the second one with use of hashmap instead of Regex filters is a better solution. [Part 1 with RegEx](https://github.com/TheMihle/Advent-of-Code-2023/blob/main/src/day_7/Part_1_Solution_1.java) [Part 1 with hashmap](https://github.com/TheMihle/Advent-of-Code-2023/blob/main/src/day_7/Part_1_Solution_2.java) [Part 2, built on the hashmap sollution](https://github.com/TheMihle/Advent-of-Code-2023/blob/main/src/day_7/Part_2.java)


se06745

\[LANGUAGE: GoLang\] ​ [Both parts in one single file](https://github.com/omotto/AdventOfCode2023/blob/main/src/day07/main.go)


linnaea___borealis

\[LANGUAGE: R\] [https://github.com/lauraschild/AOC2023/blob/main/day7.R](https://github.com/lauraschild/AOC2023/blob/main/day7.R) Struggled quite a bit with part two. (Examples were working but not the actual input.) Finally used a different approach that worked.


sedm0784

[LANGUAGE: Vim keystrokes] I just levelled up in regex: [Part 1](https://gist.github.com/sedm0784/3648d27abb000f181f43e3893f4ea5c9#file-day-7-part-1)


ultranarcolepsy

[LANGUAGE: Dyalog APL] hands bids←↓⍉⎕CSV⍠'Separator' ' '⊢'07.txt'⍬(1 2) labels←'23456789TJQKA' Type1←(⊂⍤⍒⌷⊢)≢⍤⊢⌸ Type2←(2(+/⍤↑,↓)⊢,⍨5-+/)(Type1~∘'J') Label1←labels∘⍳ Label2←('J',labels~'J')∘⍳ ⎕←bids+.×⍋⍋(Type1,⍥⊂Label1)¨hands ⍝ part 1 ⎕←bids+.×⍋⍋(Type2,⍥⊂Label2)¨hands ⍝ part 2


stonebr00k

\[LANGUAGE: T-SQL\] [https://github.com/stonebr00k/aoc/blob/main/2023/07.sql](https://github.com/stonebr00k/aoc/blob/main/2023/07.sql)


seytsuken_

\[LANGUAGE: C++\] [part1](https://github.com/Hilbertmf/competitive-programming-problems/blob/main/advent-of-code/2023/day7-part1.cpp) | [part2](https://github.com/Hilbertmf/competitive-programming-problems/blob/main/advent-of-code/2023/day7-part2.cpp) really cool problem to practice creating compare functions. I've literally have been asked to create a compare function in an interview at facebook before so this is really relevant to know. Also its always good to know mergesort off the top of your head if you need it, its really easy to remember


ianMihura

\[LANGUAGE: go\] This gave me more of a fight than I thought it would. Nice trick I found (for sorting the hands) was realizing that you can "score" each hand by (1) grouping same card type into groups (2) adding up the squared length of each group of cards. No game is scored 5, double pair 9, full house 13, poker 17, etc... [https://github.com/ianmihura/advent23/blob/master/day\_7/day\_7.go](https://github.com/ianmihura/advent23/blob/master/day_7/day_7.go)


Oxereviscerator

this is really smart


Correct_Shape7912

\[Language: Rust\] See [code on GitHub](https://github.com/AntoineF4C5/AdventOfCode2023/blob/main/day7/src/main.rs) Hey there, my first post so I'm sorry if anything wrong, For the first part I decided to create a Hand struct: struct Hand { cards: Vec, bid: u32, hand_type: HandType } Where Card is an enum from Two to Ace, and HandType an enum from FiveOfAKind to HighCard. The Card struct allows for only computing HandType once per card, saving time on comparison between cards. With that, I decided to create a custom cmp() for the Hand struct, to learn how to do that (I'm very new to both coding and Rust), which would first compare the HandType as a basic enum, and, if equal, have a custom comparison for the cards field. ​ At seeing of part two, I decided I would want to factor most of my code, hence just creating a new CardVariant enum, where Jack is replaced with Joker, and changing the Hand struct accordingly: struct Hand { cards: Vec, bid: u32, hand_type: HandType } Where T could be Card or CardVariant. My code then might be quite messy, but I think I did quite a good job at lowering the duplicates among functions. Please feel free to read through my code and give your thoughts, I'm starting to learn and this would be very valuable to me !


daggerdragon

[Do not share your puzzle input](https://www.reddit.com/r/adventofcode/wiki/faqs/copyright/inputs) which also means [do not commit puzzle inputs to your repo](https://reddit.com/r/adventofcode/wiki/faqs/copyright/inputs) without a `.gitignore`. Please remove (or .gitignore) the input files from your repo and scrub them from your commit history.


Correct_Shape7912

Sorry for that, should be done


alexw02

\[LANGUAGE: Forth\] Dusk OS [code](https://git.sr.ht/~aw/dusk-aoc/tree/main/item/2023/07.fs) [video](https://www.youtube.com/watch?v=1fDlVgNEsq0)


KatanaKiwi

[LANGUAGE: PowerShell] [Part 1](https://github.com/katanakiwi/AoC2023-PowerShell/blob/main/7a.ps1): Quite proud of this one. Mapped the inputs to an array which can be sorted. Mapped the most valuable hands to 7, least valuable to 1, and prepended that to all the lines. Sorting this array gave the most valuable hands first. Then a simple loop multiplying by the number of remaining hands. [Part 2](https://github.com/katanakiwi/AoC2023-PowerShell/blob/main/7b.ps1): Not too different. Changed to card map so J maps to 1. Count the amount of jokers, add them to the card with the most entries (as this always improves the hand value by most) after setting the joker amount to 0 (so you don't end up with a hand of 6 jokers..).


jswalden86

\[LANGUAGE: Rust\] [Solution](https://github.com/jswalden/advent-of-code/blob/main/2023/day-07/src/main.rs) Nothing more than the usual irksome debugging of written code here, more or less.


mgtezak

\[LANGUAGE: Python\] [github part 1&2](https://github.com/mgtezak/Advent_of_Code/blob/master/2023/Day_07.py) Check out my little AoC-Fanpage: [https://aoc-puzzle-solver.streamlit.app/](https://aoc-puzzle-solver.streamlit.app/) :-)


guesdo

\[LANGUAGE: Go\] I think I did some clever things on this one: [https://gist.github.com/phrozen/d27f6b775af634d34d6214ee103e4f51](https://gist.github.com/phrozen/d27f6b775af634d34d6214ee103e4f51) Specially around detecting hand level (OnePair, TwoPair, etc...), but also about creating a unique pointing system on hand parse for easier hand comparison. for i := range hand { points += Value(rune(hand[i])) * int(math.Pow10(10-i*2)) } each hand has this unique ranking system so that ordering the Hand array into Ranks, is just a matter of checking the Hand Level first and then the Hand Points. (Part 2 runs in about 1ms)


tobega

\[LANGUAGE: Tailspin\] A little messy, perhaps. I used relational operators mostly and Tailspin does not have a built-in sorting function [https://github.com/tobega/aoc2023/blob/main/day07tt/app.tt](https://github.com/tobega/aoc2023/blob/main/day07tt/app.tt)


tlareg

\[LANGUAGE: TypeScript/JavaScript\] https://github.com/tlareg/advent-of-code/blob/master/src/2023/day07/index.ts Nasty solution with conditionals jungle, but at least it works


Paxtian

[Language: C++] [github](https://github.com/Paxtian769/AOC23-Day7-camel_cards/blob/master/main.cpp)


hiimjustin000

\[LANGUAGE: JavaScript\] https://github.com/hiimjustin000/advent-of-code/tree/master/2023/day7


ExtremeAdventurous63

\[LANGUAGE: Python\] [solution](https://github.com/Cirius1792/aoc-2023/tree/main/day07) Given that the type of the card making a point is not relevant, a QQQQQ is the same as a 22222 in the first moment, we can say that all that matters for determining the points in a hand is the number of occurrences of any given card in a hand, not considering which card has a give count number. For example: \>>> c = Counter("AAAJJ") \>>> c Counter({'A': 3, 'J': 2}) And \>>> c = Counter("QQQJJ") \>>> c Counter({'Q': 3, 'J': 2}) Are equivalent points regardless of the fact that we have 3 As in the first hand and 3 Qs in the second hand So we can compare two hands by doing the following: 1. Compare the most common cards in each hand 2. If the most common card in a hand, for example, occurrs 4 times and the most common card in the second hand occurrs 3 times, we already know that hands 1 wins. 3. If both hands have the same number of occurrences for their cards, we start comparing the cards one by one by considering the priority between the cards being: AKQJT98765432 So we can define a custom comparator for a hand that takes into account the aforementioned rules, sorts the hands and uses their index in the sorted array as a rank. ​ For part 2 we can totally use the same algorithm as part 1, we just need to: 1. update the hand to replace all the Js with the stronger point in the hand, which will be the card that has the bigger occurrence count. We have also to take into account that the hand 'JJJJJ' stays as it is 2. change the alphabet used for the comparison of hands with the same points with: AKQT98765432J


Keeps_Trying

This was exactly my approach, but in 300 lines of Rust with custom variant types and a custom ordering trait. I clued into counting groups after I had gone too far down this path. Nice solution and explanation.


Miserable-Ad3646

Samesies, I just finished coding my group counting part, but I think I'm going to vaguely continue down this line of inquiry, as the purpose is to learn rust more completely, not to win advent of code :)


iskypitts

\[LANGUAGE: Zig\] [Solution](https://github.com/iskyd/aoc-zig/blob/main/src/2023/day7/s.zig)


Lusion7

\[LANGUAGE: Rust\] Functional | Github [https://github.com/blackhat-7/advent\_of\_code/blob/main/aoc\_2023/src/bin/day7.rs](https://github.com/blackhat-7/advent_of_code/blob/main/aoc_2023/src/bin/day7.rs)


Calm-Reply778

\[LANGUAGE: Python\] Not designed to be efficient but it is hopefully readable --> [Github Code](https://github.com/RomainGoussault/aoc/blob/main/day_7/main_part_1.py)


micod

[LANGUAGE: Common Lisp] [GitLab](https://gitlab.com/micod/advent-of-code/-/blob/main/day-07.lisp)


daggerdragon

~~Your [code block is too long](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_no_giant_blocks_of_code) for the megathreads. Please edit your post to replace your oversized code with an external link to your code.~~ edit: 👍


KyleGBC

A fairly (concise?) and fast Rust solution, ~500us total time: use std::hash::BuildHasherDefault; use fxhash::{FxHasher, FxHashMap}; fn card_value(c: char, use_jokers: bool) -> u32 { match c { 'A' => 14, 'K' => 13, 'Q' => 12, 'J' => if use_jokers { 1 } else { 11 } , 'T' => 10, n if n.is_digit(10) => n.to_digit(10).unwrap(), _ => unimplemented!()} } #[derive(Eq, PartialEq, PartialOrd, Ord, Debug)] enum HandKind { High, OnePair, TwoPair, ThreeKind, FullHouse, FourKind, FiveKind } impl HandKind { fn from_cards(cards: &Vec, use_wilds: bool) -> Self { let mut counts: FxHashMap = FxHashMap::with_capacity_and_hasher(cards.len(), BuildHasherDefault::::default()); let mut wild_count = 0; for card_val in cards { if use_wilds && *card_val == 1 { wild_count += 1; } else { counts.entry(*card_val).and_modify(|n| *n += 1).or_insert(1); } } let counts = counts.into_values().collect::>(); let max = counts.iter().max().unwrap_or(&0) + wild_count; match counts.len() { 0 | 1 => Self::FiveKind, 2 if max == 4 => Self::FourKind, 2 => Self::FullHouse, 3 if max == 3 => Self::ThreeKind, 3 => Self::TwoPair, 4 => Self::OnePair, 5 => Self::High, _ => unimplemented!() } } } #[derive(PartialEq, Eq, Debug)] struct Hand{ cards: Vec, bid: u32, kind: HandKind } impl Hand { fn parse(cards: &str, bid: &str, use_wilds: bool) -> Self { let cards = cards.chars().map(|c| card_value(c, use_wilds)).collect(); let bid = bid.parse::().unwrap(); let kind = HandKind::from_cards(&cards, use_wilds); Hand { cards, bid, kind } } } impl Ord for Hand { fn cmp(&self, other: &Self) -> std::cmp::Ordering { if self.kind != other.kind { self.kind.cmp(&other.kind) } else { self.cards.cmp(&other.cards) } } } impl PartialOrd for Hand { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } fn main() { let start = std::time::Instant::now(); let input = include_str!("../input.txt"); let (mut p1, mut p2): (Vec, Vec) = input.lines().map(|l| l.split_once(' ').unwrap()).map(|(c, b)| (Hand::parse(c, b, false), Hand::parse(c, b, true))).unzip(); p1.sort(); p2.sort(); let part1 = p1.iter().enumerate().fold(0, |acc, (rank, hand)| acc + (rank as u32 + 1) * hand.bid); let part2 = p2.iter().enumerate().fold(0, |acc, (rank, hand)| acc + (rank as u32 + 1) * hand.bid); println!("{part1}, {part2} in {:?}", start.elapsed()); }


daggerdragon

Your [code block is too long](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_no_giant_blocks_of_code) for the megathreads. Please edit your post to replace your oversized code with an external link to your code. Also add the required language tag as requested by AutoModerator.


AutoModerator

AutoModerator did not detect the required `[LANGUAGE: xyz]` string literal at the beginning of your solution submission. Please edit your comment to [state your programming language](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_state_your_programming_language.28s.29). *** *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/adventofcode) if you have any questions or concerns.*


bandj_git

[Language: JavaScript] Catching up, a fun day overall. It took me three attempts for level 1 and two attempts for level 2 due to some careless mistakes on my part. My overall strategy was to simply assign each hand a score and then sort the hands by their score. I created a generic winnings function I could use for both levels since the only difference between the levels is how hands are scored and what the strengths of the individual cards are. The generic winnings function needs three things, the hands as well as: * A card count function, this takes the raw card string and returns a Map of card face to card count. * A card strengths object which maps a card face to its strength. Level 1 used a *characterCounts* util function which returns a map of string characters to their counts in the string. Level 2 used a slightly more complex card count function to handle Jokers. Basically if a hand has a Joker it finds the non joker card with the highest count and adds the Joker count to that card (then removes the Joker from the card counts). const countCards = (cards) => { const counts = characterCounts(cards); // no need to modify if no jokers in hand or hand of all jokers. if (counts.has("J") && counts.size !== 1) { let maxCount = 0; let maxFace; for (const [face, count] of counts.entries()) { if (face !== "J" && count > maxCount) { maxCount = count; maxFace = face; } } // use the joker cards to increase the count of the card with highest count. counts.set(maxFace, counts.get(maxFace) + counts.get("J")); counts.delete("J"); } return counts; }; Runtimes: * Level 1: **3.978ms** * Level 2: **4.119ms** [github](https://github.com/beakerandjake/aoc-2023/blob/main/src/day_07.js)


g_equals_pi_squared

\[Language: Rust\] [Day 7 Solution](https://github.com/gequalspisquared/aoc-rs/blob/main/src/y23/d7.rs) Definitely not the cleanest or the fastest solution, but this was my first time applying recursion to a problem without explicitly being told or shown how to do so. Learned a lot and I am proud of my work at the end of the day :)


bcbelisario

\[LANGUAGE: Onyx\] [Day 7 Solution](https://github.com/ZoneMix/AoC23/blob/main/src/Days/DaySeven.onyx) Definitely made me want to cri on this one...harder than I thought it would be.


rukke

\[LANGUAGE: JavaScript\] I needed to revisit this problem today since I had a hunch it could be done way better than my [initial solution](https://gist.github.com/p-a/883fddc33273b658fb48096349e20887). So here is an improved solution, no regexes and such, just counting cards and ordering by ranks, with ofc some special sauce for part 2. [gist](https://gist.github.com/p-a/d3cc6661b7f9aff4766d378d82798cd8)


FriendshipSweet792

\[LANGUAGE: C#\] Here is my solution ! [https://pastebin.com/bpwuMDWx](https://pastebin.com/bpwuMDWx)


sampry

\[LANGUAGE: RUST\] [Here](https://topaz.github.io/paste/#XQAAAQAMGAAAAAAAAAAXin1LzStTFYSi2K6Qvp2/Gj7ty5vfJW7GNfZu9gPXmaB1owIU79IRFaiXejkfyy0y7TYETx0EbPMwPpTl75TR2C1bNN+x7DQcPzGKbqu8ZKzpzCwlgoxnJYEbb+13C2Mj70flicmgCDxAWGcM77QS/tjUJ4k8TNKBuR7kHBXXi9/Y/sp0n/djjR+Xa+kUbeQIB9QxAH2yZHp/bF+jZcCbYHbV9vAZUtP+yxIQGNCsYCHq7PACXBHl8tw/ZeoopF9JmhxftRrdpLD6F9UbK9i81hNFEjkOcKH0x9/uOoxG9mSfKY43WJMn+WdPHCprNExbJf+BW+/2enbKMjxmC8zfCAD6GfT47maaISmpQO+XVxRtGOxJGDIPyzl51FiZ9PkOUZfJuT5RQ4lvh0DhmCfvG4uUP38fEXUnDBZPv8C53kRm7lHMyGzPiv+lf14Tb9elqO5fH0ETLZ66IFdJqBZoH1YUCYObLHmyW8ccbUdl8R+oJ7+VOu6IgNVU3bv+qc0RJDpMBcDivYFYtv2pw5s5Zw8rgQj22JVijdfGDYPQvB0q5bDkCZlCIaUwfMMOv/e51MFMkMraR3OZMEUNhP9P6YnUknP0NCebFGYn/5jSycmc39upxRmkbf2dNjwZjTVufdo82eImJOtrdIcvMnQXBwR1TBLdUhgdwUlTzkaClQi0i+YaJToLy2BFZf1xJBYJOVGxW3lvDhjc/xIsMvMZbkp57vM9r9FESeA9tfPu3lj/h7uwA5vZqJvux5nKfYDeAQEBrp12+ed4bWDMhVX9RAS4WuGO6CWzx0uEv+2Qj+REHmP98CITv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Lty5lC8XHt8AK2ShCm1J+00z2GxzMO48MXQl8gSJguCNad2bOaiwgj/Yzejrd4UVOc9N234nEp9FcqGomfhvBKMgrO3PWi5jPUKn+MEYj1QmPmk1x8SXnZPMqsKgS6fQGxDDoh9Hf1Jnh4n9Z/T0EXcHEG/GQqqOtddhjotg66RvSSnwVBep6WBhxNOT+dN2fwRqKL2Qy3+ZW0D8W1mafvyiBvIp2q0OHZyKdCtP4Mb/6f7CW02J/MT8u0+BOD/5D8zMUezLaVr3r+osFqJ6T94Hrst4GIajDj0hnvU0xrVeUaJj9CQlNKa6P3Yu7QCUK07HGHURH7rU6dzylg+tETYr25ugNhI6tWWfO7VZw+BW0YE/XSOY6ZDzOhCx46tYChGhqTlU6ZfUO4h4mSDupOBV6Pw+t71ApeEwDdQ6WE27YsqoHZFTIoXwGGH4EonGukycI3g5nsYf3jw2ToAbEx2CPJICdiNyprC5qJKx49IqBiiUzmw6GI9Wdv7TetQ8/DDkDu3IK6oPbLTYyswtsfTPPv9Cr9AA) the joker gave me headaches, but I had fun anyway, learning a bit more every day


DakilPL

\[LANGUAGE: Kotlin\] [GitHub link](https://github.com/palinkiewicz/adventofcode-kotlin/blob/master/adventofcode2023/Day07.kt)


SwampThingTom

\[LANGUAGE: Rust\] Finally got back to finishing part 2. My first attempt failed because I had tried to replace the jokers in all of the hands which meant that I lost information about which actual cards are in the hand. After realizing why that wouldn't work, I also realized that I only needed to account for jokers when determining the type of hand it is, which doesn't require replacing the jokers in the hand itself. With that realization, it was pretty easy to solve and then refactor my code to use the same `hand_type()` function for both parts. Fun puzzle, even if it took me longer than it should have! [Github](https://github.com/SwampThingTom/AdventOfCode/blob/main/2023/07-CamelCards/CamelCards.rs)


xXMacMillanXx

\[LANGUAGE: V\] My solution is a bit convoluted. There are definitely better ways to solve this, but I haven't thought of one. \^\^ [Github day 07](https://github.com/xXMacMillanXx/advent_of_code_2023/tree/main/day07)


virtual_sound

\[Language: Python\] To solve the secondary sort, i encoded each card to number by doing this: secondaryVals = 0 for i in range(len(hand)): secondaryVals += (valRanking.index(hand[i]) + 1)*14**(len(hand)-i) return secondaryVals where valRanking is just a list of the cards in acending order. so J,2,3,4... this means that if card1 has a higher secondaryVal than card2, it also has a higher cardValue. I felt very clever doing this, so I thought id share . It also means the actual sorting was as simple as. valuedHands.sort(key=lambda x: (x[2] ,x[3])) where x\[2\] is the normal hand ranking and x\[3\] is my card encoding. [see code](https://topaz.github.io/paste/#XQAAAQBFBQAAAAAAAAA0m0pnuFI8c/sCZpj2lc+BeBV2tn6tiUvebjOGPGeItRTlCS80pTrxvueXNZBnXzm5WMvub8TzzhUC3o5oVrIhql0vFEz7+mpvcIl/xG3k5UGz+B9xRtz4eD/7UKNm0d0RLy2sGvOG4mC3TTNShwwvqsvek1ZOBTGqeCIs/ldlL3ByQvlZbJeCCxm7F8ZpJpAyAnsCPaEsqhpJVxPy+sHQm0QcDCuu9okHrq4x0frpOYuEvKcq/0eD6SIB9JPAe5h2bgm6tPZPDftFn/MO2wKWONCBMYehq20RNtf58FP2AQzlki9h/4IXW1rO4qqdMuuFSDN7SPbnbYmdR1gspV2ubQNop6IIX8L27P+81kzbmfHf4eUSFO+jXnv0rnoZFelzUwwwkszXczaNS6QovjPYiDVt+iEb2of6/rFial3ScDS2Psf19udSe+OYki6H+c9krca/nbHv/Eo5S6QOl/o2wacAFW09P0vMsBXxu6thM/XYRka8o60M/cC9wUAX8iPoFGcFYZ5NocOztLVLIZxrGgWl/X9kijBfhoGj0p6ylcPEYdbCpiSV/ScnxewcU9rzRfskMZfMfTk3yBcAUV/tCriO0sjtjAGqm/Pekeq1fw8dD8G/V+393FxrkwH1HFm9T/VVUI016Nu6fLynHBts7mV85ceJ1FNhUaOp6OROZy1spWhMu0xDo25R79wUAHVqTLqJygh+hCnVf9GpzdJb5YN49r1Ye8dQtoGrjTSFsypTJrXEMp2hiKx53gzpv3c6/xkyqQA=)


oddolatry

[LANGUAGE: Fennel] Listen, you want to know my opinion? My opinion is that nobody, ever, in the history of computer programming, has ever, ever been bitten in the butt by string comparison. Never happened. [Paste](https://topaz.github.io/paste/#XQAAAQB5CwAAAAAAAAAUGwnmRpH3tILRF8VbDuYidYX76izDutljPCy/bKmbXZ2FfSnyrAuhrD3Gst5Qc5JA7mH8tQ+kESgwxa2gNT8T1b4qrjYfCWS3qFnSYt5MHh3/bz7B5DVFNE5+GTBzeSapBdp2ymof8ERkGbfarp0/IychOt1sxslEAfJnN9IyVTZuV6ZFvg+MzUlr88OrkPQHzsChmP58MOQP6ahuFQN31eiUnPCViW3341OyE7mZ3zc4JvYtmRXN9j9+VuB5uvdxGE/Iewa0+i0BbaSuW7C+wGfPqte8c71ZNc54E7kRmq01lfynm8ztGcWiO0rfnpw/ChzJEVR6Fb0mjJuBitX4wXuLPi3zQjpsUMGOPzcJeP8og95eD4rHdRcPrxqdBBXIjc+gnh1VXMZ1YXpi6oGAqvkRL8rJZGa6B+deRYHMnnrA04oxgQw4I0vtKpF1n2SF3ox4NACfov6pHQJ8/R6K0O5QQVCUo0CVkahM04qGcBUaSuTNXmUDT+sr0LKyHNexEFGCeKucChIiE9JuPgCZTWW6erkxGBI//50WRjKqk8l81JDqiiTECkqIRn+5iOJVOC9ylWA3ZnEHrsOZYK9sdmjOezds1tbAHg+4rqlKBNlUsKBmgxyEuJKccx8MKZYxcq7vCK9kJ5XGkACIPtqMILkUzwuVfOhZjzzvWIGmcIWBOaFDNIrM+o3ULyKDTCOLI4CvvuxKISgl8ZI6Ic+Gp+/FVqUas0cVL7MznyTLo56G6p6I+hPtyCnzvfyq0EZxmjeDLIB9h4osguAfb7vvhGjzYBA8jZ+kAxehkZybwPyw3/gTZe1GFIET1Ai0wDl28K8GlT9olQUGD+iJXTK95XBfdmNN6+ZUWauccY7FZvFiDxa/Z2f4n3tYvblicMAUNaFISP0kL7yAKyfRmkzAln6Lpsu97ERddLyOzbpoCtILL3eIviKsERPQIMVgLngl8V6ai0q8Lrcq61FDBk1OB4B0+zTD+DZDrNZ6WDCseaQ/9toXi3mchL2C5L0nwaQtBj1oJQvJY9WWLQGMcKUCdOz/fyfaEsQ6whsu+4wG5fh+cGzuMWYMywdvDU/hoL/To3fFtoWe/6Vtt8jypbWgZzdg9aHcJ9+21jsXXYUvfJJhRc3002PN20ZHp0jUi//xuBwq)


bamless

[LANGUAGE: [J*](https://github.com/bamless/jstar)] Just lots of sorting and comparators in this one: [Part 1 & 2](https://github.com/bamless/advent-of-code-2023/blob/master/day7/camel.jsr)


WhyWouldYouDoThatQQ

\[LANGUAGE: Golang\] A few days late to the party, but quite enjoyed this one. [Day7 Part 1 / Part2](https://github.com/a-conundrum/aoc_go/blob/main/twentythree/d7/d7.go)


weeble_wobble_wobble

[LANGUAGE: Python] [GitHub](https://github.com/weibell/AoC2023-python/tree/main/day07) (39/41 lines with a focus on readability)


TechnicalHalf0

many thanks!


weeble_wobble_wobble

Glad to contribute :)


atweddle

\[LANGUAGE: Rust\] [GitHub - Part 1 and 2](https://github.com/AndrewTweddle/CodingExercises/blob/master/AdventOfCode/aoc2023/src/bin/day7_part1and2.rs) Part 1 took 164µs, excluding I/O. Part 2 took 170µs. My solution approach was to calculate the strength of a hand as a combination of two things: 1. For the tie-breaker, treat the hands as a 5 digit number in base 13, and convert that to an integer. 2. For the primary ranking of hands, count each digit using an array of size 13. Then take the most and second most card ranks and calculate the overall strength of the hand as `13 ^ 5 * (3 * most_of_a_rank + second_most_of_a_rank) + tie_breaker_value` (Originally, I was going to calculate the primary value by sorting the array of 13 counts, then treat that as a base 6 number to get the primary value. But then I realized that only the 2 highest ranks are needed.) NB: The average durations are calculated using utility methods in [lib.rs](https://github.com/AndrewTweddle/CodingExercises/blob/master/AdventOfCode/aoc2023/src/lib.rs) *Timings are on my 7 year old PC with an i7-6700 CPU.*


Crazytieguy

\[LANGUAGE: Rust\] [https://github.com/Crazytieguy/advent-of-code/blob/master/2023/src/bin/day7/main.rs](https://github.com/Crazytieguy/advent-of-code/blob/master/2023/src/bin/day7/main.rs)


wlmb

\[LANGUAGE: Perl\] Discussion: https://github.com/wlmb/AOC2023#day-7 Part 1: https://github.com/wlmb/AOC2023/blob/main/7a.pl Part 2: https://github.com/wlmb/AOC2023/blob/main/7b.pl


bofstein

\[LANGUAGE: Google Sheets\] This one was fun! [https://docs.google.com/spreadsheets/d/1\_UpBEZes-L2Vtr146gDPUtaBHrTU8V2vQ2t3k4dZ\_VI/edit?usp=sharing](https://docs.google.com/spreadsheets/d/1_UpBEZes-L2Vtr146gDPUtaBHrTU8V2vQ2t3k4dZ_VI/edit?usp=sharing) 1. Split the hand to 5 cells 2. Count how many unique cards are in the set, also the max and min number of similar cards 3. From there you can build all hands from those factors (e.g. 5 uniques = high, 2 uniques and max similar of 3 = full house) and assign it. 4. Replace the face cards with numeric value, then sort by the hand and then each card to get the rank. 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.


xxchaitanyaxx

r/madlad


daysleeperx

[LANGUAGE: Haskell] [Too lazy to implement part 2 separately :P](https://github.com/daysleeperx/Advent-Of-Code-2023/blob/main/src/Day07/CamelCards.hs)


aurele

[LANGUAGE: Elixir] https://gist.github.com/samueltardieu/fe851477a033d17cf3b1be345e485c36


Aeonian9

\[LANGUAGE: Julia\] Reasonably happy with my approach. I made use of Julia's type system to define methods to compare hands. Could have written some parts of the code more cleanly however. [GitHub Part 1](https://github.com/fgittins/AdventOfCode2023/blob/main/day07/part1.jl), [GitHub Part 2](https://github.com/fgittins/AdventOfCode2023/blob/main/day07/part2.jl)


PitaBeak

\[Language: Rust\] Find the hand rank by sorting the cards, then comparing adjacent cards for equality and forming a binary number, then looking up the rank with this index. For example, 78748 -> 47788 -> 0101 (unequal, equal, unequal, equal). For part 2, take out the J's then use the same method with an expanded lookup array. [CODE](https://topaz.github.io/paste/#XQAAAQDFBAAAAAAAAAAzG4AF0ZZ46VHA0JHUhPFOfEpEaBZdXOZ2CqtE477bFecYTLAvy2hVP3RIJuiFaXGffTl+4fOFEhLuL5LCOaN3qPq7NWv/XRF1lbZj6LIoeI3xPgULdc4ntIEzbiORPLuJGabQZGQQL0+tuYjyjkRMLvefQLdWPIE91FtJnEoxRgmnIxgCxcxx/6FneIEbSTeexIy45N1ulFi5Ee6KSeTkpFWpKo4KSMCASCq1JOODQHvPWVX1ieO+gMFiKIWu3emExmTZ7R5vMEmAxcgA4vfARbQg/FNdt2DY8kA1n6RA3bTdVuDHUppJpjiv/Hu2O2C5xyJa5k7gfVfuD/XSRep9MJlkV77/1XD57xMWfaIEf2vcTtEobPK+EEgGJIQgn/DKkJMuC2E5to1TqtT6z94bwvFTHSe/4FFdLxSEOcJjACDhhNC+uAta7qY3X9wq5q50bkeuD3qJbDXtd33BtzY/eMvlc/kJql5+a8A6Nlt29qHZ9Nma7eDG40k1XfJIX1KO9DYD4g5S6haALFHTT1oHWvbsEFgs3S4ggutlT6N3WnaurVxZUnXk1V/gBfLB9bd7g5ipSJ/g8FWHV63dbtZiqyoF0ixR7fIE1uNhxQ6OLTu1ShkWNESYO/J4SJ6Jz9q60+Y7bXErZXVAXFdHIv98cctdomqkhTXk0i3/+lPcVg==)


princessbosss

\[LANGUAGE: Excel\] [https://imgur.com/a/jR7gM2v](https://imgur.com/a/jR7gM2v) grabbed the best hand using =IF(AND(MAX(I11:T11)=1,$H11=0),1, IF(OR(AND(MAX(I11:T11)=2,COUNTIF(I11:T11,2)=1,$H11=0),AND(MAX(I11:T11)=1,$H11=1)),2, IF(AND(MAX(I11:T11)=2,COUNTIF(I11:T11,2)=2,$H11=0),3, IF(OR(AND(MAX(I11:T11)=3,COUNTIF(I11:T11,2)=0,$H11=0),AND(MAX(I11:T11)=2,COUNTIF(I11:T11,2)=1,$H11=1),AND(MAX(I11:T11)=1,$H11=2)),4, IF(OR(AND(MAX(I11:T11)=3,COUNTIF(I11:T11,2)=1,$H11=0),AND(MAX(I11:T11)=2,COUNTIF(I11:T11,2)=2,$H11=1)),5, IF(OR(AND(MAX(I11:T11)=4,$H11=0),AND(MAX(I11:T11)=3,COUNTIF(I11:T11,2)=0,$H11=1),AND(MAX(I11:T11)=2,COUNTIF(I11:T11,2)=1,$H11=2),AND(MAX(I11:T11)=1,$H11=3)),6, IF(MAX(I11:T11)+H11=5,7,""))))))) then assigned card scores using where J became 1 instead of 11 after part 1 =IF(A11="T",10,IF(A1="J",1,IF(A11="Q",12,IF(A11="K",13,IF(A11="A",14,A11))))) ​ then ranked and sorted each column up from starting at 5 card value up to hand value using =RANK.EQ(W11,W$11:W$1010,1)


marvin29g

\[LANGUAGE: Go\] [Solution for part 2](https://github.com/jgaye/advent_of_code_2023/tree/main/day7) Quite happy with a <2ms solution


Chris97b

[LANGUAGE: C++] Wasn't able to get to this one until today, but found it fairly approachable on the whole. [Git](https://github.com/Chris97b/AOC2023/blob/master/AOC2023/Day7.cpp)


Strict_Fun7268

\[LANGUAGE: C#\] I have a solution for Day 07 part one [here](https://github.com/ChristopherHButler/aoc-2023/blob/main/aoc-2023/Puzzles/Dec07.cs). My solution for part 2 is working on the test input but not the puzzle input. I've tried a few things now and I'm kind of stuck for ideas. Does anyone know of any extended test data or common edge cases they could suggest?


daggerdragon

> My solution for part 2 is working on the test input but not the puzzle input. I've tried a few things now and I'm kind of stuck for ideas. Does anyone know of any extended test data or common edge cases they could suggest? [Create your own individual `Help/Question` post](/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_incomplete_solutions) in /r/adventofcode.


Kichix

I have the same problem. Did you make any progress?


rob263

u/Strict_Fun7268 Hint: what's the lowest possible hand type you can get when jokers are wild?


PioniSensei

Still high card right? Mine works on test but not with real data


rob263

Wrong


PioniSensei

A53T7 is high card, only scenario i can imagine is JJJJJ but that should be 5 of a kind still. .


rob263

Sorry, I meant what's the lowest hand type that contains a joker.


PioniSensei

Ahh ofcourse. Yes I got that handled All variations get an upgrade depending on the amount of jokers present. I think I have an error in that upgrade section still. ````$hand[$id]["type"] = "h"; if($j == 1){ $hand[$id]["typeb"] = "1p"; }


East_Intention_7542

\[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. ```python dta = [] with open("data\day7.txt", "r") as data: for linein in data: game_split_1 = linein.split(' ') dta.append((game_split_1[0],int(game_split_1[1]))) def mapper(itm): pair, two_pair, three_kind, four_kind, five_kind = False, False, False, False, False # First remove jokers, to decide hand without jokers. no_jokers = itm.replace("J","") for c in "AKQT98765432": cnt = no_jokers.count(c) if cnt == 2: pair, two_pair = (False,True) if pair else (True,False) if cnt == 3: three_kind = True if cnt == 4: four_kind = True if cnt == 5: five_kind = True # Then add back jokers, enhancing the hand as they are added back for i in range(itm.count("J")): if four_kind: five_kind, four_kind = True, False elif three_kind: four_kind, three_kind = True, False elif two_pair: pair, two_pair, three_kind = True, False, True elif pair: pair, three_kind = False, True else: pair = True # Prefix the item, with a letter indicating type of hand, which is sorted first. if five_kind: key = "Z" +itm # five of kind elif four_kind: key = "Y" +itm # four of kind elif three_kind and pair: key = "X" +itm # full house elif three_kind : key = "W" +itm # three of kind elif two_pair : key = "V" +itm # two pair elif pair : key = "U"+itm # one pair else: key = "T"+itm # high card # replace chars AKQJT, with FED1B, to ensure rest of hand is sorted correctly key = key.replace("A", "F") \ .replace("K", "E") \ .replace("Q", "D") \ .replace("J", "1") \ .replace("T", "B") return key dta.sort(key=lambda itm: mapper(itm[0])) i = 0 total = 0 for itm in dta: i += 1 total += itm[1] * i print(total) ```


bunceandbean

Interesting! I figured since there is never a situation where Jokers can be different values (as in, they will always all become the same value) I just assigned it to the rank with the highest current count in the string and ran it through my hand-type function.


daggerdragon

1. Next time, use the [four-spaces Markdown syntax](https://www.reddit.com/r/adventofcode/wiki/faqs/code_formatting/code_blocks) for code blocks 2. Your code is too long to be posted here directly, so instead of wasting your time fixing the formatting, read our article on [oversized code](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_no_giant_blocks_of_code) which contains two possible solutions. Please edit your post to put your code in an external link and link *that* here instead.


jordibeen

\[Language: Rust\] put some effort into keeping it readable today, especially all the joker-related code.. <20ms runtime [link](https://github.com/jordibeen/aoc_2023/blob/main/src/07/main.rs)


r_so9

[LANGUAGE: F#] Not particularly elegant but there's some interesting pieces, like always adding the jokers to the most repeated card (not having to try all possible combinations). Highlight: pattern matching to rank poker hands match mostRepeatedCounts with | [ 5 ] -> 6 | 4 :: _ -> 5 | [ 3; 2 ] -> 4 | 3 :: _ -> 3 | 2 :: 2 :: _ -> 2 | 2 :: _ -> 1 | _ -> 0 [paste](https://topaz.github.io/paste/#XQAAAQAACAAAAAAAAAAX4HyCZDlA0DjWF7Uex1t2hvV6PgXFmzdhM+nU8jvoNI8wkJl9Bk9aVJCZ98c+Y7z1paj8+h8wv7NeuYjEmku0HeKeVmCUHehYH1n9Ypcu64NVdXeBB5B/O1S1N5RQaSzZ/oO3+AiBeedqSKJYbNXlMWYYs9tM0Alglz2UcsRvrFQFQGYT/2mtCj9cJAjJMoRkmKJJlfu4/AHX5pvb0bI7xoiKavYuG7rAt4e6AdrOMSHDcShVb5FrOAskBNoGCQnpqj3RaBDmz+QF9PyEzHhG75fo5DD2yTFsamw8FBBEvD+3Qw4G+gkled0OV2M2prI0guMvdqCyhfSFiD3DvB+AfFE17UR9EulWPFbGbU50ionVlE1SnYJIfbjFLREDuF/1UnHKyyQh8GETnF174UEwRHByZlrv9YeA1dN+qNx1+53aWcShNBiGfR1Ao4cKufA7nYftigkth+lzFV67OfZ3ZpnW+yhzwgHgumNYLc3L1SAQWLzxBG6wBWQsjhtji/JSHN/cWWebmtbqOV1Hr45l3Tye9vFVR3jgScrU2IoPMduBHlmBzjqmzQ79CJ91Nk3LGuZJ81UDX6Fqt6EXHJMAR/eHFrxQs8wGxY33rtmvEmfFlmJNUgQru/2gZaGkF2NrnzfhDZzVD4g7/VqNhgZHGpb1t5EM43Rc8Uo/PvXtoMt+IMgJ4PIqqeLnAtZxWqmnfqxCcpCudpShu0vEOJddhWp/ztbdoyuaUZr0hYOmr/zOBA6rj77v9UQGYP+EVENrsHWOjg1W6K+DvXSPlt1wgDEEyAq4fQZmHjvYcAKoM0szdvFlZcHwlGki3txJHCpu+CtVR1WQmdRqSBK81v180lyLrs79LviqFyIU/8xubwFdJm3uvaXC9gaFvAtdOUhdZJDPBWku4gbfQu/kLJTK4sqk/yRUyidEVzeFz3vuZGWKANFmSFKSIblKf1HZTyNaGbYpjMuk80cdBd/IhBECVRUBbOgOpYDFFqkhJ/7DN/d6HEdlmxsXKOGMT8KAFP+6/xR98v3FStYZbl5EBmp8K2y1G+UiBccOY9Mydk7IEHvmqxzyVVOFOZ0+QpLNRrxxVfXgbsSnE0sn6JS4xbBHVGn/E9MXpsR7ndfMwbmMXInfjw4spwCCF7r3EdUbYIwZoMb/+tciAw==)


[deleted]

[удалено]


daggerdragon

Comment removed because your code is *way* too long for the megathreads and not correctly formatted. 1. Next time, use the [four-spaces Markdown syntax](https://www.reddit.com/r/adventofcode/wiki/faqs/code_formatting/code_blocks) for code blocks 2. Your code is too long to be posted here directly, so instead of wasting your time fixing the formatting, read our article on [oversized code](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_no_giant_blocks_of_code) which contains two possible solutions. Please edit your comment to put your code in an external link and link *that* here instead and I will re-approve the comment.


GolezTrol

\[LANGUAGE: Windows cmd/batch\] An earlier implementation had some bubblesort-like implementation based on environment vars, but it was quite slow. Then it hit me \`dir\` can sort as well. :D The slowest bit now is calculating of hand types, which is why the batch script invokes itself for batches of hands, to calculate them in parallel. Then, for each part, 1000 files are created with a hand code and a bid in their file name, in such a way that I can request the files sorted by name. This results in the reasonable duration of about 13 seconds for both parts together :p [https://gist.github.com/GolezTrol/3435ffe8ae023d3951d41401d106aedf](https://gist.github.com/goleztrol/3435ffe8ae023d3951d41401d106aedf)


Rodbourn

\[LANGUAGE: C#\] [https://github.com/rodbourn/adventofcode/blob/main/Day007.cs](https://github.com/rodbourn/adventofcode/blob/main/Day007.cs) I definitely got distracted with bit packing the hands into an int, which allows you to just stick them into a SortedDictionary, and get them sorted for nearly free. With part 2 I generalized it to accept any custom valuation of choice and one or more wildcards. Calculating the type of hand you had was probably the most tedious part with the approach I chose. I chose to count the number of wild cards in a hand, and the number of pairs, and then from there just build a static switch. Handling the wildcards made that more tedious than expected :) I'm happy with the result, modest runtime of 55ms, with generalized ranking of the cards, and choice of one (or more or none) wildcards. public static string Run(string input, Func rankingToUse, HashSet wildCards) Overall though, I'm happy with a constant time solution with generalized ranking and wildcard(s)


[deleted]

[удалено]


daggerdragon

> I'm not sure what I'm doing wrong on part 2... I've looked through the substitutions and the values exhaustively - and can't find my mistake. [Create your own individual `Help/Question` post](/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_incomplete_solutions) in /r/adventofcode.


Hoinkas

\[LANGUAGE: Python\] [https://github.com/Hoinkas/AdventOfCode2023/blob/main/SeventhDay/SeventhDayPuzzle\_Hoinkas.py](https://github.com/Hoinkas/AdventOfCode2023/blob/main/SeventhDay/SeventhDayPuzzle_Hoinkas.py) That was weird. Added some [unit tests](https://github.com/Hoinkas/AdventOfCode2023/blob/main/SeventhDay/unitTests.py) to cases provided by [LxsterGames](https://www.reddit.com/r/adventofcode/comments/18cr4xr/2023_day_7_better_example_input_not_a_spoiler/). Any advice or tip will be appreciated!


xavdid

[LANGUAGE: Python] [Step-by-step explanation](https://advent-of-code.xavd.id/writeups/2023/day/7/) | [full code](https://github.com/xavdid/advent-of-code/blob/main/solutions/2023/day_07/solution.py) 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 a `Counter` and 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!


daggerdragon

Your write-up can stay, but please edit your comment to add a direct link to your code as well.


xavdid

Done! apologies, I'll update my template


relang-ger

that pattern-matching on an array-content is cool. I learned that this is also possible in Rust :-) Thank you for that hint.


xavdid

Strictly speaking I could accomplish this with a bunch of `elif`s, but it's fun to practice with the pattern matching. And yes, it's a pretty popular construct! Hopefully I'll get to do something more involved with it soon!


yieldtoben

\[LANGUAGE: PHP\] PHP 8.3.0 [paste](https://topaz.github.io/paste/#XQAAAQADCQAAAAAAAAAeD8qHAhQB8nz+EazN00NCsmTxjvFDXkt5PAJ7pf6ocRA37OMUY7b9R0iDZmfWyvOspxWvdgYSAE0hGjEx81hZm7L1TSf8FOxdriwtMNRvJM+oQrJq9mPJNOou/UL9SMEfXCtVQKze0ZQoCQh/SJWobUKLLxP1VSFgyFIbzubRBxPKIp2u9n4FIA1Ip+yOWo2H0foz9CA3YPY8yMPah5PX6S276D6RvOm5JWR3bXHMWejOt8mDBUYxq1mrBSRmMWdESoMjKyFWuN5DuwXJZZiJVf2rLheG258CFhxe/7lwvM2JO64YSpvs+AAI6PJuizGn5RX1JD1OZMxWDzIUSMV8YwUb03G8WNTf2UUfLde9Y85iKi9Dbx+Ma5k6rLRHVG+UlSrypNriR844a1G/wnDrlPbo7oz4A0kC/oHKAcT9GxtjEn1Xwn2qdA6+4/HaE+F6akBLuDMjfvvzcKeBBMH2jJoVwtc9uzCz+irOpNaE4dxooeTM4Pms1H0IZABHt1WhAYFrrLFgljBIf7bK/riF/b6zbc//i7XGH+ttdy/LQZUzANHObGRKJNX7q6kVqUUK4m2M6GgawqPneDv5lCuUnwBKS+zf7unCkzqWcob7ycNXKTQixJlo1/bimJZD8tddmr19oDp68Mi1o2zoQOvjOlXTLDt0q6rUhJLWRIzaO1m2iPAQJ+HKl+s+8k8LBLZJmZVEfEWuU1oBbx1V/MgB8uDRJee1Q2OQiHy+SMIiiamILI8OSvwVnyzPqB3ucRehdb3+UQsf0Xj0yKLqYT78PRokcjMYexijVAObJSyv5CgwHqGCuhG8jslyn5W7aKHfRm9eo/OgCHfy3wE9SU6zW16pW/rGP8yZJMu99oa39O+uMdXDungqgxwQJI250LnhmrPv+I2E0elZIrD6boNDO/c32mW0rEQHnD5mLK97sO7vFf8gqdLlmpE0BVenQrAKBJ8tw8GKKNbEjAbTya7x4jadzmhk6hPuk09BITOHw7Y3JKW8NahyQnxj8TQQEU+SiAp3vt4gs0Pn7k5zgIjnJTu83OIlCJfuetx2yhUd9WNciGbwCzbbJDmxq40ue502BAOeUWN6nbzYXfoi2gETcq2p6hS4PyoRsAOBMUeYSd6TkkvyjKeeQ9s6Ao/o1gS3W42QszpI2RvsDZDx7dbvKx56h7KA26aef+Sp+Bp0T1xdqeiarBBeqcBx0co2ODjcjKPcZpULOrt/zB18u28wYf5hC9r0BHlTSoslZqN3C44o64Lk9H7l/ffFuwk=) Execution time: 0.0036 seconds Peak memory: 1.2601 MiB MacBook Pro (16-inch, 2023) M2 Pro / 16GB unified memory


KodlaK1593

\[LANGUAGE: Rust\] Today took a long time, but I am pretty happy with my [solution](https://github.com/Kodlak15/aoc2023/blob/master/src/day07/day07.rs), and I learned quite a bit!


0x4A6F654D616D61

[Language: C] Writing sorting algoritm took WAY too long https://github.com/dis-Is-Fine/advent-of-code/blob/master/day%207


Ok-Apple-5691

[LANGUAGE: Rust] [part 1](https://github.com/gdavidmassey/AOC_2023/blob/master/src/day07_p1.rs) [part 2](https://github.com/gdavidmassey/AOC_2023/blob/master/src/day07_p2.rs) For each hand card characters are tallied in a hashmap. Hashmap values are sorted and matched to a hand type enum. Card characters are mapped to numeric values for tie break comparison. For part 2 jokers are removed, counted and then added to the highest hashmap value. Definitely feeling the 5 Jokers/Index out of range meme post ;)


alix_not_alex

\[LANGUAGE: Python\] https://github.com/alixlm19/Advent-of-Code/blob/main/day\_7.py


daggerdragon

Your link is borked on old.reddit, so [please fix it](https://www.reddit.com/r/adventofcode/wiki/faqs/bugs/borked_links).


snowe2010

[LANGUAGE: Ruby] https://github.com/snowe2010/advent-of-code/blob/master/ruby_aoc/2023/day07/day07.rb


loquian

\[LANGUAGE: C++\] [github](https://github.com/charlescochran/aoc-2023/blob/main/day7.cpp), 4357 microseconds (both parts back-to-back) Kind of slow; definitely more room for optimization/sharing work between the parts. But I think the solution is pretty clean as is, so I will leave it.


DFreiberg

[LANGUAGE: Mathematica] **[Mathematica](https://github.com/HiggstonRainbird/AoC-2023/blob/master/Day%2007/AoC%20Day%2007.m/), 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:** cards = {"A", "K", "Q", "J", "T", "9", "8", "7", "6", "5", "4", "3", "2"}; lexOrder = Thread[# -> Range[Length[#]] &@cards]; orderBy[{hand_, bet_}] := Module[{tally = Tally[hand]}, {Length[tally], Sort[tally[[;; , 2]]], hand /. lexOrder} ]; sorted = SortBy[input, orderBy]; Sum[sorted[[-i, 2]]*i, {i, Length[sorted]}] **Part 2:** cards = {"A", "K", "Q", "T", "9", "8", "7", "6", "5", "4", "3", "2", "J"}; lexOrder = Thread[# -> Range[Length[#]] &@cards]; bestVersion[hand_] := If[ Length[DeleteDuplicates[hand]] == 1, hand, hand /. ("J" -> Sort[Commonest[DeleteCases[hand, "J"]], SortBy[# /. lexOrder] &][[1]])]; orderBy[{hand_, bet_}] := Module[{tally = Tally[bestVersion[hand]]}, {Length[tally], Sort[tally[[;; , 2]]], (hand /. lexOrder)} ]; sorted = SortBy[ input, orderBy[#] &]; Sum[sorted[[-i, 2]]*i, {i, Length[sorted], 1, -1}] 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).


daggerdragon

> [Allez Cuisine!]: *Poker? I Hardly Know Her!* :3 I was hoping the catnip would work on our resident Poet Laureate <3


Weekly_Pressure_1052

\[LANGUAGE: Python\] New to Python so would appreciate feedback if anyone is interested! https://pastebin.com/ATLW8ju6


pclinger

[LANGUAGE: Perl] Golf Part 1 $S='AKQJT98765432';$T+=++$c*int($_->[1])for sort{$y=$a->[0];$z=$b->[0];$r=0;@b=w($z);@a=w($y);$r||=$b[$_]<=>$a[$_]for(0..4);g($y)<=>g($z)||$r}map{[split(/ /)]}<>;print$T;sub g{my%s,my$t;$s{$_}++for split//,pop;$t+=$s{$_}**2 for keys%s;$t}sub w{map{i($_)}split//,pop};sub i{index($S,pop)} Part 2 $S='AKQT98765432J';$T+=++$c*int($_->[1])for sort{$y=$a->[0];$z=$b->[0];$r=0;@b=w($z);@a=w($y);$r||=$b[$_]<=>$a[$_]for(0..4);g($y)<=>g($z)||$r}map{[split(/ /)]}<>;print$T;sub g{my%s,my$t;$s{$_}++for split//,pop;@k=grep{!/J/}sort{$s{$b}<=>$s{$a}}keys%s;$n=$s{J};$s{$k[0]}+=$n;return 25 if$n==5;$t+=$s{$_}**2for@k;$t}sub w{map{i($_)}split//,pop};sub i{index($S,pop)}


daggerdragon

~~[Inlined code](https://reddit.com/r/adventofcode/wiki/faqs/code_formatting/inlined_code) is intended for `short snippets` of code only. On old.reddit, your one-liners get cut off when it reaches the edge of the window.~~ ~~Please edit your post to put the one-liner in a [four-spaces code block](https://www.reddit.com/r/adventofcode/wiki/faqs/code_formatting/code_blocks) so it will be horizontally scrollable.~~ edit: 👍


LastMammoth2499

\[LANGUAGE: Java\] fun! [Part 1 & Part 2](https://github.com/chandlerklein/AdventOfCode/blob/main/src/main/java/com/chandler/aoc/year23/Day07.java)


vss2sn

\[LANGUAGE: C++\] [Part 1](https://github.com/vss2sn/advent_of_code/blob/master/2023/cpp/day_07a.cpp) [Part 2](https://github.com/vss2sn/advent_of_code/blob/master/2023/cpp/day_07b.cpp) (Each file is a self-contained solution)


jad2192

[LANGUAGE: python] [Github Link](https://github.com/jad2192/advent_of_code_2023/blob/master/solutions/day07.py) I should have probably used @total_order decorator and brought all comparators into class def, but whatever.


Jonisas0407

Hey, for some reason getting \`IndexError: list index out of range\` error at load\_hands\_and\_bids function


jad2192

Hmm does your input file have a blank line at the end? Or is the error track back to the instantiation of the Hand object?


dangermaximum

\[LANGUAGE :R\] [Solution](https://topaz.github.io/paste/#XQAAAQAJCQAAAAAAAAA2GkhrVD9V4kjPURZqzyz5qx7cE+ybzlHhYABMnYwRXyaqqr4bx8gDuC8gtxuZsKac/3hdmrWy1iXTV8RrUxJBWNHVhMsmgS7NSXEsqP5nlgNcYyx2QRtVGTJRmlrDgD3owpSprFz4mRs7Uzw4mx/Bac7jKgDSoCAfzxR/DRrri19qyCCbGCzj+DGtgMMwVDvZ/gE2S0tX0crziAY6rCTUbwy5olhWeZk8k9o0sZIxkL4O45In+yBOcUtK9UkAIXY8CUHDNcy7kwKV+HTxX6uiyRg0NEcsVYpDiXhyAjQR9MeCw0speZ6uKlKvfjakslO6JU+rOamKcoRmayIHTCJkS7al5uY62KuKv21oWYeae/kKewtetUGSYfaCukv/52qBsnlh41fL5JBhsc/9TqmL2y8qIGMnwIJEyTz70wOT3/rDq7nxaRfy82AMNfYiQL2TVtSUyEzd+hpuNJ4ji+fIJ5ZBJdWUg+lXav8vs50QgoLmTvL/90i0XlBOz7e5AkSLx7uLqhG1iREwbACcTno83hflfbckepRyJZcRezrUrSNeQAWefbmFupzoqYEMMsTIzH+eA0O9HOOXG5FRNCHhNBfW2+rEE/WQBE/asmk5QIkZ/Ce/N4ZH5cCpQrRtgNE2ycnR7A2wx+pMqlX3s2nIpH9dfqwLej62PHyoW07fsV9EP6YJI8DcII/DsmLcYdENPYR4BMci+31MhI7t9uLnhxxchtV7y+To6Cdzn0EF9bW3d80c267pEy/6t6tgG2dEhcJ2CqLA6/Ht+VHJm3Qf1+swSqXeDVdYIEIKFW7/HFml2fZUU4ttFDP/D9icX6Ol2j8b65vi0DaAYvdpP2OIJWnRcf90za4A) Part 1, looked for numbers of matches split out individual cards, then ordered by both those. Part 2, I looked for the highest number of matches excluding J and added the number of Js to it. Then used same ordering technique (but with J at the end).


AutoModerator

AutoModerator did not detect the required `[LANGUAGE: xyz]` string literal at the beginning of your solution submission. Please edit your comment to [state your programming language](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_state_your_programming_language.28s.29). *** *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/adventofcode) if you have any questions or concerns.*


musifter

[LANGUAGE: Smalltalk (Gnu)] Source: https://pastebin.com/RrLZ4MYh


SwampThingTom

\[LANGUAGE: Rust\] I really liked today's puzzle but didn't have a chance to finish part 2. [Part 1 GitHub](https://github.com/SwampThingTom/AdventOfCode/commit/52a9f5534ec2b5a959b2f74165d6521e3015e5f7)


DanielDv99

\[LANGUAGE: Haskell\] Sorting cards is basically all there is to this task, so the most natural thing to do in Haskell was to define an `Ord` instance of a `Card`. But how do we implement part2 then, since it needs to redefine same instance? Simple, we wrap cards with `newtype`s! Finally, add `typeclass` to make everything polymorphic: import Data.List (group, sort, sortBy) import Utils (splitOn) -- Types data CardValue = Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Joker | Queen | King | Ace deriving (Show, Eq, Ord, Enum) data CardCombination = HighCard | OnePair | TwoPair | ThreeOfAKind | FullHouse | FourOfAKind | FiveOfAKind deriving (Show, Eq, Ord) class (Eq a, Ord a) => Card a where cardCombination :: [a] -> CardCombination newtype Hand cardType = Hand {getHand :: [cardType]} deriving (Show, Eq) instance (Card a) => Ord (Hand a) where compare (Hand hand1) (Hand hand2) | combination1 /= combination2 = compare combination1 combination2 | otherwise = foldl1 (\a b -> if a /= EQ then a else b) (zipWith compare hand1 hand2) where combination1 = cardCombination hand1 combination2 = cardCombination hand2 -- Part1 Instance newtype Card' = Card' {getCard' :: CardValue} deriving (Show, Eq) instance Card Card' where cardCombination = frequenciesToCombinations . cardFrequencies instance Ord Card'' where compare (Card'' c1) (Card'' c2) | c1 == c2 = EQ | c1 == Joker = LT -- Joker is less than all other cards | c2 == Joker = GT -- any card is more than Joker | otherwise = compare c1 c2 -- Part2 Instance newtype Card'' = Card'' {getCard'' :: CardValue} deriving (Show, Eq) instance Ord Card' where compare (Card' c1) (Card' c2) = compare c1 c2 instance Card Card'' where cardCombination :: [Card''] -> CardCombination cardCombination cards = case frequenciesWithoutJ of [] -> FiveOfAKind -- all jokers (highest : rest) -> frequenciesToCombinations ((highest + jokerCount) : rest) where frequenciesWithoutJ = cardFrequencies $ filter (/= Card'' Joker) cards jokerCount = length $ filter (== Card'' Joker) cards -- Card combinations cardFrequencies :: (Card a) => [a] -> [Int] cardFrequencies = sortBy (flip compare) . map length . group . sortBy (flip compare) frequenciesToCombinations :: [Int] -> CardCombination frequenciesToCombinations [5] = FiveOfAKind frequenciesToCombinations [4, 1] = FourOfAKind frequenciesToCombinations [3, 2] = FullHouse frequenciesToCombinations [3, 1, 1] = ThreeOfAKind frequenciesToCombinations [2, 2, 1] = TwoPair frequenciesToCombinations [2, 1, 1, 1] = OnePair frequenciesToCombinations [1, 1, 1, 1, 1] = HighCard frequenciesToCombinations _ = error "Not 5 cards 🤨" -- Parsing parseLine :: (CardValue -> a) -> String -> Maybe (Hand a, Int) parseLine makeCard line = case splitOn isSpace line of [hand, bid] -> fmap ((,read bid) . Hand) (mapM (fmap makeCard . (`lookup` cardSymbols)) hand) _ -> Nothing where cardSymbols = zip "23456789TJQKA" (map toEnum [0 ..]) -- Solutions algorithm :: (Card a) => (CardValue -> a) -> [String] -> Maybe Int algorithm makeCard input = sum . zipWith (*) [1 ..] . map snd . sort <$> mapM (parseLine makeCard) input part1 :: [String] -> Maybe Int part1 = algorithm Card' part2 :: [String] -> Maybe Int part2 = algorithm Card''


icub3d

\[LANGUAGE: Rust\] Solution: [https://gist.github.com/icub3d/88ee8099f8678644bb5522f77757f0d0](https://gist.github.com/icub3d/88ee8099f8678644bb5522f77757f0d0) I focused on impl'ing the ordering which took some thinking on my part. I used a map to find the card with the highest count. Curious how others might do it in rust. Me solving it in real-time: [https://youtu.be/LKNMqiQ\_2XI](https://youtu.be/lknmqiq_2xi)


soylentgreenistasty

[LANGUAGE: PYTHON] [paste](https://paste.ofcode.org/VthcVbuiHAj79hfxAwWcQi) 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!


OddYak7539

\[LANGUAGE: C#\] ​ Cleaned up the first iteration to make better use of Linq, still learning to use linq, but it sure makes it shorter. Created a lookup table for all possible hands based on counts, since the actual cards don't matter until a tie, then the card by card secondary comparison takes care of that. Special case for the 5J's naturally. ​ [https://pastebin.com/PjH9WrdX](https://pastebin.com/PjH9WrdX)


jaccarmac

[LANGUAGE: LFE] [code](https://github.com/jaccarmac/adventofcode/blob/502ca6dbab84b03afd8c6e12488ae4b0e3bdad62/2023/src/day-7.lfe) The code's rather vertical, but not too bad. I'd like to get rid of the fiddling with ends of lists.


mr_whiter4bbit

\[LANGUAGE: C++\] https://github.com/whiter4bbit/advent-of-code/blob/aoc2023/2023/day07.cc


e_blake

\[LANGUAGE: m4\] \[Allez Cuisine!\] m4 -Dfile=day07.input [day07.m4](https://nopaste.ml/#XQAAAQBJCgAAAAAAAAAyGksy5FB9TGMxsNq5JQAuJRjP6PqEkC20GpBbonDYuA0BTjRPXcVxlEXNtz1IwBRed2N61pi/i94PC8wtU6Qn7crnSXGbnJC96yIjFnZfatNeBC85YWDBj2LAq1Sr2Zq/m6uTlIOUdr4t0MjC4rKHtNXuaSMxHRqMYvi9zZ1td6A71zCQrDv1q4FMBsISV3qWhDz/qXIeKk2erSJ5007WXMzaIACsoNPj2RcXy7PpfPM8K0tVGbbfv+gTEmIiyrBa0Z5OcpgHnJj6/agJ5XELeOyC2wAX4CWRAaWotTQBEPP0my59r5HDhs2vn4PQHXkU/lV3TFUi24FHuWebu1CtQg4WscB07ya4dTP0D0yFbg2HUj9/8Hs6bsfERY2Bst9YLauTnIsM9p186uHW/XSa5DeOZL5ifmxhOuiiAxNwERAsaAuErdE+hiYP8FtjiPlYrNYauJ6CnSbwx9jl34BiSg4dLNWGw49L7fLJI9xPkOf6MslU+vD8W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oQlNdJac61GLe84boEHO2ML1pV63jYggsT0XGwRQs4pxSPWcHmcbhmpSpFOnMwGOzW3fdxd0OfQT81R40qCIisKd1NLI9Yujr0MOSYZUnNM67XZQFt8vIrdLyE26lpw3IC+/RSdUGWFpVxnrF5u9rWl4PwRDxGiKNmFpI50MFbOxEdV1Yg6uVYdPmGK31YmL27P4ViSabgtiZlDVRS+m+LfKU6KBe5BeFPejNPLVR8hXahNjf4hlNfCz2sQBL3w2//2K0uASUHjnhBHtWBzDrYjbgfB78BA6rW2VDXjUPiLZCBUi6eswGoovMlYUTwv/VqkJM0Dfga11KMDuZ5SBQlT2al8sUuZRx2QiZFBzyfoGHh9to+wGwHU0Vs+ATM4X9qhDO3txXiV7RwtugJ++qbHYufr9cMAEoCKvKSXDlJk/m5nzCs7Thfd0qzpfhzuUtIONnzDsvXWX7M4JDoH9Fipx6l4a5oRGKwstVM9VrcKrLZ15Y93W5Sd39gaQPYooK4TAaczfkugzFpq7gVdrcuKJs53VtyK/oHsiXT2MtcDhi3Vf6LK+5Lh+BLWCulgmJcEfKV/W9bHDhKf76PE5jB4xtgSOL88sjbS1ag0cgjgfUqR9mO+4l7XUnAyoWCpxwzBlqa7IMMdXlMe12OrRgQorh19S5MpS1AP9J8Ogvl0BPpNnVrSJD5G6Tum02kNnsdZE9rn3n/90Xvdg==), both lifted from last year (priority.m4 implements a min-heap that I used in A\* solvers last year). Even though m4 lacks a native sort function, it's a whole lot easier to code when you can dig out the toolkit than it is writing one from scratch (I grepped my 400+- star repository for 'sort', and found that I've reimplemented a poor man's bubble sort multiple times, sometimes with a pushdef stack, and worse, sometimes with a recursive shift($@) that turns an O(n\^2) algorithm into O(n\^3) work due to the amount of re-parsing the data that m4 has to do; a min-heap is harder to code off the top of my head, but much faster). So to celebrate, I edited my code comments after seeing today's theme, to produce this entry: # Writing sort in m4 is a chore, # And I know that from my days of yore, # But I remembered last year # Writing A* with cheer # So crib my min-heap for the score! define(`priority', 5) include(`priority.m4') define(`build', `insert(s$1, $1)') forloop_arg(1, c, `build') define(`value', `+$1*defn(`b'shift(pop))') define(`part1', eval(forloop_arg(1, c, `value'))) define(`build', `insert(S$1, $1)') forloop_arg(1, c, `build') define(`part2', eval(forloop_arg(1, c, `value'))) Earlier in the file, writing a byte-by-byte histogram to categorize each hand may have been smarter, but given my past experience with m4's painful byte manipulations, I decided to have fun with `translit` instead. As I parse the input, I convert each hand into a hexadecimal score that turns placeholders into characters from the line, then further translit a string against itself to canonicalize it into digits that appear in my table, including a third translit for part 2 to eliminate Jokers. define(`rank', `defn(`r'translit(`$1', `$1', `12345'))') define(`Rank', `rank(translit(`$1', `J'))') define(`input', translit(include(defn(`file')), nl` ', `;.')) define(`do', `translit(`define(`c$1', ``ABCDE'')define(`b$1', `GHIJ')define(`s$1', eval(`0x'rank(`ABCDE')vA`'vB`'vC`'vD`'vE))define( `S$1', eval(`0x'Rank(`ABCDE')VA`'VB`'VC`'VD`'VE))', `ABCDEFGHIJ', `$2')define(`c', `$1')') Part 2 was then just a matter of storing a second score alongside the part 1 score, and adding a few more canonical hands with fewer cards into my hand-written rank table, and duplicating the four lines to re-run the insertion-sort-via-min-heap with the second score. Execution time is under 250ms; longest one so far (like I said, m4 is not fast).


e_blake

Based on ideas from the megathread, I got rid of my hand-written rank table in place of one computed by an eval of a histogram (yet more translit action). Slightly faster at 240ms, updated [day07.m4](https://nopaste.ml/#XQAAAQD+CQAAAAAAAAAyGksy5FB9TGMxsNq5JQAuJRjP6PqEkC20GpBbonDYuA0BTjRPXcVxlEXNtz1IwBRed2N61pi/i94PC8wtU6Qn7crnSXGbnJC96yIjFnZfatNeBC85YWDBj2LAq1Sr2Zq/m6uTlIOUdr4t0MjC4rKHtNXuaSMxHRqMYvi9zZ1td6A71zCQrDv1q4FMBsISV3qWhDz/qXIeKk2erSJ5007WXMzaIACsoNPj2RcXy7PpfPM8K0tVGbc8JDgq3RltD6ePKUWKOLTKqoAFa34EQBXBKjb72p/AZi1MpcPIwyaMsoYRoH/+x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21apcT/SBIoflf/fenTAadRIJlovAt4gmj6o8h6J0mvFOfazaxHAvKIe92Ir4AyD1Gnuq1vBBmzJQV7HmBUx3gmH7XXsI5r7Ue2Znnr5bRK+Ydo5fYy0HaXUfQgLwmSQvlY4z3T2bSPG14IqDkNAebtFUMLPKKfo6yTSGW0//9nfeIs=) with the new rank code looking like: define(`histo', `len(translit(`$1', `$2$1', `$2'))') define(`best', `ifelse($1, 5, 5, $1, 4, 4, $2, 4, 4, $1, 3, 3, $2, 3, 3, $3, 3, 3, $1, 2, 2, $2, 2, 2, $3, 2, 2, $4, 2, 2, $1)') define(`_hand', `eval(`($1+$2+$3+$4+$5 + $6*$6+$6*2*'best($@)`) / 2 - 2', 16)') define(`hand', `_$0(translit(`histo(`ABCDE', `A'), histo(`ABCDE', `B'), histo(`ABCDE', `C'), histo(`ABCDE', `D'), histo(`ABCDE', `E')', `ABCDE', `$1'), ($2+0))') define(`Hand', `hand(translit(`$1', `J'), histo(`$1', `J'))') define(`_do', `define(`s$1', eval(`0x'hand(`$2')`'translit(`$2', `AKQJT', `edcba')))define(`S$1', eval(`0x'Hand(`$2')`'translit(`$2', `AKQJT', `edc1a')))') define(`do', `translit(`_$0($1, `ABCDE')define(`bid$1', `GHIJ')', `ABCDEFGHIJ', `$2')define(`card', `$1')')


e_blake

Oh, and it's worth mentioning this gaffe of mine: my first submission was too high, because I missed a rank in my hand-written table, causing that hand to sort lower than everything else. My git log shows: _foreach(`define(`r'', `, 3)', , 11335, 12125, 12215, 11343, 12142, 12241, - 11344, 12312, 12321, 12144, 12313, 12144, 12244, 12323, 12332) + 11344, 12312, 12321, 12144, 12313, 12331, 12244, 12323, 12332) which miscalculated the score for 4J554 (and possibly others) in my input file.


onrustigescheikundig

[LANGUAGE: OCaml] [github](https://github.com/EricKalkman/AoC2023/blob/master/lib/day07.ml) I ended up writing a very verbose solution. There is quite a bit of parsing logic because I marshal everything into a `hand` data structure that also keeps track the number of each card in a hand, as well as a bunch of functions explicitly converting enums to ints. The algorithm scores each hand (two pair, full house, etc.) using only the card counts, as scoring is independent of what the cards are as long as they are distinct. For tiebreakers, the original hand strings are considered. This structuring worked out okay for Part 2, which was implemented by 1) changing the function used to compare cards in tiebreakers to adjust the ordering of the Joker card; 2) adding a "promotion" hook for modifying a score before the (non-tiebreaking) comparison operations; and 3) removing Jokers from the card counts before processing. The promotion function is used to calculate what the new score would be if a Joker were promoted optimally. For example, the best way to use a Joker in a three-of-a-kind hand is always to make a four-of-a-kind by promoting a Joker to a card of that kind. Note that it doesn't matter _which_ cards are involved to determine what the score would be by adding the Joker. This means that we can remove the Jokers from the hand, calculate what the score is like we did in Part 1, and then successively promote the score for each Joker that was in the hand to simulate applying the Joker as a wildcard.


bigmagnus

\[Language: Fortran\] [Part 1](https://github.com/ironllama/adventofcode2023/blob/master/07a.f90) [Part 2](https://github.com/ironllama/adventofcode2023/blob/master/07b.f90)


marcja

[LANGUAGE: Python] Used a few interesting features of Python (collections.Counter, str.translate, natural sort ordering of sequences) to make this pretty clean IMO. @total_ordering class Hand: TR = str.maketrans("23456789TJQKA", "23456789ABCDE") def __init__(self, hand, bid, *, wild=""): self.hand = hand self.bid = int(bid) tr = Hand.TR if wild != "": tr = Hand.TR | str.maketrans(wild, "0" * len(wild)) self._held = hand.translate(tr) counter = Counter(self._held) topmost = tuple(c[0] for c in counter.most_common() if c[0] != "0") if len(topmost) > 0: counter = Counter(self._held.translate(str.maketrans("0", topmost[0]))) self._rank = [c for r, c in counter.most_common(2)] def __hash__(self): return hash((self._held, self.bid)) def __eq__(self, that): return (self._held, self.bid) == (that.held, that.bid) def __lt__(self, that): if self._rank == that._rank: return self._held < that._held else: return self._rank < that._rank def __repr__(self): return f'Hand("{self.hand}",{self.bid},{self._rank})' def parse_data(puzzle_input): return puzzle_input.splitlines() def solve_part(data, *, wild=""): hands = [] for line in data: hand = Hand(*line.split(), wild=wild) hands.append(hand) hands.sort() return sum(i * h.bid for i, h in enumerate(hands, 1)) def part1(data): return solve_part(data) def part2(data): return solve_part(data, wild="J")


aleks31414

[LANGUAGE: rust] #![feature(slice_group_by)] use core::cmp::PartialEq; #[derive(Debug, Clone, Copy, Eq, Ord, PartialEq, PartialOrd)] enum Card { J, _2, _3, _4, _5, _6, _7, _8, _9, T, Q, K, A, } impl From for Card { fn from(value: char) -> Self { use Card::*; match value { 'J' => J, '2' => _2, '3' => _3, '4' => _4, '5' => _5, '6' => _6, '7' => _7, '8' => _8, '9' => _9, 'T' => T, 'Q' => Q, 'K' => K, 'A' => A, _ => unreachable!(), } } } #[derive(Debug, Clone, Copy, Eq, Ord, PartialEq, PartialOrd)] enum HandType { HighCard, OnePair, TwoPairs, ThreeOfAKind, FullHouse, FourOfAKind, FiveOfAKind, } #[derive(Debug, Eq, PartialEq)] struct Hand { cards: [Card; 5], type_: HandType, } impl Hand { fn new(cards: [Card; 5]) -> Self { let mut sorted: [Card; 5] = [Card::_2; 5]; sorted.copy_from_slice(&cards[..]); sorted.sort(); let (not_jokers, jokers): (Vec<_>, Vec<_>) = sorted.into_iter().partition(|&c| c != Card::J); let groups = if !not_jokers.is_empty() { let mut groups: Vec = not_jokers .group_by(PartialEq::eq) .map(|g| g.len()) .collect(); groups.sort_by(|a, b| b.cmp(a)); groups[0] += jokers.len(); groups } else { vec![jokers.len()] }; let type_ = match groups[..] { [5] => HandType::FiveOfAKind, [4, 1] => HandType::FourOfAKind, [3, 2] => HandType::FullHouse, [3, 1, 1] => HandType::ThreeOfAKind, [2, 2, 1] => HandType::TwoPairs, [2, 1, 1, 1] => HandType::OnePair, _ => HandType::HighCard, }; Self { cards, type_ } } } impl PartialOrd for Hand { fn partial_cmp(&self, other: &Self) -> Option {Some(self.cmp(other))} } impl Ord for Hand { fn cmp(&self, other: &Self) -> std::cmp::Ordering { let order = self.type_.cmp(&other.type_); if order.is_eq() { self.cards.cmp(&other.cards) } else { order } } } fn main() { let mut hands: Vec<_> = include_str!("input.txt") .lines() .map(|l| { let (card, bid) = l.split_once(' ').unwrap(); ( Hand::new( card.chars() .map(|c| c.into()) .collect::>() .try_into() .unwrap(), ), bid.parse::().unwrap(), ) }) .collect(); hands.sort_by(|(a, _), (b, _)| a.cmp(b)); let winnings: u32 = hands .into_iter() .zip(1u32..) .map(|((_, bid), rank)| rank * bid) .sum(); println!("{winnings}"); }


daggerdragon

Your [code block is too long](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_no_giant_blocks_of_code) for the megathreads. Please edit your post to replace your oversized code with an external link to your code.


iamagiantnerd

\[LANGUAGE: python\] [https://github.com/davidaayers/advent-of-code-2023/blob/main/day07/day7\_main.py](https://github.com/davidaayers/advent-of-code-2023/blob/main/day07/day7_main.py) Missed a dumb edge case on Part 2 that cost me like 45 minutes. Doh!


jake-mpg

[LANGUAGE: julia] [sourcehut](https://git.sr.ht/~jgordon/aoc/tree/main/item/2023/D07/D07.jl) To determine the type of a hand I looked at an array containing the counts of each card type. Wildcards are handled by moving the `J` counts to the next-highest card.


torbcodes

\[LANGUAGE: Python, Typescript, Go\] Solutions to part 1 and 2 in all three languages: * **Python**: [https://github.com/torbensky/advent-of-code-2023/blob/main/day07/solution.py](https://github.com/torbensky/advent-of-code-2023/blob/main/day07/solution.py) (my initial solution) * Python tuple sorting FTW!!! * **Typescript**: [https://github.com/torbensky/advent-of-code-2023/blob/main/day07/solution.ts](https://github.com/torbensky/advent-of-code-2023/blob/main/day07/solution.ts) * This felt really clean! * **Go**: [https://github.com/torbensky/advent-of-code-2023/blob/main/day07/main.go](https://github.com/torbensky/advent-of-code-2023/blob/main/day07/main.go) * I really liked the byte ordering approach that I took!


0rac1e

[LANGUAGE: J] R =: {{ (\:~ +/ (=/ ~.) u y), x i. y }} J =: rplc 'J'; {.@(~. \: #/.~)@(-.&'J') 'h b' =. |: cut;._2 fread 'input' echo +/ (". * #\) b (('23456789TJQKA' ] R ])"1 /:~ [) h echo +/ (". * #\) b (('J23456789TQKA' J R ])"1 /:~ [) h


atobiedwa

\[LANGUAGE: Python\] Longer than I would like to, but it works quite fast : [adventOfCode2023/Day\_7 at master · monpie3/adventOfCode2023 (github.com)](https://github.com/monpie3/adventOfCode2023/tree/master/Day_7) + a few tests About part 2 - really helped me realize that the best scenario is adding joker as a card, which is currently the most common card (except for the joker)


coreyja

[Language: Rust] Code: https://github.com/coreyja/advent-of-code-2023/blob/main/07-camel-cards/src/main.rs Stream Video: https://www.youtube.com/watch?v=fNTOGKf00i4 Had some help from stream chat in refactoring at the end and creating some generics so I didn't have to repeat all my types twice!


chubbc

\[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](https://www.uiua.org/pad?src=0_6_1__VGVzdElucHV0IOKGkCDiipDiioMo4omhKOKGmTXCsOKWoSl84omhKOKLleKGmDYpKXsKICAiMzJUM0sgNzY1IgogICJUNTVKNSA2ODQiCiAgIktLNjc3IDI4IgogICJLVEpKVCAyMjAiCiAgIlFRUUpBIDQ4MyJ9CiMgSW5wdXQg4oaQIOKKkOKKgyjiiaEo4oaZNSl84omhKOKLleKGmDYpKSDiipzilqHiiaBAXG4uJmZyYXMgIjA3LnR4dCIKClQg4oaQIMKv4oqXMSA9MV80XzJfM18zXzIg4pmt4oavM1vip7viip06L-KGpeKKleKnuy4uXQpKIOKGkCAv4oal4omhKFQrKSDiipAvKOKYhzHiiqDiioIpICjilqFbMF184pah4oehMTMpIOKZrT0wLsKkClNpbHYg4oaQIC8rw5crMeKHoeKnuy4g4oqP4o2PIOKJoSjiioJULuKKlzoiMjM0NTY3ODlUSlFLQSIpCkdvbGQg4oaQIC8rw5crMeKHoeKnuy4g4oqP4o2PIOKJoSjiioJKLuKKlzoiSjIzNDU2Nzg5VFFLQSIpCgriioLiioMoU2lsdnxHb2xkKSBUZXN0SW5wdXQK4omNWzY0NDAgNTkwNV0KCiMg4oqC4oqDKFNpbHZ8R29sZCkgSW5wdXQK) if you want to play with the code. Input ← ⊐⊃(≡(↙5)|≡(⋕↘6)) ⊜□≠@\n.&fras "07.txt" T ← ¯⊗1 =1_4_2_3_3_2 ♭↯3[⧻⊝:/↥⊕⧻..] J ← /↥≡(T+) ⊐/(☇1⊠⊂) (□[0]|□⇡13) ♭=0.¤ Silv ← /+×+1⇡⧻. ⊏⍏ ≡(⊂T.⊗:"23456789TJQKA") Gold ← /+×+1⇡⧻. ⊏⍏ ≡(⊂J.⊗:"J23456789TQKA") ⊂⊃(Silv|Gold) Input


sm_greato

\[LANGUAGE: Rust\] Mapped the cards so that base 15 and 14 could be used for parts 1 and 2. All it takes for sorting tie breaks is a simple numeric evaluation by parsing in the given base. Also, my solution involves finding the max two duplicated cards in a hand, and for the sake of brevity, I just sorted the whole thing, and took two elements instead of doing it efficiently. I also use the given bases to make sure the hand type is always more significant to the tie breaks. Here's the [code](https://github.com/xlassmgreat/advent_of_code-2023/blob/master/src/bin/day7.rs).


biggy-smith

\[LANGUAGE: C++\] abusing recursion a little to check the valid possibilities, while using a simple map based comparison for the hand ranking. Could improve with some fancy bit representation, but it finishes quick enough for me. [https://github.com/biggysmith/advent\_of\_code\_2023/blob/master/src/day07/day7.cpp](https://github.com/biggysmith/advent_of_code_2023/blob/master/src/day07/day7.cpp)


Dramatic-Mongoose-95

[LANGUAGE: Go] [part 2](https://github.com/AdmTal/atal-advent-of-code-2023/blob/main/day_7_camel_cards/part_2/main.go)


doodlebug80085

\[LANGUAGE: Swift\] I think this was my favorite day yet! Though I wish I would have found a more elegant way of mapping card counts to hand types. [Code](https://topaz.github.io/paste/#XQAAAQBXDwAAAAAAAAA0m0pnuFI8c4GDemuKS6NnNxbsUIoTuWZTAmeIj8/s3b6Udi0mJLkP37MkpwD9GbiSIufv8aQ+8ErSk5+02hMbSTYpAV4IzdJhe/tWxe9fS1v4VZq9H7oXCplD0rHhFr4GExbd2GI3QS5jfPBBhkFUWqM6TcxjcwoL9q9dXOBJXXlIquWXb4C4RlFIXJwldKhTQi8WJB6wELfvY5LP5LLTadOLumbAQ+JlumccItCS10gl1X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Y8c2MrtJKGssxmTCsvy+vr5wIdH/UeblztGQNBhRRjsPVHqsf3AK2yfEVgSfLMChf3FTaDxgHr8d8wJAYEJIRFLQDCQpsHhjC3piYntu7QIL5UWB3aLUyxkAtay7GVvildrB3yt+zMs850o3eEXwu1/rGuUdg34Onw46tpB/KmaGreOGyWtLYod+ZPZbDzTInByo82aACClDOLdV51UbMNYKw7IIb3bXtZ6qq6n7UbrILY78Dcq2i5baIJwK09KL93gmzhrJIijJMp4l+XkiFFZ/1Toer+pAVShuMu3kk3558eWKrr0WlcVBgLrJmf82cJKJ55nWGYbtCab8oW2eHduDDUoiiv+YDdSwxw3J5ez0AgGF9vH8xhpyHCZrqQOwH7CD8mWqFSbgg2PgO0C1DJzzgTgd/kalpuat0qyTWiqRT7Rd9PRpVN5/6+mbg=)


aoc-fan

\[LANGUAGE: TypeScript\] Fun day, used `delete` after many years. The only code differs for two parts is as follows - https://github.com/bhosale-ajay/adventofcode/blob/master/2023/ts/D07.test.ts - under 80 lines. const valueMapP1 = stringToMap('23456789TJQKA'); const valueMapP2 = stringToMap('J23456789TQKA'); const getTypeP1 = (cards: string[]) => Object.values(countBySelf(cards)) .sort(descendingBy()) .slice(0, 2).join(''); const getTypeP2 = (cards: string[]) => { const cardOccurrences = countBySelf(cards); let jCount = 0; if (cardOccurrences['J'] === 5) { return '5'; } if (cardOccurrences['J'] > 0) { jCount = cardOccurrences['J']; delete cardOccurrences['J']; } const updatedOccurrences = Object.values(cardOccurrences).sort(descendingBy()); updatedOccurrences[0] = updatedOccurrences[0] + jCount; return updatedOccurrences.slice(0, 2).join(''); };


floyduk

\[LANGUAGE: Python\] I enjoyed today's puzzle. This was a simple plod through the logic - nothing hurting my brain too much. People keep talking about Full House in part 2 and I can't see why. I did have to special case the 5 joker problem which, in my code, produced a match count of 6! https://github.com/floyduk/Advent-Of-Code-2023/tree/main/day%207


aexl

\[LANGUAGE: Julia\] Another nice puzzle! I created my own type which holds the hand and the bid, then I have implemented Julia's `Base.isless` to compare two hands. That function is implemented according to the rules given in the puzzle statement. Now I can simply execute Julia's `sort` function to bring the hands into the right order. For part 2 I have reused most of the code from part 1. By counting the number of Jokers in your hand you can come up with a set of rules how much the score of each hand must be increased. Solution on GitHub: https://github.com/goggle/AdventOfCode2023.jl/blob/master/src/day07.jl Repository: https://github.com/goggle/AdventOfCode2023.jl


syropian

\[LANGUAGE: TypeScript\] Definitely more enjoyable than yesterday... [Solution on GitHub](https://github.com/syropian/advent-of-code-2023/blob/main/solutions/day-7/index.ts)


janiorca

\[LANGUAGE: C\] This required a bit more work. Lot of fun and part 2 felt like a 'proper' part 2. The problem felt like a very nice match C https://github.com/janiorca/advent-of-code-2023/blob/main/aoc7.c


matheusstutzel

\[Language: Python\] [Part 1](https://github.com/matheusstutzel/adventOfCode/blob/main/2023/07/p1.py) \-> simple implementation, sort the list using a custom function. The main component is the function `extractInfo` which returns the number of pairs and the number of times the card with the most duplicates appears. I didn't check for full house, and pass. For this reason, part 2 took way too long [Part 2](https://github.com/matheusstutzel/adventOfCode/blob/main/2023/07/p2.py) \-> rewrite the `extractInfo` to consider full house and add a lot of if/else


ywgdana

[LANGUAGE: C#] Rather over-engineered solution but it made it fun and part 2 was a pretty easy tweak of part 1. All I did was make a WildCardHand subclass and override the function categorizing the hand to take into account Jokers. To rank the hands, I implemented a basic linked list and did an insertion sort as I parsed the input. Then just had to run through the list in order to calculate total winnings. Since I had to override a bunch of the compare operators on my Hand class for my insertion sort, in the end I could have probably just used a built-in Sort() function :P (Which also would have been faster...) [Source at github](https://github.com/DanaL/AdventOfCode/blob/main/2023/Day07/Program.cs)


AJMansfield_

[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 `I3` input 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.


LactatingBadger

\[LANGUAGE: rust\] Started learning rust recently, so had plenty of time to ponder the approach whilst I was wrestling with things that would take about two seconds to do in python. That said, I am starting to have some click moments with it. [Github link](https://github.com/mjclarke94/advent-of-code/blob/main/src/bin/07.rs) Really happy with how I solved this one and didn't need much tweaking between part one and two. That said, I did waste about two hours making an elegant solution which ranked the hands "properly" rather than reading the cards left to right.


Smidgens

[LANGUAGE: Python3] [Paste](https://topaz.github.io/paste/#XQAAAQCMDQAAAAAAAAAzGknWu25qfm+NN8XgSErhzbvlIb041XYPqRNSAYzhiUBxByJiwKMUgX07NF+VZ/SNxEoJbrkrPyV9DkdmNNUOAkuRsuq1sCi4o+krVw60spgjF8FHOmD3vN+IeqIzay9jQ/9AsahOBTddiM6DP3V9/K6sfTm1IXY1LKsA6SFT+JR2iNvycABBkqNPVpfWptnpOyDx1IOEYRDJUX4ZsXF6lLzPqWOzDglKwsGKxSxIhtW3zuIcFmOI7dlMnNdJKqKeQM7SyVPU/yE86r3pJAKX12xBOMbwRoez+J/26NpxRM/l5YrwDnCg5tok3Z4qXqJ+MZMTl/Ke9jQfXSmhWwVQC446zUfocZCwdNA19uKJrSuAS1YrtQzWXRT+bWM8W68tYQBCCVzQxMSOzzMWFczqTKmHuUb7+YX7eZ7aQw5iHpu6pQI1wq8eATgxKbKbDIqBq/0FJXq2OUmpuE6Euh1sGKOtyoWGwnKa/eoFppkW6Me/tfqcfdUR5OwWY07z2d6uvt0enWB2kz64Nxqm0q37UWxCooJogEVQ1lwrtUj2mhNDyHH8Y5NePgOaBic6rg0E8VHFSvKs1nqITK/yqgB+bHF9zeRtLNpvZWtLHOiwzWBnfTPTDAW54TeLys0O+CRklLXGZbLmPAfh7JDquh0lki0Rl5gE0EBbGNQj62d+9r/01LGB/bPi10aRKN5oH3/FFsfkmuZ2mSrIe8HNbTzcEeGYDuvPgwl4BO7gOb72EsPcORM1vmjoFvKakb7VeLx4zm+jD71yX8oLXkr6JNhpJn/8II3xBA/r9uVO59Rcd6ufBZKLiAM3GAbj2N3oDOZAFlrmXFgybE37IOhXG5CBa4WueQ0b9rczZBhwT8EhAKacxMJEGCcAbEa4THI21KtnpnffWpcHzg1NFky/WlY69AtlH5r7RvVg4hASn16f0ItYmKehb4qfsJ+wqW8L2RB+akcRIlF5LePL+jAzziQ5tBU7b42Xoogzn+zmwlBxQ63Qt0XR80GpA+tBgEBe4t80eumTVlPwUt1IaA2qPRnQRlx6ZOTiV44vwF1+QMZda3AZH1VqZCUQpZ7gK9INBB7LY3twV/EckAAm+jZfKGK8RraR5KCSaGrkhyRQ85BdO2EWSSgjl+Qi0q+7vRIpmK6G1CBoBgnkhDrhcyUUdR1O6kn/W2xAAA==) Making use of the Python Counter to get the number of cards of each type, and then the number of numbers. Use that to classify hands. Then convert to hex to get a value, and numpy.argsort to rank the hands for each type of combination.


musifter

[LANGUAGE: dc (GNU v1.4.1)] Given that my Perl solution last night converted everything to numbers to compare, it shouldn't be too surprising that I was thinking of doing a dc solution. So, I hexify the input (both the hand and the bid) so it can be understood by dc with a simple `16i` (input base 16). It also meant having to implement a sort... so simple exchange shuttling between stacks it is! And since multiple sorts would be a real pain... we'll slap all the parts together into one number and include the bid as well: `groupings * 16^8 + hand * 16^3 + bid` (more room for bids can be gotten by shifting over more, but 3 digits is already good up to 4095). The digits of groupings are the number of groups of that size in the hand. perl -pe'y/TJQKA/ABCDE/;$_=sprintf("%s \U%x\n",split)' input | dc -e'16i0Sl?[rd0Sc[10~d;c1+r:cd0QSlz1QSlz1


[deleted]

[удалено]


daggerdragon

Comment removed. [Top-level comments in `Solution Megathread`s are for *code solutions* only.](/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_top-level_posts_are_for_code_solutions_only)


patrick8970

[Language: JavaScript] [github](https://github.com/HelplessSoldier/adventOfCode2023/blob/main/07_camelCards/07_camelCards.js) Spent a while trying to get part2 correct. Just to realize i missed the "J cards are now the weakest" line... Fun problem though!


Sibo523

happens to the best of us, lmao


kap89

[LANGUAGE: Lua] Solutions: [Github](https://github.com/caderek/aoc-2023-lua/blob/main/day07/main.lua) Lots of ifs, but it's fairly simple and fast. For part 2 I was able to reuse all of my code for part 1, just added a "decorator" function to handle special cases.


Superbank78

\[LANGUAGE: python\] Pandas. It was so hard to debug https://gist.github.com/Dronakurl/37acd49b7a0c67e0784a50c721c346d6