diff --git a/2024/rust2/.gitignore b/2024/rust2/.gitignore new file mode 100644 index 0000000..a9d37c5 --- /dev/null +++ b/2024/rust2/.gitignore @@ -0,0 +1,2 @@ +target +Cargo.lock diff --git a/2024/rust2/Cargo.toml b/2024/rust2/Cargo.toml new file mode 100644 index 0000000..c316124 --- /dev/null +++ b/2024/rust2/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "rust2" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/2024/rust2/src/main.rs b/2024/rust2/src/main.rs new file mode 100644 index 0000000..fe3ddbc --- /dev/null +++ b/2024/rust2/src/main.rs @@ -0,0 +1,43 @@ +use std::io::{BufRead, BufReader}; +use std::fs::File; + +fn is_safe(v:Vec) -> 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; + } + } + + println!("{}", safe); +}