2022 day3/rust: add solution

This commit is contained in:
Xiretza 2022-12-03 06:16:52 +01:00
parent f2f3697152
commit 5ad4f56771
4 changed files with 57 additions and 0 deletions

View file

@ -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]

View file

@ -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::<Vec<_>>().chunks(3) {
let common = lines
.iter()
.map(|line| line.chars().collect::<HashSet<_>>())
.reduce(|l, r| &l & &r)
.unwrap();
assert_eq!(common.len(), 1);
sum += item_priority(common.into_iter().next().unwrap());
}
println!("{}", sum);
}

4
Cargo.lock generated
View file

@ -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"

View file

@ -11,4 +11,5 @@ members = [
"2021/day22/rust",
"2022/day1/rust",
"2022/day2/rust",
"2022/day3/rust",
]