convert the other methods

This commit is contained in:
Daniel Barlow 2023-11-03 18:47:50 +00:00
parent 1cc78f1e54
commit 4f3fb62432

View File

@ -20,20 +20,6 @@ mod rover {
}
}
impl Rover {
pub fn forward(&self) -> Rover {
let Rover(lon, lat, direction) = self;
let (xoff, yoff) = velocity(&direction);
Rover(lon + xoff as i32, lat + yoff as i32, *direction)
}
}
pub fn backward(slf : &Rover) -> Rover {
let Rover(lon, lat, direction) = slf;
let (xoff, yoff) = velocity(&direction);
Rover(lon - xoff as i32, lat - yoff as i32, *direction)
}
fn next_direction(direction : Facing) -> Facing {
match direction {
Facing::N => Facing::W,
@ -41,21 +27,34 @@ mod rover {
Facing::S => Facing::E,
Facing::E => Facing::N,
}
}
pub fn rotate(slf : &Rover, rotation: Rotation) -> Rover {
let Rover(lon, lat, direction) = slf;
match rotation {
Rotation::Left => {
let new_d = next_direction(*direction);
Rover(*lon, *lat, new_d)
},
Rotation::Right => {
let new_d = next_direction(*direction);
let new_d = next_direction(new_d);
let new_d = next_direction(new_d);
Rover(*lon, *lat, new_d)
impl Rover {
pub fn forward(&self) -> Rover {
let Rover(lon, lat, direction) = self;
let (xoff, yoff) = velocity(&direction);
Rover(lon + xoff as i32, lat + yoff as i32, *direction)
}
pub fn backward(&self) -> Rover {
let Rover(lon, lat, direction) = self;
let (xoff, yoff) = velocity(&direction);
Rover(lon - xoff as i32, lat - yoff as i32, *direction)
}
pub fn rotate(&self, rotation: Rotation) -> Rover {
let Rover(lon, lat, direction) = self;
match rotation {
Rotation::Left => {
let new_d = next_direction(*direction);
Rover(*lon, *lat, new_d)
},
Rotation::Right => {
let new_d = next_direction(*direction);
let new_d = next_direction(new_d);
let new_d = next_direction(new_d);
Rover(*lon, *lat, new_d)
}
}
}
}
@ -68,9 +67,9 @@ mod driver {
fn perform_command(command: &str, rover: &rover::Rover) -> rover::Rover {
match command {
"f" => rover.forward(),
"b" => rover::backward(&rover),
"l" => rover::rotate(&rover, rover::Rotation::Left),
"r" => rover::rotate(&rover, rover::Rotation::Right),
"b" => rover.backward(),
"l" => rover.rotate(rover::Rotation::Left),
"r" => rover.rotate(rover::Rotation::Right),
_ => rover.clone()
}
}
@ -126,20 +125,20 @@ mod tests {
fn move_backward() {
let r = Rover(1 as i32, 1 as i32, rover::Facing::E);
let r2 = r.forward();
assert_eq!(rover::backward(&r2), r);
assert_eq!(r2.backward(), r);
}
#[test]
fn spin_left() {
let r = Rover(1 as i32, 1 as i32, rover::Facing::E);
match rover::rotate(&r, rover::Rotation::Left) {
match r.rotate(rover::Rotation::Left) {
Rover(_, _, facing) => assert_eq!(facing, rover::Facing::N)
}
}
#[test]
fn spin_right() {
let r = Rover(1 as i32, 1 as i32, rover::Facing::S);
match rover::rotate(&r, rover::Rotation::Right) {
match r.rotate(rover::Rotation::Right) {
Rover(_, _, facing) => assert_eq!(facing, rover::Facing::W)
}
}