From c2575cbcea9b87444f2f04e17eb1480303230f17 Mon Sep 17 00:00:00 2001 From: Aaron Manning Date: Fri, 6 Dec 2024 18:18:25 +1100 Subject: [PATCH] day 1 --- .gitignore | 2 ++ day-01/Cargo.lock | 7 +++++++ day-01/Cargo.toml | 6 ++++++ day-01/src/main.rs | 43 +++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 58 insertions(+) create mode 100644 .gitignore create mode 100644 day-01/Cargo.lock create mode 100644 day-01/Cargo.toml create mode 100644 day-01/src/main.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fae1e28 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +input.txt +target/ diff --git a/day-01/Cargo.lock b/day-01/Cargo.lock new file mode 100644 index 0000000..7dc86fc --- /dev/null +++ b/day-01/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "day-01" +version = "0.1.0" diff --git a/day-01/Cargo.toml b/day-01/Cargo.toml new file mode 100644 index 0000000..84d4d11 --- /dev/null +++ b/day-01/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "day-01" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/day-01/src/main.rs b/day-01/src/main.rs new file mode 100644 index 0000000..f1b8b14 --- /dev/null +++ b/day-01/src/main.rs @@ -0,0 +1,43 @@ +const INPUT: &str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/input.txt")); + +fn main() { + let (mut first, mut second): (Vec<_>, Vec<_>) = + INPUT.lines() + .filter_map(|line| { + let mut parts = line.split_whitespace(); + let first = parts.next()?; + let second = parts.next()?; + Some(( + str::parse::(first).ok()?, + str::parse::(second).ok()?, + )) + }) + .unzip(); + + first.sort(); + second.sort(); + + let difference = first.iter().zip(second.iter().copied()) + .map(|(x, y)| x.abs_diff(y)) + .sum::(); + + println!("Part 1: {}", difference); + + let mut similarity = 0; + let mut idx = 0; + for element in first { + while second.get(idx).is_some_and(|x| *x < element) { + idx += 1; + } + + let mut occurances = 0; + while second.get(idx) == Some(&element) { + idx += 1; + occurances += 1; + } + + similarity += occurances * element; + } + + println!("Part 2: {}", similarity); +}