use std::{ collections::HashMap, error::Error, fs::File, io::{BufRead, BufReader}, }; fn main() -> Result<(), Box> { let f = File::open("input/1")?; let f = BufReader::new(f); let mut list_a: Vec = Vec::new(); let mut list_b: Vec = Vec::new(); for line in f.lines() { let line = line?; let (a, b) = line.trim_end().split_once(" ").ok_or("Invalid line")?; list_a.push(a.parse()?); list_b.push(b.parse()?); } list_a.sort(); list_b.sort(); println!( "part1: {}", list_a .iter() .zip(list_b.iter()) .map(|p| (p.0 - p.1).abs()) .sum::() ); let mut frequencies: HashMap = HashMap::new(); for n in list_b { *frequencies.entry(n).or_default() += 1; } println!( "part2: {}", list_a .into_iter() .map(|n| n * frequencies.get(&n).copied().unwrap_or_default()) .sum::() ); Ok(()) }