diff --git a/Cargo.lock b/Cargo.lock index 9504be6..e8bbce6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -23,6 +23,7 @@ version = "0.11.0" dependencies = [ "chrono", "dhat", + "itertools", "pico-args", "tinyjson", ] @@ -126,6 +127,12 @@ dependencies = [ "thousands", ] +[[package]] +name = "either" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0" + [[package]] name = "gimli" version = "0.28.1" @@ -155,6 +162,15 @@ dependencies = [ "cc", ] +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.9" diff --git a/Cargo.toml b/Cargo.toml index 038a1a3..a80ffa7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,6 +24,7 @@ test_lib = [] # Template dependencies chrono = { version = "0.4.38", optional = true } dhat = { version = "0.3.3", optional = true } +itertools = "0.13.0" pico-args = "0.5.0" tinyjson = "2.5.1" diff --git a/data/examples/01.txt b/data/examples/01.txt new file mode 100644 index 0000000..b8af9ad --- /dev/null +++ b/data/examples/01.txt @@ -0,0 +1,6 @@ +3 4 +4 3 +2 5 +1 3 +3 9 +3 3 diff --git a/src/bin/01.rs b/src/bin/01.rs new file mode 100644 index 0000000..2aadd43 --- /dev/null +++ b/src/bin/01.rs @@ -0,0 +1,51 @@ +use itertools::Itertools; + +advent_of_code::solution!(1); + +fn get_lists(input: &str) -> (Vec, Vec) { + let numbers: Vec = input + .lines() + .flat_map(|line| line.split_whitespace().map(|x| x.parse::().unwrap())) + .collect(); + let left = numbers.iter().step_by(2).map(|x| *x).collect(); + let right = numbers.iter().skip(1).map(|x| *x).step_by(2).collect(); + + (left, right) +} + +pub fn part_one(input: &str) -> Option { + let (left, right) = get_lists(input); + Some( + left.iter() + .sorted() + .zip(right.iter().sorted()) + .map(|(l, r)| l.abs_diff(*r)) + .sum(), + ) +} + +pub fn part_two(input: &str) -> Option { + let (left, right) = get_lists(input); + Some( + left.iter() + .map(|l| l * right.iter().filter(|r| *r == l).count() as u32) + .sum(), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_part_one() { + let result = part_one(&advent_of_code::template::read_file("examples", DAY)); + assert_eq!(result, Some(11)); + } + + #[test] + fn test_part_two() { + let result = part_two(&advent_of_code::template::read_file("examples", DAY)); + assert_eq!(result, Some(31)); + } +}