Created
December 7, 2023 19:10
-
-
Save rondreas/7a0c65bda7881029b4700cf7f4cc88c6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::collections::HashSet; | |
#[derive(Debug, Eq, Ord, PartialEq, PartialOrd)] | |
enum HandType { | |
HighCard, | |
OnePair, | |
TwoPair, | |
ThreeOfAKind, | |
FullHouse, | |
FourOfAKind, | |
FiveOfAKind, | |
} | |
#[derive(Debug, Eq, Ord, PartialEq, PartialOrd)] | |
struct Hand { | |
hand_type: HandType, | |
cards: [u8; 5], | |
bid: u32, | |
} | |
impl Hand { | |
fn new(cards: [u8; 5], bid: u32) -> Hand { | |
let unique_cards = HashSet::from(cards); | |
let mut counts: Vec<usize> = Vec::with_capacity(5); | |
for card in unique_cards { | |
let count = cards.iter().filter(|&c| *c == card).count(); | |
counts.push(count); | |
} | |
counts.sort(); | |
let mut hand_type = HandType::HighCard; | |
match counts[..] { | |
[5] => hand_type = HandType::FiveOfAKind, | |
[1, 4] => hand_type = HandType::FourOfAKind, | |
[2, 3] => hand_type = HandType::FullHouse, | |
[1, 1, 3] => hand_type = HandType::ThreeOfAKind, | |
[1, 2, 2] => hand_type = HandType::TwoPair, | |
[1, 1, 1, 2] => hand_type = HandType::OnePair, | |
_ => (), | |
} | |
Hand{ | |
hand_type, | |
cards, | |
bid, | |
} | |
} | |
} | |
fn main() { | |
let input = include_str!("input.txt"); | |
let mut hands: Vec<Hand> = Vec::with_capacity(input.lines().count()); | |
for line in input.lines() { | |
let (cards, bid) = line.split_once(' ').unwrap(); | |
// map the cards to a values, | |
let mut arr = [0u8; 5]; | |
for (i,c) in cards.chars().enumerate() { | |
match c { | |
'2' => arr[i] = 1, | |
'3' => arr[i] = 2, | |
'4' => arr[i] = 3, | |
'5' => arr[i] = 4, | |
'6' => arr[i] = 5, | |
'7' => arr[i] = 6, | |
'8' => arr[i] = 7, | |
'9' => arr[i] = 8, | |
'T' => arr[i] = 9, | |
'J' => arr[i] = 10, | |
'Q' => arr[i] = 11, | |
'K' => arr[i] = 12, | |
'A' => arr[i] = 13, | |
_ => panic!("Invalid card {c}"), | |
} | |
} | |
let bid = bid.parse::<u32>().unwrap(); | |
let hand = Hand::new(arr, bid); | |
hands.push(hand); | |
} | |
hands.sort(); | |
let bids: Vec<u32> = hands | |
.iter() | |
.enumerate() | |
.map(|(i, hand)| hand.bid * (i as u32 + 1)) | |
.collect(); | |
println!("Part one: {}", bids.iter().sum::<u32>()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment