diff --git a/README.md b/README.md index 9fe2758..135f8d2 100644 --- a/README.md +++ b/README.md @@ -18,8 +18,9 @@ Solutions for [Advent of Code](https://adventofcode.com/) in [Rust](https://www. | Day | Part 1 | Part 2 | | :---: | :---: | :---: | | [Day 1](./src/bin/01.rs) | `72.0µs` | `76.8µs` | +| [Day 2](./src/bin/02.rs) | `333.6µs` | `642.1µs` | -**Total: 0.15ms** +**Total: 1.12ms** --- diff --git a/data/examples/02.txt b/data/examples/02.txt new file mode 100644 index 0000000..b49c10d --- /dev/null +++ b/data/examples/02.txt @@ -0,0 +1,6 @@ +7 6 4 2 1 +1 2 7 8 9 +9 7 6 2 1 +1 3 2 4 5 +8 6 4 4 1 +1 3 6 7 9 diff --git a/src/bin/02.rs b/src/bin/02.rs new file mode 100644 index 0000000..95166cc --- /dev/null +++ b/src/bin/02.rs @@ -0,0 +1,88 @@ +advent_of_code::solution!(2); + +use std::cmp::Ordering; + +fn validate_input_p1(input: &Vec) -> bool { + input + .iter() + .fold( + (true, 0, None), + |(is_good, last, ord): (bool, u32, Option), cur: &u32| match ( + is_good, last, cur, ord, + ) { + (false, _, _, _) => (false, 0, None), + (_, 0, cur, None) => (true, *cur, None), + (_, last, cur, None) if last.abs_diff(*cur) < 4 => { + (true, *cur, Some(last.cmp(cur))) + } + (_, last, cur, Some(cmp)) if last.abs_diff(*cur) < 4 && last.cmp(cur) == cmp => { + (true, *cur, Some(cmp)) + } + _ => (false, 0, None), + }, + ) + .0 +} + +fn validate_input_p2(input: &Vec) -> bool { + if validate_input_p1(input) { + return true; + } + + for i in 0..input.len() { + let mut input2 = input.clone(); + input2.remove(i); + if validate_input_p1(&input2) { + return true; + } + } + + false +} + +pub fn part_one(input: &str) -> Option { + input + .strip_suffix("\n") + .unwrap_or(input) + .lines() + .map(|s| { + s.split_whitespace() + .map(|nb| nb.parse::().expect("parsing failed")) + .collect::>() + }) + .filter(validate_input_p1) + .count() + .into() +} + +pub fn part_two(input: &str) -> Option { + input + .strip_suffix("\n") + .unwrap_or(input) + .lines() + .map(|s| { + s.split_whitespace() + .map(|nb| nb.parse::().expect("parsing failed")) + .collect::>() + }) + .filter(validate_input_p2) + .count() + .into() +} + +#[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(2)); + } + + #[test] + fn test_part_two() { + let result = part_two(&advent_of_code::template::read_file("examples", DAY)); + assert_eq!(result, Some(4)); + } +}