Complete day 12.2

This commit is contained in:
Tristan Daniël Maat 2020-12-12 20:33:59 +00:00
parent c0a6391e85
commit 7b7e983e9a
Signed by: tlater
GPG key ID: 49670FD774E43268

View file

@ -8,6 +8,10 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let location = simulate_ship_movement(&actions); let location = simulate_ship_movement(&actions);
println!("{}", location.0.abs() + location.1.abs()); println!("{}", location.0.abs() + location.1.abs());
// Part 2
let location = simulate_waypoint_movement(&actions);
println!("{}", location.0.abs() + location.1.abs());
Ok(()) Ok(())
} }
@ -136,6 +140,48 @@ fn simulate_ship_movement(actions: &Vec<Action>) -> (i64, i64) {
coords coords
} }
fn simulate_waypoint_movement(actions: &Vec<Action>) -> (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)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@ -158,4 +204,22 @@ mod tests {
Ok(()) Ok(())
} }
#[test]
fn test_simple2() -> Result<(), Box<dyn std::error::Error>> {
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(())
}
} }