this post was submitted on 07 Dec 2023
18 points (100.0% liked)

Advent Of Code

768 readers
1 users here now

An unofficial home for the advent of code community on programming.dev!

Advent of Code is an annual Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved in any programming language you like.

AoC 2023

Solution Threads

M T W T F S S
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25

Rules/Guidelines

Relevant Communities

Relevant Links

Credits

Icon base by Lorc under CC BY 3.0 with modifications to add a gradient

console.log('Hello World')

founded 1 year ago
MODERATORS
 

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


๐Ÿ”’ Thread is locked until there's at least 100 2 star entries on the global leaderboard

๐Ÿ”“ Thread has been unlocked after around 20 mins

you are viewing a single comment's thread
view the rest of the comments
[โ€“] [email protected] 1 points 11 months ago

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()
    }
}