From 612bd4313fc2645146fc378098ab78f2ffc38727 Mon Sep 17 00:00:00 2001 From: Samuel Ortion Date: Wed, 4 Dec 2024 12:52:52 +0100 Subject: [PATCH] day 2: part2: rust --- 2024/days/02/part2/Cargo.toml | 6 +++ 2024/days/02/part2/src/main.rs | 73 ++++++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 2024/days/02/part2/Cargo.toml create mode 100644 2024/days/02/part2/src/main.rs diff --git a/2024/days/02/part2/Cargo.toml b/2024/days/02/part2/Cargo.toml new file mode 100644 index 0000000..d85b608 --- /dev/null +++ b/2024/days/02/part2/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "part1" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/2024/days/02/part2/src/main.rs b/2024/days/02/part2/src/main.rs new file mode 100644 index 0000000..e888c32 --- /dev/null +++ b/2024/days/02/part2/src/main.rs @@ -0,0 +1,73 @@ +use std::u64; + + +fn is_increasing(levels: &Vec) -> bool { + let mut current = 0; + for item in levels { + if *item < current { + return false; + } else { + current = *item; + } + } + return true; +} + +fn is_decreasing(levels: &Vec) -> bool { + let mut current = u64::MAX; + for item in levels { + if *item > current { + return false; + } else { + current = *item; + } + } + return true; +} + +fn is_monotonous(levels: &Vec) -> bool { + return is_increasing(levels) || is_decreasing(levels); +} + +fn is_safe(levels: &Vec) -> bool { + if !is_monotonous(levels) { + return false; + } + for i in 0..(levels.len() - 1) { + let j = i+1; + let a = levels[i]; + let b = levels[j]; + let diff = (a as i64 - b as i64).abs() as u64; + if diff < 1 || diff > 3 { + return false; + } + } + return true; +} + +fn is_safe_but_one(levels: &Vec) -> bool { + if is_safe(levels) { + return true; + } + for i in 0..(levels.len()) { + let mut levels_but_one = levels.clone(); + levels_but_one.remove(i); + if is_safe(&levels_but_one) { + return true; + } + } + return false; +} + +fn main() -> std::io::Result<()> { + let mut count = 0; + for line in std::io::stdin().lines() { + let line = line.unwrap(); + let levels: Vec = line.split(" ").map(|x| x.parse::().unwrap()).collect(); + if is_safe_but_one(&levels) { + count += 1; + } + } + println!("{}", count); + Ok(()) +} \ No newline at end of file