2022-12-03 06:16:52 +01:00
|
|
|
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,
|
2022-12-03 06:29:32 +01:00
|
|
|
_ => panic!("invalid item {item}"),
|
2022-12-03 06:16:52 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-03 06:29:32 +01:00
|
|
|
struct Rucksack {
|
|
|
|
left: HashSet<char>,
|
|
|
|
right: HashSet<char>,
|
|
|
|
}
|
|
|
|
|
2022-12-03 06:16:52 +01:00
|
|
|
fn main() {
|
|
|
|
let mut data = String::new();
|
|
|
|
stdin().read_to_string(&mut data).unwrap();
|
|
|
|
|
2022-12-03 06:29:32 +01:00
|
|
|
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();
|
|
|
|
|
|
|
|
Rucksack { left, right }
|
|
|
|
})
|
|
|
|
.collect();
|
|
|
|
|
|
|
|
let sum1: u32 = sacks
|
|
|
|
.iter()
|
|
|
|
.map(|sack| item_priority(*sack.left.intersection(&sack.right).next().unwrap()))
|
|
|
|
.sum();
|
|
|
|
|
|
|
|
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);
|
|
|
|
|
|
|
|
item_priority(common.into_iter().next().unwrap())
|
|
|
|
})
|
|
|
|
.sum();
|
|
|
|
|
|
|
|
println!("{}", sum1);
|
|
|
|
println!("{}", sum2);
|
2022-12-03 06:16:52 +01:00
|
|
|
}
|