A rust implementation of a simple exercise
| fn main() { | |
| println!("{:?}", robot_paths(6)); | |
| } | |
| #[derive(Clone)] | |
| struct Board { | |
| squares: Vec<Vec<bool>>, | |
| } | |
| impl Board { | |
| fn new(n: usize) -> Board { | |
| Board { | |
| squares: vec![vec![false; n]; n], | |
| } | |
| } | |
| fn toggle_piece(&mut self, i: usize, j: usize) { | |
| self.squares[i][j] = !self.squares[i][j]; | |
| } | |
| fn has_been_visited(&mut self, i: usize, j: usize) -> bool { | |
| self.squares[i][j] | |
| } | |
| } | |
| fn robot_paths(n: usize) -> usize { | |
| fn robot_paths(n: usize, board: &mut Board, i: usize, j: usize) -> usize { | |
| if i == n - 1 && j == n - 1 { | |
| return 1; | |
| } | |
| board.toggle_piece(i, j); | |
| let mut result = 0; | |
| for x in [(0, 1), (1, 0), (-1, 0), (0, -1)].iter() { | |
| let i = i as isize + x.0; | |
| let j = j as isize + x.1; | |
| if i >= 0 | |
| && j >= 0 | |
| && i < n as isize | |
| && j < n as isize | |
| && !board.has_been_visited(i as usize, j as usize) | |
| { | |
| result += robot_paths(n, board, i as usize, j as usize); | |
| } | |
| } | |
| board.toggle_piece(i, j); | |
| result | |
| } | |
| robot_paths(n, &mut Board::new(n), 0, 0) | |
| } | |
| #[cfg(test)] | |
| mod test { | |
| use super::*; | |
| #[test] | |
| fn it_works() { | |
| assert_eq!(8512, robot_paths(5)) | |
| } | |
| } |
This comment has been minimized.
This comment has been minimized.
josalhor
commented
Jan 8, 2019
|
i and j being Options seems completly unnecessary, I believe that could be slowing it down. |
This comment has been minimized.
This comment has been minimized.
BartMassey
commented
Jan 9, 2019
|
Some dumb little things:
|
This comment has been minimized.
This comment has been minimized.
ThomasdenH
commented
Jan 10, 2019
I'm really not sure about this. The API guidelines recommend the opposite. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
ErichDonGubler commentedJan 8, 2019
You're doing a LOT of cloning that seems unnecessary here. Let's fix that: