2024 - Day 2 part 1 - rust
This commit is contained in:
parent
beef70848d
commit
cad8a7d48d
3 changed files with 51 additions and 0 deletions
2
2024/rust2/.gitignore
vendored
Normal file
2
2024/rust2/.gitignore
vendored
Normal file
|
@ -0,0 +1,2 @@
|
|||
target
|
||||
Cargo.lock
|
6
2024/rust2/Cargo.toml
Normal file
6
2024/rust2/Cargo.toml
Normal file
|
@ -0,0 +1,6 @@
|
|||
[package]
|
||||
name = "rust2"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
43
2024/rust2/src/main.rs
Normal file
43
2024/rust2/src/main.rs
Normal file
|
@ -0,0 +1,43 @@
|
|||
use std::io::{BufRead, BufReader};
|
||||
use std::fs::File;
|
||||
|
||||
fn is_safe(v:Vec<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<u32> = wline.split(' ')
|
||||
.filter(|&x| !x.is_empty())
|
||||
.map(|x| x.parse().unwrap())
|
||||
.collect();
|
||||
|
||||
if is_safe(nums){
|
||||
safe += 1;
|
||||
}
|
||||
}
|
||||
|
||||
println!("{}", safe);
|
||||
}
|
Loading…
Reference in a new issue