diff options
Diffstat (limited to '2023/day07.rs')
| -rw-r--r-- | 2023/day07.rs | 112 |
1 files changed, 112 insertions, 0 deletions
diff --git a/2023/day07.rs b/2023/day07.rs new file mode 100644 index 0000000..eeb0763 --- /dev/null +++ b/2023/day07.rs @@ -0,0 +1,112 @@ +#![allow(dead_code)] +#![allow(unused_variables)] +#![allow(unused_mut)] +use std::cmp::Ordering; +use std::fs::File; +use std::io::Read; + +#[derive(Debug)] +struct Hand { + cards: Vec<u8>, + bid: u32, +} + +fn count_cards(arr: &Vec<u8>) -> Vec<u32> { + let mut count = [0; 256].to_vec(); + for a in arr { + count[*a as usize] += 1; + } + let mut count = count + .iter() + .filter(|x| **x != 0) + .copied() + .collect::<Vec<_>>(); + count.sort(); + count.reverse(); + count +} + +fn card_type(count: &Vec<u32>) -> u32 { + // returns card type from card count + if count[0] == 5 { + return 6; + } else if count[0] == 4 { + return 5; + } else if count[0] == 3 && count[1] == 2 { + return 4; + } else if count[0] == 3 { + return 3; + } else if count[0] == 2 && count[1] == 2 { + return 2; + } else if count[0] == 2 { + return 1; + } else { + return 0; + } +} + +fn compare_cards(c1: &Vec<u8>, c2: &Vec<u8>) -> Ordering { + let count1 = count_cards(c1); + let count2 = count_cards(c2); + let type1 = card_type(&count1); + let type2 = card_type(&count2); + + if type1 > type2 { + return Ordering::Greater; + } else if type1 < type2 { + return Ordering::Less; + } else { + for (e1, e2) in c1.iter().zip(c2.iter()) { + // println!("{} {} {}", e1, e2, e1 > d2); + if e1 > e2 { + return Ordering::Greater; + } else if e1 < e2 { + return Ordering::Less; + } + } + } + Ordering::Equal +} + +fn string_to_card(s: &str) -> Vec<u8> { + let map = [ + '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A', + ]; + let mut out = Vec::new(); + for c in s.chars() { + out.push(map.iter().position(|x| x == &c).unwrap() as u8); + } + out +} + +fn main() { + // let filename = "in/day07.ref"; + let filename = "in/day07.pzl"; + + let mut f = File::open(filename).expect("cannot open file"); + let mut content = String::new(); + f.read_to_string(&mut content).expect("cannot read file"); + let lines: Vec<_> = content.trim_end().split('\n').collect(); + // println!("{:?}", lines); + + let mut hands: Vec<Hand> = Vec::new(); + for line in lines.iter() { + let (cards, bid) = line.split_once(" ").unwrap(); + hands.push(Hand { + cards: string_to_card(cards), + bid: bid.parse().unwrap(), + }); + } + + hands.sort_unstable_by(|x, y| compare_cards(&x.cards, &y.cards)); + + let mut res1 = 0; + for (i, h) in hands.iter().enumerate() { + res1 += (i as u32 + 1) * h.bid; + } + + let mut res2 = 0; + + println!("res1: {}", res1); + println!("res2: {}", res2); +} |
