use std::{
fs::File,
io::{BufRead, BufReader},
path::Path,
};
pub fn solve(input: &Path) -> anyhow::Result<()> {
println!("part one: {}", part_one(input)?);
println!("part two: {}", part_two(input)?);
Ok(())
}
fn part_one(input: &Path) -> anyhow::Result<i32> {
let reader = BufReader::new(File::open(input)?);
let mut first: Vec<i32> = vec![];
let mut second: Vec<i32> = vec![];
for line in reader.lines() {
let line = line?;
let mut numbers = line.split_whitespace();
first.push(numbers.next().unwrap().parse()?);
second.push(numbers.next().unwrap().parse()?);
}
first.sort();
second.sort();
let mut answer = 0;
for (i, f) in first.into_iter().enumerate() {
answer += (f - second[i]).abs();
}
Ok(answer)
}
fn part_two(input: &Path) -> anyhow::Result<i32> {
let reader = BufReader::new(File::open(input)?);
let mut first: Vec<i32> = vec![];
let mut second: Vec<i32> = vec![];
for line in reader.lines() {
let line = line?;
let mut numbers = line.split_whitespace();
first.push(numbers.next().unwrap().parse()?);
second.push(numbers.next().unwrap().parse()?);
}
let mut answer = 0;
for f in first {
let amount = second
.clone()
.into_iter()
.filter(|&s| s == f)
.collect::<Vec<i32>>()
.len();
answer += f * amount as i32;
}
Ok(answer)
}