From 7b53b318da4d61c88f9676a49e6ef0766116bd1a Mon Sep 17 00:00:00 2001 From: nekineki Date: Thu, 7 Dec 2023 20:59:08 +0100 Subject: day07 derive Ord --- 2023/day07.rs | 38 ++++++++++---------------------------- 1 file changed, 10 insertions(+), 28 deletions(-) diff --git a/2023/day07.rs b/2023/day07.rs index 24635b3..e65748d 100644 --- a/2023/day07.rs +++ b/2023/day07.rs @@ -1,11 +1,10 @@ -use std::cmp::Ordering; use std::fs::File; use std::io::Read; -#[derive(Debug)] +#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)] struct Hand { + typ: u32, cards: Vec, - ct: u32, bid: u32, } @@ -30,11 +29,11 @@ fn card_type(count: &Vec) -> u32 { return 6; } else if count[0] == 4 { return 5; - } else if count[0] == 3 && count[1] == 2 { + } else if count[0..2] == [3, 2] { return 4; } else if count[0] == 3 { return 3; - } else if count[0] == 2 && count[1] == 2 { + } else if count[0..2] == [2, 2] { return 2; } else if count[0] == 2 { return 1; @@ -59,23 +58,6 @@ fn get_card_type2(c: &Vec) -> u32 { card_type(&count) } -fn compare_hands(h1: &Hand, h2: &Hand) -> Ordering { - if h1.ct > h2.ct { - return Ordering::Greater; - } else if h1.ct < h2.ct { - return Ordering::Less; - } else { - for (e1, e2) in h1.cards.iter().zip(h2.cards.iter()) { - if e1 > e2 { - return Ordering::Greater; - } else if e1 < e2 { - return Ordering::Less; - } - } - } - Ordering::Equal -} - fn string_to_card(s: &str, map: &[char]) -> Vec { s.chars() .map(|c| map.iter().position(|x| x == &c).unwrap() as u8) @@ -108,26 +90,26 @@ fn main() { hands1.push(Hand { cards: cards1.clone(), bid: bid.parse().unwrap(), - ct: get_card_type1(&cards1), + typ: get_card_type1(&cards1), }); hands2.push(Hand { cards: cards2.clone(), bid: bid.parse().unwrap(), - ct: get_card_type2(&cards2), + typ: get_card_type2(&cards2), }); } - hands1.sort_by(compare_hands); + hands1.sort(); let mut res1 = 0; for (i, h) in hands1.iter().enumerate() { - // println!("{:?} {}", h.cards, h.ct); + // println!("{:?} {}", h.cards, h.typ); res1 += (i as u32 + 1) * h.bid; } - hands2.sort_by(compare_hands); + hands2.sort(); let mut res2 = 0; for (i, h) in hands2.iter().enumerate() { - // println!("{:?} {}", h.cards, h.ct); + // println!("{:?} {}", h.cards, h.typ); res2 += (i as u32 + 1) * h.bid; } -- cgit v1.2.3