feat: added day 2 part 1 and 2
All checks were successful
Build and run challenges / Challenge for day (1) (push) Successful in 3s

Signed-off-by: Louis Vallat <contact@louis-vallat.fr>
This commit is contained in:
Louis Vallat 2024-12-03 22:04:35 +01:00
parent 54684d8df9
commit 38a1bf189d
Signed by: louis
SSH Key Fingerprint: SHA256:0iPwDU/PZtEy/K13Oar4TzmcunmI9H5U9IsOR3jyT/Q
3 changed files with 1070 additions and 0 deletions

6
day2/Cargo.toml Normal file
View File

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

1000
day2/input Normal file

File diff suppressed because it is too large Load Diff

64
day2/src/main.rs Normal file
View File

@ -0,0 +1,64 @@
use std::{env, fs};
fn read_input(path: &str) -> String {
fs::read_to_string(path).expect("Cannot read file.")
}
fn parse_input(input: &str) -> Vec<Vec<i32>> {
input
.lines()
.filter(|line| !line.is_empty())
.map(|line| {
line.split(" ")
.map(|num| num.parse().expect("Could not parse as i32."))
.collect()
})
.collect()
}
fn is_safe(levels: &Vec<i32>, allowed_errors: u32) -> bool {
if levels.len() < 2 {
return true;
}
if levels.len() == 2 {
return (1..=3).contains(&(levels[0] - levels[1]).abs())
}
let mut diff: i32 = levels[1] - levels[2];
for i in 1..levels.len() {
let local_diff = levels[i - 1] - levels[i];
if local_diff.signum() != diff.signum() || !(1..=3).contains(&local_diff.abs()) {
return if allowed_errors == 0 {
false
} else {
let mut levels_low = levels.clone();
levels_low.remove(i - 1);
let mut levels_high = levels.clone();
levels_high.remove(i);
is_safe(&levels_low, allowed_errors - 1) || is_safe(&levels_high, allowed_errors - 1)
}
}
diff = local_diff;
}
true
}
fn part_1(levels: &Vec<Vec<i32>>) -> usize {
levels.iter().filter(|level| is_safe(level, 0)).count()
}
fn part_2(levels: &Vec<Vec<i32>>) -> usize {
levels.iter().filter(|level| is_safe(level, 1)).count()
}
fn main() {
let args: Vec<String> = env::args().collect();
for arg in args.iter().skip(1) {
let input = read_input(&arg);
let levels = parse_input(&input);
println!("[{}]", &arg);
println!("\t[Part 1] => Answer is '{}'.", part_1(&levels));
println!("\t[Part 2] => Answer is '{}'.", part_2(&levels));
}
}