From 892d59f21b42f0b58711695e33a2601f1c8f4c84 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Sat, 30 Nov 2024 21:38:31 -0800 Subject: [PATCH] day 1: problem 1 solution --- 1/Cargo.lock | 7 +++++ 1/Cargo.toml | 6 ++++ 1/src/main.rs | 85 +++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 98 insertions(+) create mode 100644 1/Cargo.lock create mode 100644 1/Cargo.toml create mode 100644 1/src/main.rs diff --git a/1/Cargo.lock b/1/Cargo.lock new file mode 100644 index 0000000..ae5bfe8 --- /dev/null +++ b/1/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "day1" +version = "0.1.0" diff --git a/1/Cargo.toml b/1/Cargo.toml new file mode 100644 index 0000000..fb6b7ec --- /dev/null +++ b/1/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "day1" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/1/src/main.rs b/1/src/main.rs new file mode 100644 index 0000000..55d4039 --- /dev/null +++ b/1/src/main.rs @@ -0,0 +1,85 @@ +use std::fs::File; +use std::io::{BufRead, BufReader, Lines}; +use std::iter::zip; +use std::time::Instant; + +// BOILERPLATE +type InputIter = Lines>; + +fn get_input() -> InputIter { + let f = File::open("input").unwrap(); + let br = BufReader::new(f); + br.lines() +} + +fn main() { + let start = Instant::now(); + let ans1 = problem1(get_input()); + let duration = start.elapsed(); + println!("Problem 1 solution: {} [{}s]", ans1, duration.as_secs_f64()); + + let start = Instant::now(); + let ans2 = problem2(get_input()); + let duration = start.elapsed(); + println!("Problem 2 solution: {} [{}s]", ans2, duration.as_secs_f64()); +} + +// PROBLEM 1 solution + +#[derive(Debug)] +struct Entry { + pos: usize, + val: u32, +} + +fn problem1(input: Lines) -> u64 { + let mut left = Vec::new(); + let mut right = Vec::new(); + for (pos, line) in input.enumerate() { + if line.is_err() { + panic!("can't read line"); + } + let line = line.unwrap(); + let parts: Vec<&str> = line.split_ascii_whitespace().collect(); + left.push(Entry{pos, val: parts[0].parse::().unwrap()}); + right.push(Entry{pos, val: parts[1].parse::().unwrap()}); + } + left.sort_by_key(|entry| entry.val); + right.sort_by_key(|entry| entry.val); + + println!("{:?}", right); + + zip(left, right).map(|(left, right)| { + println!("{:?} {:?}", left, right); + u64::abs_diff(left.val as u64, right.val as u64)}).sum() +} + +// PROBLEM 2 solution +fn problem2(input: Lines) -> u64 { + 0 +} + +#[cfg(test)] +mod tests { + use crate::*; + use std::io::Cursor; + + const EXAMPLE: &str = &"3 4 +4 3 +2 5 +1 3 +3 9 +3 3"; + + #[test] + fn problem1_example() { + let c = Cursor::new(EXAMPLE); + assert_eq!(problem1(c.lines()), 11); + } + + #[test] + fn problem2_example() { + let c = Cursor::new(EXAMPLE); + assert_eq!(problem2(c.lines()), 0); + } +}