day 2 almost part 2

This commit is contained in:
Daniel Bulant 2024-12-02 08:50:42 +01:00
parent 7082fbb005
commit 6f2d8b1b80
No known key found for this signature in database
5 changed files with 1075 additions and 0 deletions

6
2024/data/02/1.in Normal file
View file

@ -0,0 +1,6 @@
7 6 4 2 1
1 2 7 8 9
9 7 6 2 1
1 3 2 4 5
8 6 4 4 1
1 3 6 7 9

1
2024/data/02/1.part1.out Normal file
View file

@ -0,0 +1 @@
2

1
2024/data/02/1.part2.out Normal file
View file

@ -0,0 +1 @@
4

1000
2024/data/02/2.in Normal file

File diff suppressed because it is too large Load diff

67
2024/src/bin/02.rs Normal file
View file

@ -0,0 +1,67 @@
use std::{fs::File, io::{BufRead, BufReader}};
use anyhow::Result;
use aoc2024::{Context, Day};
use itertools::Itertools;
fn part1(ctx: &Context) -> Result<String> {
Ok(BufReader::new(File::open(&ctx.args.input)?).lines().map(|line| {
let line = line.unwrap();
let mut rising = None;
let nums = line.split_whitespace().map(|n| n.parse::<u32>().unwrap()).tuple_windows().all(|(a,b)| valid(a,b, &mut rising));
nums
}).map(|r| r as i32).sum::<i32>().to_string())
}
fn valid(a: u32, b: u32, rising: &mut Option<bool>) -> bool {
let diff = a.abs_diff(b);
if !(1..=3).contains(&diff) { return false }
match &rising {
None => {
*rising = Some(b > a);
true
},
Some(r) => {
if *r {
b > a
} else {
b < a
}
}
}
}
fn part2(ctx: &Context) -> Result<String> {
Ok(BufReader::new(File::open(&ctx.args.input)?).lines().map(|line| {
let mut found = false;
let mut skip = 0;
let line = line.unwrap();
let mut rising = None;
let nums = line.split_whitespace().map(|n| n.parse::<u32>().unwrap()).tuple_windows().all(|(a,b,c)| {
if skip > 0 {
skip -= 1;
return true
}
if valid(a,b,&mut rising) {
true
} else {
if found { return false }
found = true;
skip = 1;
valid(a, c, &mut rising)
}
});
nums
})
.map(|r| r as i32).sum::<i32>().to_string())
}
fn main() {
Day::new()
.part1(part1)
.part2(part2)
.run();
}