From a141de6ff47cd3fe7db921f9529b4abdc4271cf6 Mon Sep 17 00:00:00 2001 From: _tud <98935832+UnderscoreTud@users.noreply.github.com> Date: Mon, 2 Dec 2024 15:11:24 +0300 Subject: [PATCH] Day 2 --- data/examples/02.txt | 6 ++++ src/bin/02.rs | 70 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 data/examples/02.txt create mode 100644 src/bin/02.rs diff --git a/data/examples/02.txt b/data/examples/02.txt new file mode 100644 index 0000000..82cd679 --- /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 \ No newline at end of file diff --git a/src/bin/02.rs b/src/bin/02.rs new file mode 100644 index 0000000..bad38fc --- /dev/null +++ b/src/bin/02.rs @@ -0,0 +1,70 @@ +advent_of_code::solution!(2); + +fn is_safe(data: &Vec) -> bool { + let mut previous_direction = None; + for i in 0..(data.len() - 1) { + let diff = data[i].abs_diff(data[i + 1]); + if diff > 3 { + return false; + } + let direction = data[i].cmp(&data[i + 1]); + match previous_direction { + Some(previous_direction) => if previous_direction != direction { + return false; + }, + None => previous_direction = Some(direction) + } + } + true +} + +fn is_safe_lenient(data: &Vec) -> bool { + if is_safe(data) { + return true; + } + for i in 0..data.len() { + let mut modified_data = data.clone(); + modified_data.remove(i); + if is_safe(&modified_data) { + return true + } + } + false +} + +fn count_safe_reports

(input: &str, predicate: P) -> u32 +where + P: FnMut(&Vec) -> bool +{ + input.lines() + .map(|line| line.split_whitespace() + .map(|number| number.parse::().unwrap()) + .collect::>()) + .filter(predicate) + .count() as u32 +} + +pub fn part_one(input: &str) -> Option { + Some(count_safe_reports(input, is_safe)) +} + +pub fn part_two(input: &str) -> Option { + Some(count_safe_reports(input, is_safe_lenient)) +} + +#[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)); + } +}