2022 day3/rust: add solution
This commit is contained in:
parent
f2f3697152
commit
5ad4f56771
4 changed files with 57 additions and 0 deletions
8
2022/day3/rust/Cargo.toml
Normal file
8
2022/day3/rust/Cargo.toml
Normal 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]
|
44
2022/day3/rust/src/main.rs
Normal file
44
2022/day3/rust/src/main.rs
Normal 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
4
Cargo.lock
generated
|
@ -469,6 +469,10 @@ version = "0.1.0"
|
||||||
name = "rust_2022_02"
|
name = "rust_2022_02"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rust_2022_03"
|
||||||
|
version = "0.1.0"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ryu"
|
name = "ryu"
|
||||||
version = "1.0.11"
|
version = "1.0.11"
|
||||||
|
|
|
@ -11,4 +11,5 @@ members = [
|
||||||
"2021/day22/rust",
|
"2021/day22/rust",
|
||||||
"2022/day1/rust",
|
"2022/day1/rust",
|
||||||
"2022/day2/rust",
|
"2022/day2/rust",
|
||||||
|
"2022/day3/rust",
|
||||||
]
|
]
|
||||||
|
|
Loading…
Reference in a new issue