From cca999f9b1ccfe877f41839071813a78a56db24c Mon Sep 17 00:00:00 2001 From: kleph Date: Tue, 3 Dec 2024 00:05:38 +0100 Subject: [PATCH] 2024 - Day 2 part 2 - rust --- 2024/rust2_2/.gitignore | 2 ++ 2024/rust2_2/Cargo.toml | 6 +++++ 2024/rust2_2/src/main.rs | 51 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 59 insertions(+) create mode 100644 2024/rust2_2/.gitignore create mode 100644 2024/rust2_2/Cargo.toml create mode 100644 2024/rust2_2/src/main.rs diff --git a/2024/rust2_2/.gitignore b/2024/rust2_2/.gitignore new file mode 100644 index 0000000..a9d37c5 --- /dev/null +++ b/2024/rust2_2/.gitignore @@ -0,0 +1,2 @@ +target +Cargo.lock diff --git a/2024/rust2_2/Cargo.toml b/2024/rust2_2/Cargo.toml new file mode 100644 index 0000000..9be5dc2 --- /dev/null +++ b/2024/rust2_2/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "rust2_2" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/2024/rust2_2/src/main.rs b/2024/rust2_2/src/main.rs new file mode 100644 index 0000000..16cc3b6 --- /dev/null +++ b/2024/rust2_2/src/main.rs @@ -0,0 +1,51 @@ +use std::io::{BufRead, BufReader}; +use std::fs::File; + +fn is_safe(v:&[u32]) -> bool +{ + let s_diff = if v[0] > v[1] {false} else {true}; + + for n in 1..v.len() { + let diff = v[n].abs_diff(v[n - 1]); + + if diff > 3 || diff == 0{ + return false; + } + + let s_diff2 = if v[n] < v[n-1] {false} else {true}; + if s_diff2 ^ s_diff { + return false; + } + + } + return true; +} + +fn main (){ + let filename = "../2/input_example.txt"; + // let filename = "../2/input.txt"; + let file = BufReader::new(File::open(filename).expect("Unable to open file")); + let mut safe: u32 = 0; + + for line in file.lines() { + let wline = line.unwrap(); + let nums: Vec = wline.split(' ') + .filter(|&x| !x.is_empty()) + .map(|x| x.parse().unwrap()) + .collect(); + + if is_safe(&nums[..]){ + safe += 1; + } else { + for n in 1..nums.len(){ + let to_test = &[&nums[0..n], &nums[n+1..nums.len()]].concat(); + if is_safe(to_test){ + safe += 1; + break; + } + } + } + } + + println!("{}", safe); +}