diff options
author | Tomasz Kramkowski <tomasz@kramkow.ski> | 2024-12-01 11:59:08 +0000 |
---|---|---|
committer | Tomasz Kramkowski <tomasz@kramkow.ski> | 2024-12-01 11:59:08 +0000 |
commit | 9c340e9288d5ad90fa7d582ccafc15c61e985246 (patch) | |
tree | 489049ae4aff78796e8827e3b0980a7d37cedacd /src | |
parent | 464400a609636cb8fd172610b4d5f391b2c0bb71 (diff) | |
download | aoc2024-9c340e9288d5ad90fa7d582ccafc15c61e985246.tar.gz aoc2024-9c340e9288d5ad90fa7d582ccafc15c61e985246.tar.xz aoc2024-9c340e9288d5ad90fa7d582ccafc15c61e985246.zip |
Day 1
Diffstat (limited to 'src')
-rw-r--r-- | src/bin/1.rs | 41 |
1 files changed, 41 insertions, 0 deletions
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<dyn Error>> { + let f = File::open("input/1")?; + let f = BufReader::new(f); + let mut list_a: Vec<i64> = Vec::new(); + let mut list_b: Vec<i64> = 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::<i64>() + ); + let mut frequencies: HashMap<i64, i64> = 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::<i64>() + ); + Ok(()) +} |