blob: df5dead3aabc75f65e17de933f9e907c1ec9a18d (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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(())
}
|