commit c812b79363f9f85901d76f7d25ae201323baff7e
parent a8e9ab810cbddd224fcee2fd633f041343f60b6f
Author: Daniel Barlow <dan@telent.net>
Date: Wed, 1 Nov 2023 00:22:12 +0000
implement rotation
Diffstat:
| M | src/main.rs | | | 38 | ++++++++++++++++++++++++++++++++++++++ |
1 file changed, 38 insertions(+), 0 deletions(-)
diff --git a/src/main.rs b/src/main.rs
@@ -5,6 +5,8 @@ fn main() {
mod rover {
#[derive(Debug, PartialEq, Copy, Clone)]
pub enum Facing { N, E, S, W }
+ #[derive(Debug, PartialEq, Copy, Clone)]
+ pub enum Rotation { Left, Right }
type Rover = (i32, i32, Facing);
@@ -26,6 +28,27 @@ mod rover {
let (xoff, yoff) = velocity(&direction);
(lon - xoff as i32, lat - yoff as i32, *direction)
}
+
+ fn next_direction(direction : Facing) -> Facing {
+ match direction {
+ Facing::N => Facing::W,
+ Facing::W => Facing::S,
+ Facing::S => Facing::E,
+ Facing::E => Facing::N,
+ }
+ }
+
+ pub fn rotate((lon, lat, direction) : &Rover, rotation: Rotation) -> Rover {
+ if rotation == Rotation::Left {
+ let new_d = next_direction(*direction);
+ (*lon, *lat, new_d)
+ } else {
+ let new_d = next_direction(*direction);
+ let new_d = next_direction(new_d);
+ let new_d = next_direction(new_d);
+ (*lon, *lat, new_d)
+ }
+ }
}
@@ -71,4 +94,19 @@ mod tests {
let r2 = rover::forward(&r);
assert_eq!(rover::backward(&r2), r);
}
+
+ #[test]
+ fn spin_left() {
+ let r = (1 as i32, 1 as i32, rover::Facing::E);
+ match rover::rotate(&r, rover::Rotation::Left) {
+ (_, _, facing) => assert_eq!(facing, rover::Facing::N)
+ }
+ }
+ #[test]
+ fn spin_right() {
+ let r = (1 as i32, 1 as i32, rover::Facing::S);
+ match rover::rotate(&r, rover::Rotation::Right) {
+ (_, _, facing) => assert_eq!(facing, rover::Facing::W)
+ }
+ }
}