Created
May 6, 2020 17:28
-
-
Save davidwhitney/e0f7ae20e1431d7c6b139387b12b15ba to your computer and use it in GitHub Desktop.
Rusty Mars Rover
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[package] | |
name = "rover" | |
version = "0.1.0" | |
authors = ["David Whitney <[email protected]>"] | |
edition = "2018" | |
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html | |
[dependencies] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
5 5 <-- grid size | |
1 2 N < -- location of rover | |
LMLMLMLMM <---- directions | |
3 3 E <--- another rover | |
MMRMMRMRRM <--- other directions | |
Output: | |
1 3 N | |
5 1 E | |
*/ | |
pub fn main() { | |
calc(1, 2, 'N', "LMLMLMLMM"); | |
println!("======="); | |
calc(3, 3, 'E', "MMRMMRMRRM"); | |
} | |
fn calc(x: i32, y: i32, facing: char, instructions: &str) { | |
let mut _x = x; | |
let mut _y = y; | |
let mut _facing = facing; | |
let compass: [char; 4] = ['N', 'E', 'S', 'W']; | |
let mut _facing_index: i32 = compass.iter().position(|&s| s == _facing).unwrap() as i32; | |
let mut iterator = instructions.chars(); | |
for _i in 0..instructions.chars().count() { | |
let ch = iterator.next().unwrap(); | |
match ch { | |
'L' => { | |
_facing_index = if _facing_index == 0 { | |
(compass.len() as i32) - 1 | |
} else { | |
_facing_index - 1 | |
} | |
} | |
'R' => { | |
_facing_index = if _facing_index == 3 { | |
0 | |
} else { | |
_facing_index + 1 | |
} | |
} | |
'M' => match _facing { | |
'N' => _y = _y + 1, | |
'E' => _x = _x + 1, | |
'S' => _y = _y - 1, | |
'W' => _x = _x - 1, | |
_ => {} | |
}, | |
_ => {} | |
} | |
_facing = compass[_facing_index as usize]; | |
} | |
println!("{0}, {1}, {2}", _x, _y, _facing); | |
} | |
#[cfg(test)] | |
mod tests { | |
// Note this useful idiom: importing names from outer (for mod tests) scope. | |
use super::*; | |
#[test] | |
fn test_add() { | |
// assert_eq!(add(1, 2), 3); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment