diff --git a/src/bin/day03.rs b/src/bin/day03.rs index ed511db..508504f 100644 --- a/src/bin/day03.rs +++ b/src/bin/day03.rs @@ -1,25 +1,53 @@ use std::collections::HashSet; +use std::str::FromStr; use aoc_2022::*; -use color_eyre::eyre::Result; +use color_eyre::eyre::{Report, Result}; use tracing::*; use tracing_subscriber::EnvFilter; -type Input = Vec<(HashSet, HashSet)>; +struct Backpack(HashSet, HashSet); + +type Input = Vec; type Output = i32; +impl FromStr for Backpack { + type Err = Report; + + fn from_str(s: &str) -> Result { + let mut left: HashSet = HashSet::new(); + let mut right: HashSet = HashSet::new(); + + let mid = s.len() / 2; + for (i, c) in s.chars().enumerate() { + let s = if i < mid { &mut left } else { &mut right }; + + s.insert( + c as i32 + + if c.is_ascii_lowercase() { + 1 - 'a' as i32 + } else { + 27 - 'A' as i32 + }, + ); + } + + Ok(Backpack(left, right)) + } +} + fn part_1(input: &Input) -> Output { input .iter() - .map(|(left, right)| left.intersection(right).sum::()) + .map(|Backpack(left, right)| left.intersection(right).sum::()) .sum() } fn part_2(input: &Input) -> Output { input .iter() - .map(|(left, right)| left.union(right).cloned().collect()) + .map(|Backpack(left, right)| left.union(right).cloned().collect()) .collect::>>() .chunks(3) .map(|sets| { @@ -36,26 +64,7 @@ fn part_2(input: &Input) -> Output { } fn parse_input(pathname: &str) -> Input { - file_to_lines(pathname) - .iter() - .map(|line| { - let mut left: HashSet = HashSet::new(); - let mut right: HashSet = HashSet::new(); - - let mid = line.len() / 2; - for (i, c) in line.chars().enumerate() { - let s = if i < mid { &mut left } else { &mut right }; - - s.insert(if c < 'a' { - c as i32 - 'A' as i32 + 27 - } else { - c as i32 - 'a' as i32 + 1 - }); - } - - (left, right) - }) - .collect() + file_to_structs(pathname) } fn main() -> Result<()> {