diff --git a/2024/day1/.gitignore b/2024/day1/.gitignore new file mode 100644 index 0000000..348d29e --- /dev/null +++ b/2024/day1/.gitignore @@ -0,0 +1,2 @@ +/target +input.txt diff --git a/2024/day1/Cargo.lock b/2024/day1/Cargo.lock new file mode 100644 index 0000000..ae5bfe8 --- /dev/null +++ b/2024/day1/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/2024/day1/Cargo.toml b/2024/day1/Cargo.toml new file mode 100644 index 0000000..fb6b7ec --- /dev/null +++ b/2024/day1/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "day1" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/2024/day1/src/main.rs b/2024/day1/src/main.rs new file mode 100644 index 0000000..69e3021 --- /dev/null +++ b/2024/day1/src/main.rs @@ -0,0 +1,32 @@ +use std::fs; + +fn main() { + let input = fs::read_to_string("./input.txt").unwrap(); + let mut column1 = Vec::new(); + let mut column2 = Vec::new(); + for line in input.lines() { + let mut split = line.split_whitespace(); + column1.push(split.next().unwrap().parse::().unwrap()); + column2.push(split.next().unwrap().parse::().unwrap()); + } + column1.sort_unstable(); + column2.sort_unstable(); + + println!("Solution 1: {}", puzzle1(&column1, &column2)); + println!("Solution 2: {}", puzzle2(&column1, &column2)); +} + +fn puzzle1(column1: &[i32], column2: &[i32]) -> i32 { + column1 + .iter() + .zip(column2) + .map(|(c1, c2)| (c1 - c2).abs()) + .sum() +} + +fn puzzle2(column1: &[i32], column2: &[i32]) -> i32 { + column1 + .iter() + .map(|c1| column2.iter().filter(|&c2| c1 == c2).count() as i32 * c1) + .sum() +}