From c812b79363f9f85901d76f7d25ae201323baff7e Mon Sep 17 00:00:00 2001
From: Daniel Barlow <dan@telent.net>
Date: Wed, 1 Nov 2023 00:22:12 +0000
Subject: [PATCH] implement rotation

---
 src/main.rs | 38 ++++++++++++++++++++++++++++++++++++++
 1 file changed, 38 insertions(+)

diff --git a/src/main.rs b/src/main.rs
index da6b9ad..c816dac 100644
--- 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)
+	}
+    }
 }