2022 day3/rust: cleanup

This commit is contained in:
Xiretza 2022-12-03 06:29:32 +01:00
parent 5ad4f56771
commit c4268a0093

View file

@ -7,38 +7,52 @@ 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!(),
_ => panic!("invalid item {item}"),
}
}
struct Rucksack {
left: HashSet<char>,
right: HashSet<char>,
}
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 sacks: Vec<_> = data
.lines()
.map(|line| {
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 left: HashSet<_> = left.chars().collect();
let right: HashSet<_> = right.chars().collect();
let common = *left.intersection(&right).next().unwrap();
sum += item_priority(common);
}
Rucksack { left, right }
})
.collect();
println!("{}", sum);
let sum1: u32 = sacks
.iter()
.map(|sack| item_priority(*sack.left.intersection(&sack.right).next().unwrap()))
.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);
let sum2: u32 = sacks
.chunks(3)
.into_iter()
.map(|sacks| {
let common = sacks
.iter()
.map(|sack| &sack.left | &sack.right)
.reduce(|a, b| &a & &b)
.unwrap();
assert_eq!(common.len(), 1);
sum += item_priority(common.into_iter().next().unwrap());
}
println!("{}", sum);
item_priority(common.into_iter().next().unwrap())
})
.sum();
println!("{}", sum1);
println!("{}", sum2);
}