diff options
Diffstat (limited to 'rust/robot-simulator/src')
| -rw-r--r-- | rust/robot-simulator/src/lib.rs | 85 |
1 files changed, 85 insertions, 0 deletions
diff --git a/rust/robot-simulator/src/lib.rs b/rust/robot-simulator/src/lib.rs new file mode 100644 index 0000000..d6b6719 --- /dev/null +++ b/rust/robot-simulator/src/lib.rs | |||
| @@ -0,0 +1,85 @@ | |||
| 1 | // The code below is a stub. Just enough to satisfy the compiler. | ||
| 2 | // In order to pass the tests you can add-to or change any of this code. | ||
| 3 | |||
| 4 | #[derive(PartialEq, Debug)] | ||
| 5 | pub enum Direction { | ||
| 6 | North, | ||
| 7 | East, | ||
| 8 | South, | ||
| 9 | West, | ||
| 10 | } | ||
| 11 | |||
| 12 | pub struct Robot { | ||
| 13 | x: i32, | ||
| 14 | y: i32, | ||
| 15 | d: Direction, | ||
| 16 | } | ||
| 17 | |||
| 18 | impl Robot { | ||
| 19 | pub fn new(x: i32, y: i32, d: Direction) -> Self { | ||
| 20 | Robot { x, y, d } | ||
| 21 | } | ||
| 22 | |||
| 23 | pub fn turn_right(self) -> Self { | ||
| 24 | Robot { | ||
| 25 | d: { | ||
| 26 | use Direction::*; | ||
| 27 | match self.d { | ||
| 28 | North => East, | ||
| 29 | East => South, | ||
| 30 | South => West, | ||
| 31 | West => North, | ||
| 32 | } | ||
| 33 | }, | ||
| 34 | ..self | ||
| 35 | } | ||
| 36 | } | ||
| 37 | |||
| 38 | pub fn turn_left(self) -> Self { | ||
| 39 | Robot { | ||
| 40 | d: { | ||
| 41 | use Direction::*; | ||
| 42 | match self.d { | ||
| 43 | North => West, | ||
| 44 | East => North, | ||
| 45 | South => East, | ||
| 46 | West => South, | ||
| 47 | } | ||
| 48 | }, | ||
| 49 | ..self | ||
| 50 | } | ||
| 51 | } | ||
| 52 | |||
| 53 | pub fn advance(self) -> Self { | ||
| 54 | Robot { | ||
| 55 | x: match self.d { | ||
| 56 | Direction::West => self.x - 1, | ||
| 57 | Direction::East => self.x + 1, | ||
| 58 | _ => self.x, | ||
| 59 | }, | ||
| 60 | y: match self.d { | ||
| 61 | Direction::North => self.y + 1, | ||
| 62 | Direction::South => self.y - 1, | ||
| 63 | _ => self.y, | ||
| 64 | }, | ||
| 65 | ..self | ||
| 66 | } | ||
| 67 | } | ||
| 68 | |||
| 69 | pub fn instructions(self, instructions: &str) -> Self { | ||
| 70 | instructions.chars().fold(self, |acc, action| match action { | ||
| 71 | 'A' => acc.advance(), | ||
| 72 | 'R' => acc.turn_right(), | ||
| 73 | 'L' => acc.turn_left(), | ||
| 74 | _ => acc, | ||
| 75 | }) | ||
| 76 | } | ||
| 77 | |||
| 78 | pub fn position(&self) -> (i32, i32) { | ||
| 79 | (self.x, self.y) | ||
| 80 | } | ||
| 81 | |||
| 82 | pub fn direction(&self) -> &Direction { | ||
| 83 | &self.d | ||
| 84 | } | ||
| 85 | } | ||
