diff options
author | Santo Cariotti <santo@dcariotti.me> | 2024-02-09 11:42:04 +0100 |
---|---|---|
committer | Santo Cariotti <santo@dcariotti.me> | 2024-02-09 11:42:04 +0100 |
commit | db2686c798378738020a0951a521358586e21aa0 (patch) | |
tree | 8d585ceb9bdc302ae10a2458cc343be40d60acb7 /2023/rust/day8/src | |
parent | 67dff579e91c13ef40ecb17d14497d145861c5e7 (diff) |
Add day2 in OCaml
Diffstat (limited to '2023/rust/day8/src')
-rw-r--r-- | 2023/rust/day8/src/lib.rs | 115 |
1 files changed, 115 insertions, 0 deletions
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<String> = input + .trim_end() + .split('\n') + .map(|x| x.to_string()) + .collect(); + let ltype = &lines[0]; + let mut hm: HashMap<String, (String, String)> = 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<String> = input + .trim_end() + .split('\n') + .map(|x| x.to_string()) + .collect(); + let ltype = &lines[0]; + let mut hm: HashMap<String, (String, String)> = 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<String> = hm + .keys() + .filter(|x| x.ends_with("A")) + .into_iter() + .map(|x| x.to_string()) + .collect::<Vec<String>>(); + + 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); + // } +} |