From 8beb899b36d22f536fc0b51c6700521f764a5a3d Mon Sep 17 00:00:00 2001 From: Wesley Moore Date: Sat, 9 Dec 2017 14:37:18 +1000 Subject: [PATCH] Add day 5 part 2 solution --- 2017/day/5/src/main.rs | 42 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/2017/day/5/src/main.rs b/2017/day/5/src/main.rs index 78a184f..221e38d 100644 --- a/2017/day/5/src/main.rs +++ b/2017/day/5/src/main.rs @@ -11,7 +11,10 @@ fn main() { .collect::>(); 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 { @@ -37,8 +40,45 @@ fn steps_to_exit(jump_offsets: &[i32]) -> i32 { 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] fn test_example() { let jumps = vec![0, 3, 0, 1, -3]; 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); +} +