From db2686c798378738020a0951a521358586e21aa0 Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Fri, 9 Feb 2024 11:42:04 +0100 Subject: Add day2 in OCaml --- 2023/rust/day8/src/lib.rs | 115 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 2023/rust/day8/src/lib.rs (limited to '2023/rust/day8/src') diff --git a/2023/rust/day8/src/lib.rs b/2023/rust/day8/src/lib.rs new file mode 100644 index 0000000..31f2e2c --- /dev/null +++ b/2023/rust/day8/src/lib.rs @@ -0,0 +1,115 @@ +use std::collections::HashMap; + +pub fn part1(input: &str) -> u32 { + let mut res: u32 = 0; + + let lines: Vec = input + .trim_end() + .split('\n') + .map(|x| x.to_string()) + .collect(); + let ltype = &lines[0]; + let mut hm: HashMap = HashMap::new(); + for play in &lines[2..] { + hm.insert( + play[..3].to_string(), + (play[7..10].to_string(), play[12..15].to_string()), + ); + } + + let mut current = "AAA".to_string(); + for i in ltype.chars().cycle() { + current = match i { + 'R' => hm.get(¤t).unwrap().1.clone(), + 'L' => hm.get(¤t).unwrap().0.clone(), + _ => panic!("wtf is this?"), + }; + res += 1; + + if current == "ZZZ".to_string() { + break; + } + } + + res +} + +pub fn part2(input: &str) -> u32 { + let mut res: u32 = 0; + + let lines: Vec = input + .trim_end() + .split('\n') + .map(|x| x.to_string()) + .collect(); + let ltype = &lines[0]; + let mut hm: HashMap = HashMap::new(); + + for play in &lines[2..] { + hm.insert( + play[..3].to_string(), + (play[7..10].to_string(), play[12..15].to_string()), + ); + } + + let mut currents: Vec = hm + .keys() + .filter(|x| x.ends_with("A")) + .into_iter() + .map(|x| x.to_string()) + .collect::>(); + + dbg!("{currents:?}"); + 'o: for i in ltype.chars().cycle() { + for k in 0..currents.len() { + currents[k] = match i { + 'R' => hm.get(¤ts[k]).unwrap().1.clone(), + 'L' => hm.get(¤ts[k]).unwrap().0.clone(), + _ => panic!("wtf is this?"), + }; + res += 1; + } + + for current in ¤ts { + if !current.ends_with("Z") { + continue 'o; + } + } + break; + } + + res +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn example_part1() { + let input = include_str!("../example.txt"); + let result = part1(input); + assert_eq!(result, 2); + } + + #[test] + fn input_part1() { + let input = include_str!("../input.txt"); + let result = part1(input); + assert_eq!(result, 21389); + } + + #[test] + fn example_part2() { + let input = include_str!("../example2.txt"); + let result = part2(input); + assert_eq!(result, 12); + } + + // #[test] + // fn input_part2() { + // let input = include_str!("../input.txt"); + // let result = part2(input); + // assert_eq!(result, 248179786); + // } +} -- cgit v1.2.3-18-g5258