aboutsummaryrefslogtreecommitdiffstats
path: root/AoC2022
diff options
context:
space:
mode:
authorOscar Najera <hi@oscarnajera.com>2022-12-04 21:18:46 +0100
committerOscar Najera <hi@oscarnajera.com>2022-12-04 21:18:46 +0100
commitc91c280211b7706561d97c8131600398063c7527 (patch)
tree32c52400e649f1f6822b3b5a4a44cf455d6ad350 /AoC2022
parent11cf813afa9c60d7404dc09bd0a72ea95e1a5268 (diff)
downloadscratch-c91c280211b7706561d97c8131600398063c7527.tar.gz
scratch-c91c280211b7706561d97c8131600398063c7527.tar.bz2
scratch-c91c280211b7706561d97c8131600398063c7527.zip
[AoC2022] Rust 03
Diffstat (limited to 'AoC2022')
-rw-r--r--AoC2022/03/makefile2
-rw-r--r--AoC2022/03/solver.rs68
2 files changed, 69 insertions, 1 deletions
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.")
+}