mirror of
https://github.com/wezm/advent-of-code.git
synced 2024-12-18 18:29:55 +00:00
Add day 5 part 2 solution
This commit is contained in:
parent
9abb60642c
commit
8beb899b36
1 changed files with 41 additions and 1 deletions
|
@ -11,7 +11,10 @@ fn main() {
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
let steps = steps_to_exit(&offsets);
|
let steps = steps_to_exit(&offsets);
|
||||||
println!("{}", steps);
|
println!("Part 1: {}", steps);
|
||||||
|
|
||||||
|
let steps = steps_to_exit_part2(&offsets);
|
||||||
|
println!("Part 2: {}", steps);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn steps_to_exit(jump_offsets: &[i32]) -> i32 {
|
fn steps_to_exit(jump_offsets: &[i32]) -> i32 {
|
||||||
|
@ -37,8 +40,45 @@ fn steps_to_exit(jump_offsets: &[i32]) -> i32 {
|
||||||
steps
|
steps
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn steps_to_exit_part2(jump_offsets: &[i32]) -> i32 {
|
||||||
|
let mut offsets = jump_offsets.to_vec();
|
||||||
|
let mut pc = 0i32;
|
||||||
|
let mut steps = 0;
|
||||||
|
|
||||||
|
loop {
|
||||||
|
if let Some(offset) = offsets.get_mut(pc as usize) {
|
||||||
|
pc += *offset;
|
||||||
|
if *offset >= 3 {
|
||||||
|
*offset -= 1;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
*offset += 1;
|
||||||
|
}
|
||||||
|
steps += 1;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if pc < 0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
steps
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_example() {
|
fn test_example() {
|
||||||
let jumps = vec![0, 3, 0, 1, -3];
|
let jumps = vec![0, 3, 0, 1, -3];
|
||||||
assert_eq!(steps_to_exit(&jumps), 5);
|
assert_eq!(steps_to_exit(&jumps), 5);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Using this rule with the above example, the process now takes 10 steps, and the offset values
|
||||||
|
// after finding the exit are left as 2 3 2 3 -1.
|
||||||
|
#[test]
|
||||||
|
fn test_example_part2() {
|
||||||
|
let jumps = vec![0, 3, 0, 1, -3];
|
||||||
|
assert_eq!(steps_to_exit_part2(&jumps), 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue