From 9c340e9288d5ad90fa7d582ccafc15c61e985246 Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Sun, 1 Dec 2024 11:59:08 +0000 Subject: Day 1 --- src/bin/1.rs | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/bin/1.rs (limited to 'src') diff --git a/src/bin/1.rs b/src/bin/1.rs new file mode 100644 index 0000000..df5dead --- /dev/null +++ b/src/bin/1.rs @@ -0,0 +1,41 @@ +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(()) +} -- cgit v1.2.3-54-g00ecf