From cad8a7d48d9eb03d5fd7f5908893a98e5a56f297 Mon Sep 17 00:00:00 2001 From: kleph Date: Mon, 2 Dec 2024 22:56:43 +0100 Subject: [PATCH] 2024 - Day 2 part 1 - rust --- 2024/rust2/.gitignore | 2 ++ 2024/rust2/Cargo.toml | 6 ++++++ 2024/rust2/src/main.rs | 43 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 51 insertions(+) create mode 100644 2024/rust2/.gitignore create mode 100644 2024/rust2/Cargo.toml create mode 100644 2024/rust2/src/main.rs 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); +}