2024 - Day 2 part 2 - rust

This commit is contained in:
kleph 2024-12-03 00:05:38 +01:00
parent cad8a7d48d
commit cca999f9b1
3 changed files with 59 additions and 0 deletions

2
2024/rust2_2/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
target
Cargo.lock

6
2024/rust2_2/Cargo.toml Normal file
View file

@ -0,0 +1,6 @@
[package]
name = "rust2_2"
version = "0.1.0"
edition = "2021"
[dependencies]

51
2024/rust2_2/src/main.rs Normal file
View file

@ -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<u32> = 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);
}