From 5ad4f56771500c7caa34cd41e409f201cd08c331 Mon Sep 17 00:00:00 2001 From: Xiretza Date: Sat, 3 Dec 2022 06:16:52 +0100 Subject: [PATCH] 2022 day3/rust: add solution --- 2022/day3/rust/Cargo.toml | 8 +++++++ 2022/day3/rust/src/main.rs | 44 ++++++++++++++++++++++++++++++++++++++ Cargo.lock | 4 ++++ Cargo.toml | 1 + 4 files changed, 57 insertions(+) create mode 100644 2022/day3/rust/Cargo.toml create mode 100644 2022/day3/rust/src/main.rs diff --git a/2022/day3/rust/Cargo.toml b/2022/day3/rust/Cargo.toml new file mode 100644 index 0000000..d3718db --- /dev/null +++ b/2022/day3/rust/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "rust_2022_03" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/2022/day3/rust/src/main.rs b/2022/day3/rust/src/main.rs new file mode 100644 index 0000000..c8ff686 --- /dev/null +++ b/2022/day3/rust/src/main.rs @@ -0,0 +1,44 @@ +use std::{ + collections::HashSet, + io::{stdin, Read}, +}; + +fn item_priority(item: char) -> u32 { + match item { + 'a'..='z' => item as u32 - 'a' as u32 + 1, + 'A'..='Z' => item as u32 - 'A' as u32 + 27, + _ => unreachable!(), + } +} + +fn main() { + let mut data = String::new(); + stdin().read_to_string(&mut data).unwrap(); + + let mut sum = 0; + for line in data.lines() { + let (left, right) = line.split_at(line.len() / 2); + assert_eq!(left.len(), right.len()); + + let left: HashSet<_> = left.chars().collect(); + let right: HashSet<_> = right.chars().collect(); + + let common = *left.intersection(&right).next().unwrap(); + sum += item_priority(common); + } + + println!("{}", sum); + + let mut sum = 0; + for lines in data.lines().collect::>().chunks(3) { + let common = lines + .iter() + .map(|line| line.chars().collect::>()) + .reduce(|l, r| &l & &r) + .unwrap(); + assert_eq!(common.len(), 1); + + sum += item_priority(common.into_iter().next().unwrap()); + } + println!("{}", sum); +} diff --git a/Cargo.lock b/Cargo.lock index 71b3503..f73a21a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -469,6 +469,10 @@ version = "0.1.0" name = "rust_2022_02" version = "0.1.0" +[[package]] +name = "rust_2022_03" +version = "0.1.0" + [[package]] name = "ryu" version = "1.0.11" diff --git a/Cargo.toml b/Cargo.toml index e7ea83a..5e2892a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,4 +11,5 @@ members = [ "2021/day22/rust", "2022/day1/rust", "2022/day2/rust", + "2022/day3/rust", ]