aoc2022/day3/src/main.rs
2022-12-03 13:49:36 +01:00

48 lines
1.4 KiB
Rust

use std::{collections::HashSet, fs::read_to_string};
use color_eyre::{eyre::*, Result};
use itertools::Itertools;
fn priority(item: &char) -> usize {
('a'..='z')
.position(|c| *item == c)
.map(|i| i + 1)
.or_else(|| ('A'..='Z').position(|c| *item == c).map(|i| i + 27))
.unwrap_or(0)
}
fn initial(input: &str) -> (usize, usize) {
let output1 = input
.lines()
.map(|line| {
let (compartment1, compartment2) = line.split_at(line.len() / 2);
let compartment1 = compartment1.chars().collect::<HashSet<_>>();
let compartment2 = compartment2.chars().collect::<HashSet<_>>();
compartment1
.intersection(&compartment2)
.map(priority)
.sum::<usize>()
})
.sum();
let output2 = input
.lines()
.chunks(3)
.into_iter()
.map(|group| {
group
.map(|line| line.chars().collect::<HashSet<_>>())
.coalesce(|a, b| Ok(a.intersection(&b).copied().collect()))
.map(|set| set.iter().map(priority).sum::<usize>())
.sum::<usize>()
})
.sum();
(output1, output2)
}
fn main() -> Result<()> {
let input = read_to_string("input.txt").wrap_err("reading input.txt")?;
let output = initial(&input);
println!("output: {output:?}");
Ok(())
}