From d503479a80d5ee341ec8744822e31f56af34e21d Mon Sep 17 00:00:00 2001 From: Martin Berg Alstad Date: Thu, 5 Dec 2024 18:57:13 +0100 Subject: [PATCH] Day2 task 2 finished --- day2/src/common.rs | 33 +++++++++++++----- day2/src/day2.md | 62 +++++++++++++++++++++++++++++++++ day2/src/main.rs | 4 +++ day2/src/task1_alt.rs | 79 +++++++++++++++++++++++++++++++++++++++++++ day2/src/task2.rs | 33 ++++++++++++++++++ 5 files changed, 203 insertions(+), 8 deletions(-) create mode 100644 day2/src/day2.md create mode 100644 day2/src/task1_alt.rs create mode 100644 day2/src/task2.rs diff --git a/day2/src/common.rs b/day2/src/common.rs index 441ad5d..77e3e80 100644 --- a/day2/src/common.rs +++ b/day2/src/common.rs @@ -1,7 +1,7 @@ -use std::convert::{identity, Infallible}; +use std::convert::Infallible; use std::str::FromStr; -pub(crate) struct Level(Vec); +pub(crate) struct Level(pub(crate) Vec); impl FromStr for Level { type Err = Infallible; @@ -18,13 +18,30 @@ impl FromStr for Level { impl Level { // TODO optimize pub(crate) fn is_safe(&self) -> bool { - (0..self.0.len()) - .map(|index| Self::is_increasing(&self.0[index..])) - .all(identity) - || (0..self.0.len()) - .map(|index| Self::is_decreasing(&self.0[index..])) - .all(identity) + (0..self.0.len()).all(|index| Self::is_increasing(&self.0[index..])) + || (0..self.0.len()).all(|index| Self::is_decreasing(&self.0[index..])) } + + // a b c d e + // x b c d e + // a x c d e + // a b x d e + // a b c x e + // a b c d x + pub(crate) fn safe_by_removing(&mut self) -> bool { + if self.is_safe() { + return true; + } + for index in 0..self.0.len() { + let mut array = self.0.clone(); + array.remove(index); + if Level(array).is_safe() { + return true; + } + } + false + } + pub(crate) fn is_increasing(array: &[usize]) -> bool { Self::is_changing(array, PartialOrd::gt) diff --git a/day2/src/day2.md b/day2/src/day2.md new file mode 100644 index 0000000..12f4561 --- /dev/null +++ b/day2/src/day2.md @@ -0,0 +1,62 @@ +--- Day 2: Red-Nosed Reports --- + +Fortunately, the first location The Historians want to search isn't a long walk from the Chief Historian's office. + +While the Red-Nosed Reindeer nuclear fusion/fission plant appears to contain no sign of the Chief Historian, the engineers there run up to you as soon as they see you. Apparently, they still talk about the time Rudolph was saved through molecular synthesis from a single electron. + +They're quick to add that - since you're already here - they'd really appreciate your help analyzing some unusual data from the Red-Nosed reactor. You turn to check if The Historians are waiting for you, but they seem to have already divided into groups that are currently searching every corner of the facility. You offer to help with the unusual data. + +The unusual data (your puzzle input) consists of many reports, one report per line. Each report is a list of numbers called levels that are separated by spaces. For example: + +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 + +This example data contains six reports each containing five levels. + +The engineers are trying to figure out which reports are safe. The Red-Nosed reactor safety systems can only tolerate levels that are either gradually increasing or gradually decreasing. So, a report only counts as safe if both of the following are true: + + The levels are either all increasing or all decreasing. + Any two adjacent levels differ by at least one and at most three. + +In the example above, the reports can be found safe or unsafe by checking those rules: + + 7 6 4 2 1: Safe because the levels are all decreasing by 1 or 2. + 1 2 7 8 9: Unsafe because 2 7 is an increase of 5. + 9 7 6 2 1: Unsafe because 6 2 is a decrease of 4. + 1 3 2 4 5: Unsafe because 1 3 is increasing but 3 2 is decreasing. + 8 6 4 4 1: Unsafe because 4 4 is neither an increase or a decrease. + 1 3 6 7 9: Safe because the levels are all increasing by 1, 2, or 3. + +So, in this example, 2 reports are safe. + +Analyze the unusual data from the engineers. How many reports are safe? + +Your puzzle answer was 598. +--- Part Two --- + +The engineers are surprised by the low number of safe reports until they realize they forgot to tell you about the Problem Dampener. + +The Problem Dampener is a reactor-mounted module that lets the reactor safety systems tolerate a single bad level in what would otherwise be a safe report. It's like the bad level never happened! + +Now, the same rules apply as before, except if removing a single level from an unsafe report would make it safe, the report instead counts as safe. + +More of the above example's reports are now safe: + + 7 6 4 2 1: Safe without removing any level. + 1 2 7 8 9: Unsafe regardless of which level is removed. + 9 7 6 2 1: Unsafe regardless of which level is removed. + 1 3 2 4 5: Safe by removing the second level, 3. + 8 6 4 4 1: Safe by removing the third level, 4. + 1 3 6 7 9: Safe without removing any level. + +Thanks to the Problem Dampener, 4 reports are actually safe! + +Update your analysis by handling situations where the Problem Dampener can remove a single level from unsafe reports. How many reports are now safe? + +Your puzzle answer was 634. + +Both parts of this puzzle are complete! They provide two gold stars: ** \ No newline at end of file diff --git a/day2/src/main.rs b/day2/src/main.rs index d9d96d3..f0e993a 100644 --- a/day2/src/main.rs +++ b/day2/src/main.rs @@ -1,8 +1,12 @@ use crate::task1::task1; +use crate::task2::task2; mod task1; mod common; +mod task2; +mod task1_alt; fn main() { task1(); + task2(); } diff --git a/day2/src/task1_alt.rs b/day2/src/task1_alt.rs new file mode 100644 index 0000000..aaeeba9 --- /dev/null +++ b/day2/src/task1_alt.rs @@ -0,0 +1,79 @@ +use std::cmp::Ordering; +use crate::common::{parse_input, Level}; + +fn task1() { + let raw_input = include_str!("./input.txt"); + let safe_levels = parse_input(raw_input) + .into_iter() + .map(LevelState::from) + .filter(LevelState::is_all_safe) + .count(); + println!("The solution to task 1 is {safe_levels}") +} + +#[derive(PartialOrd, PartialEq, Debug, Copy, Clone)] +pub(crate) enum State { + Increase(usize), + Decrease(usize), + Stable, +} + +impl State { + pub(crate) fn from_values(first: usize, second: usize) -> Self { + match second.cmp(&first) { + Ordering::Less => Self::Decrease(first.abs_diff(second)), + Ordering::Greater => Self::Increase(first.abs_diff(second)), + Ordering::Equal => Self::Stable, + } + } + + pub(crate) fn is_safely_increasing(&self) -> bool { + matches!(self, State::Increase(1..=3)) + } + + pub(crate) fn is_safely_decreasing(&self) -> bool { + matches!(self, State::Decrease(1..=3)) + } +} + +pub(crate) struct LevelState(pub(crate) Vec); + +impl From for LevelState { + fn from(level: Level) -> Self { + let mut previous = None; + let mut level_state = Vec::with_capacity(level.0.len()); + + for current in level.0 { + if let Some(previous) = previous { + level_state.push(State::from_values(previous, current)) + } else { + level_state.push(State::Stable); + } + previous = Some(current); + } + Self(level_state) + } +} + +impl LevelState { + pub(crate) fn is_all_safe(&self) -> bool { + self.is_all_safely_increasing() || self.is_all_safely_decreasing() + } + + fn is_all_safely_increasing(&self) -> bool { + self.is_all_changing(State::is_safely_increasing) + } + + fn is_all_safely_decreasing(&self) -> bool { + self.is_all_changing(State::is_safely_decreasing) + } + + fn is_all_changing(&self, verify: fn(&State) -> bool) -> bool { + let states = &self.0; + match &states[..] { + [State::Stable, tail @ ..] if tail.iter().all(verify) => true, + [State::Stable] | [] => true, + _ => false, + } + } +} \ No newline at end of file diff --git a/day2/src/task2.rs b/day2/src/task2.rs new file mode 100644 index 0000000..f6303df --- /dev/null +++ b/day2/src/task2.rs @@ -0,0 +1,33 @@ +use crate::common::parse_input; + +pub(crate) fn task2() { + let raw_input = include_str!("./input.txt"); + + let mut safe_levels = 0; + for mut level in parse_input(raw_input).into_iter() { + if level.safe_by_removing() { + safe_levels += 1; + } + } + println!("The solution to task 2 is {safe_levels}") +} + +#[cfg(test)] +mod tests { + use crate::common::Level; + use crate::task1_alt::{LevelState, State}; + + #[test] + fn test_from_level() { + let level = Level(vec![1, 3, 4, 5]); + assert_eq!( + [ + State::Stable, + State::Increase(2), + State::Increase(1), + State::Increase(1) + ], + *LevelState::from(level).0 + ) + } +}