This commit is contained in:
Volodymyr Patuta 2020-10-28 19:12:30 +01:00
parent 0931835850
commit b8929887b5
1 changed files with 19 additions and 15 deletions

View File

@ -13,34 +13,30 @@ impl Robot {
Robot { id, o, p, i }
}
/// Apply given instruction to a `Robot`.
fn execute_instruction(
&mut self,
hash: &mut std::collections::HashMap<Position, u32>,
) -> Result<(), &'static str> {
hash.remove(&self.p); // we need to insert the new position after calling execute_instruction()
fn execute_instruction(&mut self) {
match self.i.pop() {
Some(instruction) => match instruction {
'L' => Ok(match self.o {
'L' => match self.o {
Orientation::N => self.o = Orientation::W,
Orientation::E => self.o = Orientation::N,
Orientation::S => self.o = Orientation::E,
Orientation::W => self.o = Orientation::S,
}),
'R' => Ok(match self.o {
},
'R' => match self.o {
Orientation::N => self.o = Orientation::E,
Orientation::E => self.o = Orientation::S,
Orientation::S => self.o = Orientation::W,
Orientation::W => self.o = Orientation::N,
}),
'F' => Ok(match self.o {
},
'F' => match self.o {
Orientation::N => self.p.y += 1,
Orientation::E => self.p.x += 1,
Orientation::S => self.p.y -= 1,
Orientation::W => self.p.x -= 1,
}),
_ => Err("Invalid instruction."),
},
_ => (),
},
None => Ok(()),
None => (),
}
}
}
@ -85,10 +81,18 @@ mod tests {
0,
Orientation::N,
Position { x: 1, y: 2 },
vec!['R', 'L', 'F', 'F'],
vec!['R', 'F', 'L', 'F'],
);
assert!(r.execute_instruction().is_ok());
let mut hash = std::collections::HashMap::new();
//hash.insert(&r.p, &r.id); // first insert while initializing.
hash.remove(&r.p); // remove before execute_instruction().
r.execute_instruction();
hash.insert(&r.p, &r.id); // second insert after moving.
assert_eq!(r.p.x, 1);
assert_eq!(r.p.y, 3);
r.execute_instruction();
r.execute_instruction();
assert_eq!(r.p.x, 0);
assert_eq!(r.p.y, 3);
}
}