Start day 2

This commit is contained in:
Felix Suchert 2024-12-10 03:44:01 +01:00
parent 8e6607a8c8
commit a20a972717
Signed by: feliix42
GPG key ID: 24363525EA0E8A99
4 changed files with 1065 additions and 1 deletions

1001
inputs/day_2.txt Normal file

File diff suppressed because it is too large Load diff

View file

@ -12,8 +12,9 @@ fn main() -> std::io::Result<()> {
return Ok(()); return Ok(());
} }
match u8::from_str(&args.next().unwrap()) { match u8::from_str(&args.nth(1).unwrap()) {
Ok(1) => solutions::day_1::run(args)?, Ok(1) => solutions::day_1::run(args)?,
Ok(2) => solutions::day_2::run(args)?,
Ok(_) => eprintln!("Unknown day. Are you from the future?"), Ok(_) => eprintln!("Unknown day. Are you from the future?"),
Err(_) => eprintln!("Unknown day format. Use integers to specify."), Err(_) => eprintln!("Unknown day format. Use integers to specify."),
} }

61
src/solutions/day_2.rs Normal file
View file

@ -0,0 +1,61 @@
use std::cmp::Ordering;
use std::env;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::str::FromStr;
pub fn run(mut args: env::Args) -> std::io::Result<()> {
let filename = args
.next()
.expect("You must provide a filename as argument");
let f = File::open(filename)?;
let reader = BufReader::new(f);
let mut num_safe = 0;
for line in reader.lines() {
let l = line.unwrap();
if l.is_empty() {
continue;
}
let levels: Vec<u8> = l
.split_whitespace()
.map(u8::from_str)
.map(Result::unwrap)
.collect();
if levels.len() <= 1 {
if levels.len() == 1 {
num_safe += 1;
}
continue;
}
let ord = levels[0].cmp(&levels[1]);
if ord != Ordering::Equal {
let mut safe = true;
for i in 1..levels.len() {
let abs_diff = levels[i - 1].abs_diff(levels[i]);
if levels[i - 1].cmp(&levels[i]) != ord || abs_diff > 3 {
// the case that the difference is < 1 is caught by cmp as it will return ==
safe = false;
break;
}
}
if safe {
num_safe += 1;
}
}
}
// Task 1
println!("Number of safe levels: {num_safe}");
// Task 2
// TBD
Ok(())
}

View file

@ -1,2 +1,3 @@
pub mod day_1; pub mod day_1;
pub mod day_2;