From 7b7e983e9a5e80f71b5cc1f92c5a38c4c7e96891 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tristan=20Dani=C3=ABl=20Maat?= Date: Sat, 12 Dec 2020 20:33:59 +0000 Subject: [PATCH] Complete day 12.2 --- day-12/src/main.rs | 64 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/day-12/src/main.rs b/day-12/src/main.rs index dc2ef28..6212c23 100644 --- a/day-12/src/main.rs +++ b/day-12/src/main.rs @@ -8,6 +8,10 @@ fn main() -> Result<(), Box> { let location = simulate_ship_movement(&actions); println!("{}", location.0.abs() + location.1.abs()); + // Part 2 + let location = simulate_waypoint_movement(&actions); + println!("{}", location.0.abs() + location.1.abs()); + Ok(()) } @@ -136,6 +140,48 @@ fn simulate_ship_movement(actions: &Vec) -> (i64, i64) { coords } +fn simulate_waypoint_movement(actions: &Vec) -> (i64, i64) { + let mut waypoint = (1, 10); + let mut ship = (0, 0); + + for action in actions { + match *action { + Action::North(amount) => { + waypoint.0 += amount as i64; + } + Action::South(amount) => { + waypoint.0 -= amount as i64; + } + Action::East(amount) => { + waypoint.1 += amount as i64; + } + Action::West(amount) => { + waypoint.1 -= amount as i64; + } + Action::Left(amount) => match amount % 360 { + 0 => {} + 90 => waypoint = (waypoint.1, -waypoint.0), + 180 => waypoint = (-waypoint.0, -waypoint.1), + 270 => waypoint = (-waypoint.1, waypoint.0), + _ => panic!("Only 90 degree turns allowed"), + }, + Action::Right(amount) => match amount % 360 { + 0 => {} + 90 => waypoint = (-waypoint.1, waypoint.0), + 180 => waypoint = (-waypoint.0, -waypoint.1), + 270 => waypoint = (waypoint.1, -waypoint.0), + _ => panic!("Only 90 degree turns allowed"), + }, + Action::Forward(amount) => { + ship.0 += waypoint.0 * amount as i64; + ship.1 += waypoint.1 * amount as i64; + } + } + } + + ship +} + #[cfg(test)] mod tests { use super::*; @@ -158,4 +204,22 @@ mod tests { Ok(()) } + + #[test] + fn test_simple2() -> Result<(), Box> { + let input = indoc!( + "F10 + N3 + F7 + R90 + F11 + " + ); + + let actions = parse_actions(&input)?; + let location = simulate_waypoint_movement(&actions); + assert_eq!(location.0.abs() + location.1.abs(), 286); + + Ok(()) + } }