From c91c280211b7706561d97c8131600398063c7527 Mon Sep 17 00:00:00 2001 From: Oscar Najera Date: Sun, 4 Dec 2022 21:18:46 +0100 Subject: [AoC2022] Rust 03 --- AoC2022/03/makefile | 2 +- AoC2022/03/solver.rs | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 1 deletion(-) create mode 100644 AoC2022/03/solver.rs diff --git a/AoC2022/03/makefile b/AoC2022/03/makefile index abcd94b..f781686 100644 --- a/AoC2022/03/makefile +++ b/AoC2022/03/makefile @@ -11,4 +11,4 @@ run: emacs -batch -l ert -l solver.el -f ert-run-tests-batch-and-exit # sbcl --load ~/.sbclrc --script solver.lisp - # rustc solver.rs && ./solver + rustc solver.rs && ./solver 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.") +} -- cgit v1.2.3