This commit is contained in:
nora 2024-12-02 19:31:27 +01:00
parent ba8c793c18
commit b525d823fb

View file

@ -50,8 +50,85 @@ fn part1(input: &str) -> u64 {
.count() as u64
}
fn part2(_input: &str) -> u64 {
0
fn part2(input: &str) -> u64 {
input
.lines()
.filter(|report| {
let levels = report
.split_ascii_whitespace()
.map(parse_unwrap)
.collect::<Vec<_>>();
let check_asc_desc = |forwards, smol, big| {
if forwards {
smol < big && smol + 3 >= big
} else {
big < smol && big + 3 >= smol
}
};
let check_direction = |forwards| {
let mut unsafe_transitions = vec![];
for (i, ab) in levels.windows(2).enumerate() {
if !check_asc_desc(forwards, ab[0], ab[1]) {
unsafe_transitions.push(i);
}
}
match unsafe_transitions.len() {
0 => true,
1 => {
// 1 3 2 4 5
// ^unsafe transition, index 1
// either idx 1 needs to go, or idx 2 needs to go (in this case 1)
let trans = unsafe_transitions[0];
if trans == 0 || trans == (levels.len() - 2) {
// It's the first or last element.
return true;
}
// Let's see what happens if we drop the first element (3 in the example).
if check_asc_desc(forwards, levels[trans - 1], levels[trans + 1]) {
// Dropping the first elem works!
return true;
}
// Let's see what happens if we drop the second element (2 in the example).
if check_asc_desc(forwards, levels[trans], levels[trans + 2]) {
// Dropping the secnd elem works!
return true;
}
false
}
2 => {
// 1 5 3 4 5
// ^ ^ unsafe transitions, idx 0 and 1
// If the two transitions are not adjacent, there's no hope.
let (trans0, trans1) = (unsafe_transitions[0], unsafe_transitions[1]);
if trans0.abs_diff(trans1) != 1 {
return false;
}
// Let's try dropping the middle one.
let min = trans0.min(trans1);
if check_asc_desc(forwards, levels[min], levels[min + 2]) {
// Dropping it works!
return true;
}
false
}
_ => false,
}
};
let forwards = check_direction(true);
if forwards {
return true;
}
check_direction(false)
})
.count() as u64
}
helper::tests! {
@ -61,8 +138,8 @@ helper::tests! {
default => 287;
}
part2 {
small => 0;
default => 0;
small => 4;
default => 354;
}
}
helper::benchmarks! {}