Day 7: Camel Cards
Megathread guidelines
- Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
- Code block support is not fully rolled out yet but likely will be in the middle of the event. Try to share solutions as both code blocks and using something such as https://topaz.github.io/paste/ , pastebin, or github (code blocks to future proof it for when 0.19 comes out and since code blocks currently function in some apps and some instances as well if they are running a 0.19 beta)
FAQ
- What is this?: Here is a post with a large amount of details: https://programming.dev/post/6637268
- Where do I participate?: https://adventofcode.com/
- Is there a leaderboard for the community?: We have a programming.dev leaderboard with the info on how to join in this post: https://programming.dev/post/6631465
🔒 Thread is locked until there's at least 100 2 star entries on the global leaderboard
🔓 Thread has been unlocked after around 20 mins
Scala3
val tiers = List(List(1, 1, 1, 1, 1), List(1, 1, 1, 2), List(1, 2, 2), List(1, 1, 3), List(2, 3), List(1, 4), List(5)) val cards = List('2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A') def cardValue(base: Long, a: List[Char], cards: List[Char]): Long = a.foldLeft(base)(cards.size * _ + cards.indexOf(_)) def hand(a: List[Char]): List[Int] = a.groupMapReduce(s => s)(_ => 1)(_ + _).values.toList.sorted def power(a: List[Char]): Long = cardValue(tiers.indexOf(hand(a)), a, cards) def power3(a: List[Char]): Long = val x = hand(a.filter(_ != 'J')) val t = tiers.lastIndexWhere(x.zipAll(_, 0, 0).forall(_ <= _)) cardValue(t, a, 'J'::cards) def win(a: List[String], pow: List[Char] => Long) = a.flatMap{case s"$hand $bid" => Some((pow(hand.toList), bid.toLong)); case _ => None} .sorted.map(_._2).zipWithIndex.map(_ * _.+(1)).sum def task1(a: List[String]): Long = win(a, power) def task2(a: List[String]): Long = win(a, power3)
Ruby
https://github.com/snowe2010/advent-of-code/blob/master/ruby_aoc/2023/day07/day07.rb
Gonna clean it up now, but pretty simple at the end of it all. Helps that ruby has several methods to make this dead simple, like
tally
,any?
,all?
, andzip
Cleaned up solution:
def get_score(tally) vals = tally.values map = { ->(x) { x.any?(5) } => 7, ->(x) { x.any?(4) } => 6, ->(x) { x.any?(3) && x.any?(2) } => 5, ->(x) { x.any?(3) && tally.all? { |_, v| v != 2 } } => 4, ->(x) { x.count(2) == 2 } => 3, ->(x) { x.one?(2) && tally.all? { |_, v| v <= 2 } } => 2, ->(x) { x.all?(1) } => 1, } map.find { |lambda, _| lambda.call(vals) }[1] end def get_ranking(lines, score_map, scores) lines.zip(scores).to_h.sort do |a, b| a_line, a_score = a b_line, b_score = b if a_score == b_score a_hand, _ = a_line.split b_hand, _ = b_line.split diff = a_hand.chars.zip(b_hand.chars).drop_while { |a, b| a == b }[0] card_1 = score_map.index(diff[0]) card_2 = score_map.index(diff[1]) card_1 <=> card_2 else a_score <=> b_score end end end def calculate_total_winnings(ranking) max_rank = ranking.size (1..max_rank).sum(0) do |rank| line = ranking[rank - 1] _, bid = line[0].split bid.to_i * rank end end score_map_p1 = %w[. . 2 3 4 5 6 7 8 9 T J Q K A] score_map_p2 = %w[. . J 2 3 4 5 6 7 8 9 T Q K A] execute(1) do |lines| scores = lines.map do |line| hand, _ = line.split tally = hand.split('').tally get_score tally end ranking = get_ranking(lines, score_map_p1, scores) calculate_total_winnings ranking end execute(2) do |lines| scores = lines.map do |line| hand, _ = line.split hand_split = hand.split('') tally = hand_split.tally if hand_split.any? { |c| c == 'J' } highest_non_j = tally.reject { |k, v| k == 'J' }.max_by { |k, v| v } if highest_non_j.nil? tally = { 'A': 5 } else tally[highest_non_j[0]] += tally['J'] end tally.delete('J') end get_score tally end ranking = get_ranking(lines, score_map_p2, scores) calculate_total_winnings(ranking) end
This wasn't too bad. Had a worried moment when the part 2 solution took more than half a second. Maybe a better solution that brute forcing all the joker combinations, but it worked.
Python
import re import argparse import itertools from enum import Enum rule_jokers_enabled = False class CardType(Enum): HighCard = 1 OnePair = 2 TwoPair = 3 ThreeOfAKind = 4 FullHouse = 5 FourOfAKind = 6 FiveOfAKind = 7 class Hand: def __init__(self,cards:str,bid:int) -> None: self.cards = cards self.bid = int(bid) if rule_jokers_enabled: self.type = self._find_type_joker(cards) else: self.type = self._find_type(cards) def _find_type(self,cards:str) -> CardType: # group cards based on card counts card_list = [*cards] card_list.sort() grouping = itertools.groupby(card_list,lambda x:x) lengths = [len(list(x[1])) for x in grouping] if 5 in lengths: return CardType.FiveOfAKind if 4 in lengths: return CardType.FourOfAKind if 3 in lengths and 2 in lengths: return CardType.FullHouse if 3 in lengths: return CardType.ThreeOfAKind if len([x for x in lengths if x == 2]) == 2: return CardType.TwoPair if 2 in lengths: return CardType.OnePair return CardType.HighCard def _find_type_joker(self,cards:str) -> CardType: try: joker_i = cards.index("J") except ValueError: return self._find_type(cards) current_value = CardType.HighCard for new_card in [*(valid_card_list())]: if new_card == "J": continue test_cards = list(cards) test_cards[joker_i] = new_card new_value = self._find_type_joker("".join(test_cards)) if new_value.value > current_value.value: current_value = new_value return current_value def sort_string(self): v = str(self.type.value) + ":" + "".join(["abcdefghijklmnoZ"[card_value(x)] for x in [*self.cards]]) return v def __repr__(self) -> str: return f"" def valid_card_list() -> str: if rule_jokers_enabled: return "J23456789TQKA" return "23456789TJQKA" def card_value(char:chr): return valid_card_list().index(char) def main(line_list: list): hand_list = list() for l in line_list: card,bid = re.split(' +',l) hand = Hand(card,bid) hand_list.append(hand) #print(hand.sort_string()) hand_list.sort(key=lambda x: x.sort_string()) print(hand_list) rank_total = 0 rank = 1 for single_hand in hand_list: rank_total += rank * single_hand.bid rank += 1 print(f"total {rank_total}") if __name__ == "__main__": parser = argparse.ArgumentParser(description="day 1 solver") parser.add_argument("-input",type=str) parser.add_argument("-part",type=int) args = parser.parse_args() if args.part == 2: rule_jokers_enabled = True filename = args.input if filename == None: parser.print_help() exit(1) file = open(filename,'r') main([line.rstrip('\n') for line in file.readlines()]) file.close()
I think one doesn't need to generate all combinations. All combinations using cards already present in the hand should be enough (since a joker can only increase the value of the hand by being grouped with existing cards (since in this game having four of a kind is always better than having any hand with a four of a kind/full house and having 3 is always better than any hand with pairs, and having a pair is better than any card without any cards of the same kind)). This massively decreases the amount of combinations needed to be generated per jokery hand.
Factor on github (with comments and imports):
! hand: "A23A4" ! card: 'Q' ! hand-bid: { "A23A4" 220 } : card-key ( ch -- n ) "23456789TJQKA" index ; : five-kind? ( hand -- ? ) cardinality 1 = ; : four-kind? ( hand -- ? ) sorted-histogram last last 4 = ; : full-house? ( hand -- ? ) sorted-histogram { [ last last 3 = ] [ length 2 = ] } && ; : three-kind? ( hand -- ? ) sorted-histogram { [ last last 3 = ] [ length 3 = ] } && ; : two-pair? ( hand -- ? ) sorted-histogram { [ last last 2 = ] [ length 3 = ] } && ; : one-pair? ( hand -- ? ) sorted-histogram { [ last last 2 = ] [ length 4 = ] } && ; : high-card? ( hand -- ? ) cardinality 5 = ; : type-key ( hand -- n ) [ 0 ] dip { [ high-card? ] [ one-pair? ] [ two-pair? ] [ three-kind? ] [ full-house? ] [ four-kind? ] [ five-kind? ] } [ dup empty? ] [ unclip pick swap call( h -- ? ) [ drop f ] [ [ 1 + ] 2dip ] if ] until 2drop ; :: (hand-compare) ( hand1 hand2 type-key-quot card-key-quot -- <=> ) hand1 hand2 type-key-quot compare dup +eq+ = [ drop hand1 hand2 [ card-key-quot compare ] { } 2map-as { +eq+ } without ?first dup [ drop +eq+ ] unless ] when ; inline : hand-compare ( hand1 hand2 -- <=> ) [ type-key ] [ card-key ] (hand-compare) ; : input>hand-bids ( -- hand-bids ) "vocab:aoc-2023/day07/input.txt" utf8 file-lines [ " " split1 string>number 2array ] map ; : solve ( hand-compare-quot -- ) '[ [ first ] bi@ @ ] input>hand-bids swap sort-with [ 1 + swap last * ] map-index sum . ; inline : part1 ( -- ) [ hand-compare ] solve ; : card-key-wilds ( ch -- n ) "J23456789TQKA" index ; : type-key-wilds ( hand -- n ) [ type-key ] [ "J" within length ] bi 2array { { { 0 1 } [ 1 ] } { { 1 1 } [ 3 ] } { { 1 2 } [ 3 ] } { { 2 1 } [ 4 ] } { { 2 2 } [ 5 ] } { { 3 1 } [ 5 ] } { { 3 3 } [ 5 ] } { { 4 2 } [ 6 ] } { { 4 3 } [ 6 ] } { { 5 1 } [ 6 ] } { { 5 4 } [ 6 ] } [ first ] } case ; : hand-compare-wilds ( hand1 hand2 -- <=> ) [ type-key-wilds ] [ card-key-wilds ] (hand-compare) ; : part2 ( -- ) [ hand-compare-wilds ] solve ;
[language: Lean4]
As with the previous days: I'll only post the solution and parsing, not the dependencies I've put into separate files. For the full source code, please see github.
The key idea for part 2 was that
Spoiler
it doesn't make any sense to pick different cards for the jokers, and that it's always the highest score to assign all jokers to the most frequent card.
Solution
inductive Card | two | three | four | five | six | seven | eight | nine | ten | jack | queen | king | ace deriving Repr, Ord, BEq inductive Hand | mk : Card → Card → Card → Card → Card → Hand deriving Repr, BEq private inductive Score | highCard | onePair | twoPair | threeOfAKind | fullHouse | fourOfAKind | fiveOfAKind deriving Repr, Ord, BEq -- we need countCards in part 2 again, but there it has different types private class CardList (η : Type) (χ : outParam Type) where cardList : η → List χ -- similarly, we can implement Ord in terms of CardList and Score private class Scorable (η : Type) where score : η → Score private instance : CardList Hand Card where cardList := λ | .mk a b c d e => [a,b,c,d,e] private def countCards {η χ : Type} (input :η) [CardList η χ] [Ord χ] [BEq χ] : List (Nat × χ) := let ordered := (CardList.cardList input).quicksort let helper := λ (a : List (Nat × χ)) (c : χ) ↦ match a with | [] => [(1, c)] | a :: as => if a.snd == c then (a.fst + 1, c) :: as else (1, c) :: a :: as List.quicksortBy (·.fst > ·.fst) $ ordered.foldl helper [] private def evaluateCountedCards : (l : List (Nat × α)) → Score | [_] => Score.fiveOfAKind -- only one entry means all cards are equal | (4,_) :: _ => Score.fourOfAKind | [(3,_), (2,_)] => Score.fullHouse | (3,_) :: _ => Score.threeOfAKind | [(2,_), (2,_), _] => Score.twoPair | (2,_) :: _ => Score.onePair | _ => Score.highCard private def Hand.score (hand : Hand) : Score := evaluateCountedCards $ countCards hand private instance : Scorable Hand where score := Hand.score instance {σ χ : Type} [Scorable σ] [CardList σ χ] [Ord χ] : Ord σ where compare (a b : σ) := let comparedScores := Ord.compare (Scorable.score a) (Scorable.score b) if comparedScores != Ordering.eq then comparedScores else Ord.compare (CardList.cardList a) (CardList.cardList b) private def Card.fromChar? : Char → Option Card | '2' => some Card.two | '3' => some Card.three | '4' => some Card.four | '5' => some Card.five | '6' => some Card.six | '7' => some Card.seven | '8' => some Card.eight | '9' => some Card.nine | 'T' => some Card.ten | 'J' => some Card.jack | 'Q' => some Card.queen | 'K' => some Card.king | 'A' => some Card.ace | _ => none private def Hand.fromString? (input : String) : Option Hand := match input.toList.mapM Card.fromChar? with | some [a, b, c, d, e] => Hand.mk a b c d e | _ => none abbrev Bet := Nat structure Player where hand : Hand bet : Bet deriving Repr def parse (input : String) : Except String (List Player) := do let lines := input.splitOn "\n" |> List.map String.trim |> List.filter String.notEmpty let parseLine := λ (line : String) ↦ if let [hand, bid] := line.split Char.isWhitespace |> List.map String.trim |> List.filter String.notEmpty then Option.zip (Hand.fromString? hand) (String.toNat? bid) |> Option.map (uncurry Player.mk) |> Option.toExcept s!"Line could not be parsed: {line}" else throw s!"Failed to parse. Line did not separate into hand and bid properly: {line}" lines.mapM parseLine def part1 (players : List Player) : Nat := players.quicksortBy (λ p q ↦ p.hand < q.hand) |> List.enumFrom 1 |> List.foldl (λ r p ↦ p.fst * p.snd.bet + r) 0 ------------------------------------------------------------------------------------------------------ -- Again a riddle where part 2 needs different data representation, why are you doing this to me? Why? -- (Though, strictly speaking, I could just add "joker" to the list of cards in part 1 and treat it special) private inductive Card2 | joker | two | three | four | five | six | seven | eight | nine | ten | queen | king | ace deriving Repr, Ord, BEq private def Card.toCard2 : Card → Card2 | .two => Card2.two | .three => Card2.three | .four => Card2.four | .five => Card2.five | .six => Card2.six | .seven => Card2.seven | .eight => Card2.eight | .nine => Card2.nine | .ten => Card2.ten | .jack => Card2.joker | .queen => Card2.queen | .king => Card2.king | .ace => Card2.ace private inductive Hand2 | mk : Card2 → Card2 → Card2 → Card2 → Card2 → Hand2 deriving Repr private def Hand.toHand2 : Hand → Hand2 | Hand.mk a b c d e => Hand2.mk a.toCard2 b.toCard2 c.toCard2 d.toCard2 e.toCard2 instance : CardList Hand2 Card2 where cardList := λ | .mk a b c d e => [a,b,c,d,e] private def Hand2.score (hand : Hand2) : Score := -- I could be dumb here and just let jokers be any other card, but that would be really wasteful -- Also, I'm pretty sure there is no combination that would benefit from jokers being mapped to -- different cards. -- and, even more important, I think we can always map jokers to the most frequent card and are -- still correct. let counted := countCards hand let (jokers, others) := counted.partition λ e ↦ e.snd == Card2.joker let jokersReplaced := match jokers, others with | (jokers, _) :: _ , (a, ac) :: as => (a+jokers, ac) :: as | _ :: _, [] => jokers | [], others => others evaluateCountedCards jokersReplaced private instance : Scorable Hand2 where score := Hand2.score private structure Player2 where bet : Bet hand2 : Hand2 def part2 (players : List Player) : Nat := let players := players.map λ p ↦ {bet := p.bet, hand2 := p.hand.toHand2 : Player2} players.quicksortBy (λ p q ↦ p.hand2 < q.hand2) |> List.enumFrom 1 |> List.foldl (λ r p ↦ p.fst * p.snd.bet + r) 0
Crystal
got stuck on both parts due to silly mistakes.
On the other hand I'm no longer behind!code
input = File.read("input.txt").lines rank = { 'J' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5, '6' => 6, '7' => 7, '8' => 8, '9' => 9, 'T' => 10, # 'J' => 11, 'Q' => 12, 'K' => 13, 'A' => 14 } hand = input.map do |line| split = line.split weights = split[0].chars.map {|c| rank[c]} {weights, split[1].to_i} end hand.sort! do |a, b| a_rank = get_rank(a[0], true) b_rank = get_rank(b[0], true) # puts "#{a}-#{a_rank} #{b}-#{b_rank}" next 1 if a_rank > b_rank next -1 if b_rank > a_rank val = 0 5.times do |i| val = 1 if a[0][i] > b[0][i] val = -1 if b[0][i] > a[0][i] break unless val == 0 end val end sum = 0 hand.each_with_index do |card, i| sum += card[1]*(i+1) end puts sum def get_rank(card : Array(Int32), joker = false ) : Float64 | Int32 aa = card.uniq if joker card = aa.map { |c| combo = card.map {|a| a == 1 ? c : a } {combo, get_rank(combo)} }.max_by {|a| a[1]}[0] aa = card.uniq end rank = 6 - aa.size case rank when 3 return 3.5 if card.count(aa[0]) == 3 return 3 if card.count(aa[0]) == 2 return 3 if card.count(aa[1]) == 2 return 3.5 when 4 return 4 if card.count(aa[0]) == 3 || card.count(aa[0]) == 2 return 4.5 else return rank end end
JavaScript
Ended up misreading the instructions due to trying to go fast. Built up a system to compare hand values like its poker before I realized its not poker
Likely last day im going to be able to write code for due to exams coming up
Code Block
// Part 1 // ====== function part1(input) { const lines = input.replaceAll("\r", "").split("\n"); const hands = lines.map((line) => line.split(" ")); const sortedHands = hands.sort((a, b) => { const handA = calculateHandValue(a[0]); const handB = calculateHandValue(b[0]); if (handA > handB) { return -1; } else if (handA < handB) { return 1; } else { for (let i = 0; i < 5; i++) { const handACard = convertToNumber(a[0].split("")[i]); const handBCard = convertToNumber(b[0].split("")[i]); if (handACard > handBCard) { return 1; } else if (handACard < handBCard) { return -1; } } } }); return sortedHands .filter((hand) => hand[0] != "") .reduce((acc, hand, i) => { return acc + hand[1] * (i + 1); }, 0); } function convertToNumber(card) { switch (card) { case "A": return 14; case "K": return 13; case "Q": return 12; case "J": return 11; case "T": return 10; default: return parseInt(card); } } function calculateHandValue(hand) { const dict = {}; hand.split("").forEach((card) => { if (dict[card]) { dict[card] += 1; } else { dict[card] = 1; } }); // 5 if (Object.keys(dict).length === 1) { return 1; } // 4 if (Object.keys(dict).filter((key) => dict[key] === 4).length === 1) { return 2; } // 3 + 2 if ( Object.keys(dict).filter((key) => dict[key] === 3).length === 1 && Object.keys(dict).filter((key) => dict[key] === 2).length === 1 ) { return 3; } // 3 if (Object.keys(dict).filter((key) => dict[key] === 3).length === 1) { return 4; } // 2 + 2 if (Object.keys(dict).filter((key) => dict[key] === 2).length === 2) { return 5; } // 2 if (Object.keys(dict).filter((key) => dict[key] === 2).length === 1) { return 6; } return 7; } // Part 2 // ====== function part2(input) { const lines = input.replaceAll("\r", "").split("\n"); const hands = lines.map((line) => line.split(" ")); const sortedHands = hands.sort((a, b) => { const handA = calculateHandValuePart2(a[0]); const handB = calculateHandValuePart2(b[0]); if (handA > handB) { return -1; } else if (handA < handB) { return 1; } else { for (let i = 0; i < 5; i++) { const handACard = convertToNumberPart2(a[0].split("")[i]); const handBCard = convertToNumberPart2(b[0].split("")[i]); if (handACard > handBCard) { return 1; } else if (handACard < handBCard) { return -1; } } } }); return sortedHands .filter((hand) => hand[0] != "") .reduce((acc, hand, i) => { console.log(acc, hand, i + 1); return acc + hand[1] * (i + 1); }, 0); } function convertToNumberPart2(card) { switch (card) { case "A": return 14; case "K": return 13; case "Q": return 12; case "J": return 1; case "T": return 10; default: return parseInt(card); } } function calculateHandValuePart2(hand) { const dict = {}; let jokers = 0; hand.split("").forEach((card) => { if (card === "J") { jokers += 1; return; } if (dict[card]) { dict[card] += 1; } else { dict[card] = 1; } }); // 5 if (jokers === 5 || Object.keys(dict).length === 1) { return 1; } // 4 if ( jokers === 4 || (jokers === 3 && Object.keys(dict).filter((key) => dict[key] === 1).length >= 1) || (jokers === 2 && Object.keys(dict).filter((key) => dict[key] === 2).length === 1) || (jokers === 1 && Object.keys(dict).filter((key) => dict[key] === 3).length === 1) || Object.keys(dict).filter((key) => dict[key] === 4).length === 1 ) { return 2; } // 3 + 2 if ( (Object.keys(dict).filter((key) => dict[key] === 3).length === 1 && Object.keys(dict).filter((key) => dict[key] === 2).length === 1) || (Object.keys(dict).filter((key) => dict[key] === 2).length === 2 && jokers === 1) ) { return 3; } // 3 if ( Object.keys(dict).filter((key) => dict[key] === 3).length === 1 || (Object.keys(dict).filter((key) => dict[key] === 2).length === 1 && jokers === 1) || (Object.keys(dict).filter((key) => dict[key] === 1).length >= 1 && jokers === 2) || jokers === 3 ) { return 4; } // 2 + 2 if ( Object.keys(dict).filter((key) => dict[key] === 2).length === 2 || (Object.keys(dict).filter((key) => dict[key] === 2).length === 1 && jokers === 1) ) { return 5; } // 2 if ( Object.keys(dict).filter((key) => dict[key] === 2).length === 1 || jokers ) { return 6; } return 7; } export default { part1, part2 };
Part 1, in C. This took me way too long, there were so many bugs and problems I overlooked. So it's very long.
https://git.sr.ht/~aidenisik/aoc23/tree/master/item/day7
EDIT: And part 2
Python
Also available on Github with all the support code. Questions and feedback welcome!
import collections from .solver import Solver _FIVE_OF_A_KIND = 0x100000 _FOUR_OF_A_KIND = 0x010000 _FULL_HOUSE = 0x001000 _THREE_OF_A_KIND = 0x000100 _TWO_PAIR = 0x000010 _ONE_PAIR = 0x000001 _CARD_ORDER = '23456789TJQKA' _CARD_ORDER_WITH_JOKER = 'J23456789TQKA' def evaluate_hand(hand: str, joker: bool = False) -> int: card_counts = collections.defaultdict(int) score = 0 for card in hand: card_counts[card] += 1 joker_count = 0 if joker: joker_count = card_counts['J'] del card_counts['J'] counts = sorted(card_counts.values(), reverse=True) top_non_joker_count = counts[0] if counts else 0 if top_non_joker_count + joker_count == 5: score |= _FIVE_OF_A_KIND elif top_non_joker_count + joker_count == 4: score |= _FOUR_OF_A_KIND elif top_non_joker_count + joker_count == 3: match counts, joker_count: case [3, 2], 0: score |= _FULL_HOUSE case [3, 1, 1], 0: score |= _THREE_OF_A_KIND case [2, 2], 1: score |= _FULL_HOUSE case [2, 1, 1], 1: score |= _THREE_OF_A_KIND case [1, 1, 1], 2: score |= _THREE_OF_A_KIND case _: raise RuntimeError(f'Unexpected card counts: {counts} with {joker_count} jokers') elif top_non_joker_count + joker_count == 2: match counts, joker_count: case [2, 2, 1], 0: score |= _TWO_PAIR case [2, 1, 1, 1], 0: score |= _ONE_PAIR case [1, 1, 1, 1], 1: score |= _ONE_PAIR case _: raise RuntimeError(f'Unexpected card counts: {counts} with {joker_count} jokers') card_order = _CARD_ORDER_WITH_JOKER if joker else _CARD_ORDER for card in hand: card_value = card_order.index(card) score <<= 4 score |= card_value return score class Day07(Solver): def __init__(self): super().__init__(7) self.hands: list[tuple[str, str]] = [] def presolve(self, input: str): lines = input.rstrip().split('\n') self.hands = list(map(lambda line: line.split(' '), lines)) def solve_first_star(self): hands = self.hands[:] hands.sort(key=lambda hand: evaluate_hand(hand[0])) total_score = 0 for rank, [_, bid] in enumerate(hands): total_score += (rank + 1) * int(bid) return total_score def solve_second_star(self): hands = self.hands[:] hands.sort(key=lambda hand: evaluate_hand(hand[0], True)) total_score = 0 for rank, [_, bid] in enumerate(hands): total_score += (rank + 1) * int(bid) return total_score
Oh boy. bitwise nonsense. Ok, can you explain it to me? I'm terrible at bitwise stuff.
Sure! This generates a number for every hand, so that a better hand gets a higher number. The resulting number will contain 11 hexadecimal digits:
0x100000 bbbbb ^^^^^^ \____ the hand itself |||||\_ 1 if "one pair" ||||\__ 1 if "two pairs" |||\___ 1 if "three of a kind" ||\____ 1 if "full house" |\_____ 1 if "four of a kind" \______ 1 if "five of a kind" For example: AAAAA: 0x100000 bbbbb AAAA2: 0x010000 bbbb0 22233: 0x001000 00011
The hand itself is 5 hexadecimal digits for every card, 0 for "2" to b for "ace".
This way the higher combination always has a higher number, and hands with the same combination are ordered by the order of the cards in the hand.
That is a really cool solution. Thanks for the explanation! I took a much more... um... naive path lol.
I think you have the same solution, basically, just the details are a bit different. I like how you handled the joker, I didn't realise you could just multiply your best streak of cards to get the best possible combination.
I didn't multiply the streak, I just took the jokers and added them to the highest hand already in the list. Is that not what you did? It looked the same to me.
This is what I meant, but I phrased it poorly :)
In my solution I reimplement the logic of identifying the hand value, but with the presence of joker (instead of just reusing the same logic).
Two days, a few failed solutions, some misread instructions, and a lot of manually parsing output data and debugging silly tiny mistakes... but it's finally done. I don't really wanna talk about it.
https://github.com/capitalpb/advent_of_code_2023/blob/main/src/solvers/day07.rs
use crate::Solver; use itertools::Itertools; use std::cmp::Ordering; #[derive(Clone, Copy)] enum JType { Jokers = 1, Jacks = 11, } #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)] enum HandType { HighCard, OnePair, TwoPair, ThreeOfAKind, FullHouse, FourOfAKind, FiveOfAKind, } #[derive(Debug, Eq, PartialEq)] struct CardHand { hand: Vec, bid: u64, hand_type: HandType, } impl CardHand { fn from(input: &str, j_type: JType) -> CardHand { let (hand, bid) = input.split_once(' ').unwrap(); let hand = hand .chars() .map(|card| match card { '2'..='9' => card.to_digit(10).unwrap() as u64, 'T' => 10, 'J' => j_type as u64, 'Q' => 12, 'K' => 13, 'A' => 14, _ => unreachable!("malformed input"), }) .collect::>(); let bid = bid.parse::().unwrap(); let counts = hand.iter().counts(); let hand_type = match counts.len() { 1 => HandType::FiveOfAKind, 2 => { if hand.contains(&1) { HandType::FiveOfAKind } else { if counts.values().contains(&4) { HandType::FourOfAKind } else { HandType::FullHouse } } } 3 => { if counts.values().contains(&3) { if hand.contains(&1) { HandType::FourOfAKind } else { HandType::ThreeOfAKind } } else { if counts.get(&1) == Some(&2) { HandType::FourOfAKind } else if counts.get(&1) == Some(&1) { HandType::FullHouse } else { HandType::TwoPair } } } 4 => { if hand.contains(&1) { HandType::ThreeOfAKind } else { HandType::OnePair } } _ => { if hand.contains(&1) { HandType::OnePair } else { HandType::HighCard } } }; CardHand { hand, bid, hand_type, } } } impl PartialOrd for CardHand { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl Ord for CardHand { fn cmp(&self, other: &Self) -> Ordering { let hand_type_cmp = self.hand_type.cmp(&other.hand_type); if hand_type_cmp != Ordering::Equal { return hand_type_cmp; } else { for i in 0..5 { let value_cmp = self.hand[i].cmp(&other.hand[i]); if value_cmp != Ordering::Equal { return value_cmp; } } } Ordering::Equal } } pub struct Day07; impl Solver for Day07 { fn star_one(&self, input: &str) -> String { input .lines() .map(|line| CardHand::from(line, JType::Jacks)) .sorted() .enumerate() .map(|(index, hand)| hand.bid * (index as u64 + 1)) .sum::() .to_string() } fn star_two(&self, input: &str) -> String { input .lines() .map(|line| CardHand::from(line, JType::Jokers)) .sorted() .enumerate() .map(|(index, hand)| hand.bid * (index as u64 + 1)) .sum::() .to_string() } }