Day1
This commit is contained in:
parent
efd8d34727
commit
02044a65fb
3 changed files with 95 additions and 0 deletions
78
src/bin/day1.rs
Normal file
78
src/bin/day1.rs
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
use std::{collections::HashMap, time::Instant};
|
||||
|
||||
use aoc_2024::{load, print_res};
|
||||
use bstr::BString;
|
||||
use color_eyre::eyre::{Context, ContextCompat};
|
||||
use itertools::Itertools;
|
||||
|
||||
type Parsed = (Vec<u64>, Vec<u64>);
|
||||
|
||||
pub fn parsing(input: &BString) -> color_eyre::Result<Parsed> {
|
||||
let (first, second) = core::str::from_utf8(input)
|
||||
.unwrap()
|
||||
.lines()
|
||||
.map(|l| -> color_eyre::Result<_> {
|
||||
let mut nums = l.split_ascii_whitespace();
|
||||
let first: u64 = nums
|
||||
.next()
|
||||
.with_context(|| "missing first number")?
|
||||
.parse()
|
||||
.with_context(|| "parsing first number")?;
|
||||
let second: u64 = nums
|
||||
.next()
|
||||
.with_context(|| "missing second number")?
|
||||
.parse()
|
||||
.with_context(|| "parsing second number")?;
|
||||
|
||||
Ok((first, second))
|
||||
})
|
||||
.process_results(|iter| iter.unzip())?;
|
||||
Ok((first, second))
|
||||
}
|
||||
|
||||
pub fn part1((mut first, mut second): Parsed) {
|
||||
first.sort_unstable();
|
||||
second.sort_unstable();
|
||||
|
||||
let total_distance: u64 = first.iter().zip(second).map(|(a, b)| a.abs_diff(b)).sum();
|
||||
print_res!("Total distance: {total_distance}");
|
||||
}
|
||||
|
||||
pub fn part2((left, right): Parsed) {
|
||||
let mut similarities = HashMap::new();
|
||||
let mut total_similarity = 0;
|
||||
|
||||
for n in left {
|
||||
match similarities.get(&n) {
|
||||
None => {
|
||||
let similarity = n * right.iter().filter(|&&x| x == n).count() as u64;
|
||||
similarities.insert(n, similarity);
|
||||
total_similarity += similarity;
|
||||
}
|
||||
Some(v) => total_similarity += v,
|
||||
}
|
||||
}
|
||||
|
||||
print_res!("Total similarity: {total_similarity}");
|
||||
}
|
||||
|
||||
pub fn main() -> color_eyre::Result<()> {
|
||||
let context = load()?;
|
||||
|
||||
let start = Instant::now();
|
||||
let parsed = parsing(&context.input)?;
|
||||
let elapsed = humantime::format_duration(start.elapsed());
|
||||
|
||||
let start = Instant::now();
|
||||
if context.part == 1 {
|
||||
part1(parsed);
|
||||
} else {
|
||||
part2(parsed);
|
||||
}
|
||||
let elapsed_part = humantime::format_duration(start.elapsed());
|
||||
|
||||
println!(" Parsing: {elapsed}");
|
||||
println!(" Solving: {elapsed_part}");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue