mirror of
https://github.com/danbulant/adventOfCode
synced 2026-06-24 16:31:44 +00:00
day 2 almost part 2
This commit is contained in:
parent
7082fbb005
commit
6f2d8b1b80
5 changed files with 1075 additions and 0 deletions
6
2024/data/02/1.in
Normal file
6
2024/data/02/1.in
Normal 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
1
2024/data/02/1.part1.out
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
2
|
||||||
1
2024/data/02/1.part2.out
Normal file
1
2024/data/02/1.part2.out
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
4
|
||||||
1000
2024/data/02/2.in
Normal file
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
67
2024/src/bin/02.rs
Normal 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();
|
||||||
|
}
|
||||||
Loading…
Reference in a new issue