we can drive a rover with sequence of commands as string

This commit is contained in:
Daniel Barlow 2023-11-02 23:16:04 +00:00
parent f09e4d4bee
commit e4bd2597d5

View File

@ -8,7 +8,7 @@ mod rover {
#[derive(Debug, PartialEq, Copy, Clone)]
pub enum Rotation { Left, Right }
type Rover = (i32, i32, Facing);
pub type Rover = (i32, i32, Facing);
fn velocity(direction : &Facing) -> (i32, i32) {
match direction {
@ -55,6 +55,29 @@ mod rover {
}
mod driver {
use super::rover;
fn perform_insn(command: &str, rover: &rover::Rover) -> rover::Rover {
match command {
"f" => rover::forward(&rover),
"b" => rover::backward(&rover),
"l" => rover::rotate(&rover, rover::Rotation::Left),
"r" => rover::rotate(&rover, rover::Rotation::Right),
_ => rover.clone()
}
}
pub fn execute(rover: &rover::Rover, instructions: &str) -> rover::Rover {
if instructions.is_empty() {
rover.clone()
} else {
let (first, rest) = instructions.split_at(1);
execute(&perform_insn(first, rover), rest)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
@ -112,4 +135,12 @@ mod tests {
(_, _, facing) => assert_eq!(facing, rover::Facing::W)
}
}
#[test]
fn drive() {
let r = (1 as i32, 1 as i32, rover::Facing::S);
assert_eq!(driver::execute(&r, "ffrf"),
(0 as i32, 3 as i32, rover::Facing::W));
}
}