implement backward()

this has meant changing the type signature of forward()
so that it accepts the rover by reference not value, and
making Facing a Copy type so that the direction passed to
forward can also be returned in its output
This commit is contained in:
Daniel Barlow 2023-10-31 23:51:45 +00:00
parent d8c0a21985
commit a8e9ab810c

View File

@ -3,7 +3,7 @@ fn main() {
}
mod rover {
#[derive(Debug,PartialEq)]
#[derive(Debug, PartialEq, Copy, Clone)]
pub enum Facing { N, E, S, W }
type Rover = (i32, i32, Facing);
@ -17,12 +17,18 @@ mod rover {
}
}
pub fn forward((lon, lat, direction) : Rover) -> Rover {
pub fn forward((lon, lat, direction) : &Rover) -> Rover {
let (xoff, yoff) = velocity(&direction);
(lon + xoff as i32, lat + yoff as i32, direction)
(lon + xoff as i32, lat + yoff as i32, *direction)
}
pub fn backward((lon, lat, direction) : &Rover) -> Rover {
let (xoff, yoff) = velocity(&direction);
(lon - xoff as i32, lat - yoff as i32, *direction)
}
}
#[cfg(test)]
mod tests {
use super::*;
@ -30,32 +36,39 @@ mod tests {
#[test]
fn move_north() {
let r = (1 as i32, 1 as i32, rover::Facing::N);
assert_eq!(rover::forward(r),
assert_eq!(rover::forward(&r),
(1 as i32, 0 as i32, rover::Facing::N));
let r = (1 as i32, 3 as i32, rover::Facing::N);
assert_eq!(rover::forward(r),
assert_eq!(rover::forward(&r),
(1 as i32, 2 as i32, rover::Facing::N));
}
#[test]
fn move_south() {
let r = (1 as i32, 1 as i32, rover::Facing::S);
assert_eq!(rover::forward(r),
assert_eq!(rover::forward(&r),
(1 as i32, 2 as i32, rover::Facing::S));
}
#[test]
fn move_west() {
let r = (1 as i32, 1 as i32, rover::Facing::W);
assert_eq!(rover::forward(r),
assert_eq!(rover::forward(&r),
(0 as i32, 1 as i32, rover::Facing::W));
}
#[test]
fn move_east() {
let r = (1 as i32, 1 as i32, rover::Facing::E);
assert_eq!(rover::forward(r),
assert_eq!(rover::forward(&r),
(2 as i32, 1 as i32, rover::Facing::E));
}
#[test]
fn move_backward() {
let r = (1 as i32, 1 as i32, rover::Facing::E);
let r2 = rover::forward(&r);
assert_eq!(rover::backward(&r2), r);
}
}