add day02 solution

This commit is contained in:
Malte 2024-12-02 10:47:53 +01:00
parent 7db0c7c6c4
commit 6015b6ec38
2 changed files with 67 additions and 0 deletions

66
2024/src/day02.rs Normal file
View file

@ -0,0 +1,66 @@
use std::fs::read_to_string;
fn check_report(report: &Vec<i32>) -> bool {
let desc = report[0] > report[1];
for x in report.windows(2) {
let prev = if desc { x[0] } else { x[1] };
let curr = if desc { x[1] } else { x[0] };
let dist = prev - curr;
if dist > 3 || dist < 1 || prev < curr {
return false;
}
}
true
}
pub fn stage1(input: &str) -> usize {
read_to_string(input)
.unwrap()
.lines()
.map(|line| {
line.split_whitespace()
.map(|x| x.parse::<i32>().unwrap())
.collect::<Vec<i32>>()
})
.filter(|report| check_report(report))
.count()
}
pub fn stage2(input: &str) -> usize {
read_to_string(input)
.unwrap()
.lines()
.map(|line| {
line.split_whitespace()
.map(|x| x.parse::<i32>().unwrap())
.collect::<Vec<_>>()
})
.filter(|report| {
for y in 0..report.len() {
let mut variant = report.clone();
variant.remove(y);
if check_report(&variant) {
return true;
}
}
false
})
.count()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_stage1() {
assert_eq!(stage1("input/02_input.example"), 2);
assert_eq!(stage1("input/02_input.txt"), 463);
}
#[test]
fn test_stage2() {
assert_eq!(stage2("input/02_input.example"), 4);
assert_eq!(stage2("input/02_input.txt"), 514);
}
}

View file

@ -1,2 +1,3 @@
#[allow(dead_code)] #[allow(dead_code)]
mod day01; mod day01;
mod day02;