diff options
Diffstat (limited to 'AoC2022/03/solver.rs')
-rw-r--r-- | AoC2022/03/solver.rs | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/AoC2022/03/solver.rs b/AoC2022/03/solver.rs new file mode 100644 index 0000000..21a02c9 --- /dev/null +++ b/AoC2022/03/solver.rs @@ -0,0 +1,68 @@ +use std::fs; +use std::io::{self, BufRead}; + +fn badge_find(items: &[u8]) -> u64 { + items + .iter() + .fold(0, |badge, &item| badge | 1 << (item - 64)) +} + +fn repetition_find(items: &[u8]) -> u32 { + let len = items.len() / 2; + let left_pack = &items[..len]; + let right_pack = &items[len..]; + let (mut left, mut right) = (0u64, 0u64); + let mut total = 0; + + for i in 0..len { + left |= 1 << left_pack[i] - 64; + right |= 1 << right_pack[i] - 64; + let cross = left & right; + if cross > 0 { + total += priority(cross); + break; + } + } + total +} +fn priority(item: u64) -> u32 { + let item = item.trailing_zeros(); + if item < 32 { + item + 26 + } else { + item - 32 + } +} + +fn solve_prio() -> u32 { + let file = fs::File::open("input").unwrap(); + let lines = io::BufReader::new(file).lines(); + let mut total = 0; + for line in lines { + total += repetition_find(line.unwrap().as_bytes()); + } + total +} +fn solve_badge() -> u32 { + let file = fs::File::open("input").unwrap(); + let lines = io::BufReader::new(file).lines(); + let mut total = 0; + let mut badge = u64::MAX; + let mut grouper = 0; + + for line in lines { + let items = line.unwrap(); + badge &= badge_find(items.as_bytes()); + grouper += 1; + if grouper % 3 == 0 { + total += priority(badge); + badge = u64::MAX; + } + } + total +} +fn main() { + assert_eq!(8072, solve_prio()); + assert_eq!(2567, solve_badge()); + println!("All test passed.") +} |