feat: added day 2 part 1 and 2
All checks were successful
Build and run challenges / Challenge for day (1) (push) Successful in 3s
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:
parent
54684d8df9
commit
38a1bf189d
6
day2/Cargo.toml
Normal file
6
day2/Cargo.toml
Normal file
@ -0,0 +1,6 @@
|
||||
[package]
|
||||
name = "day2"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
1000
day2/input
Normal file
1000
day2/input
Normal file
File diff suppressed because it is too large
Load Diff
64
day2/src/main.rs
Normal file
64
day2/src/main.rs
Normal 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));
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user