dancing_droids/src/main.rs

91 lines
2.1 KiB
Rust
Raw Normal View History

2020-10-13 10:31:50 +02:00
use std::fs;
use std::io;
2020-10-17 18:16:40 +02:00
/// Struct to store robot position
2020-10-16 09:11:28 +02:00
struct Position {
2020-10-16 12:59:40 +02:00
x: u32,
y: u32,
2020-10-16 09:11:28 +02:00
}
2020-10-17 18:16:40 +02:00
/// A Robot *aka droid* is represented here.
/// Each robot must have a unique id.
2020-10-16 09:11:28 +02:00
struct Robot {
2020-10-16 12:59:40 +02:00
id: u32,
2020-10-16 09:11:28 +02:00
o: Orientation,
p: Position,
}
2020-10-17 18:16:40 +02:00
/// Enum to store all possible orientations.
2020-10-11 18:25:42 +02:00
enum Orientation {
2020-10-06 23:25:17 +02:00
N,
E,
S,
W,
2020-10-06 20:34:48 +02:00
}
2020-10-06 23:25:17 +02:00
2020-10-17 18:16:40 +02:00
/// Enum to store all possible instructions.
2020-10-11 18:25:42 +02:00
enum Instruction {
L,
R,
F,
}
2020-10-17 18:16:40 +02:00
/// Parse char and return corresponding orientation.
fn parse_orientation(c: char) -> Result<Orientation, &'static str> {
match c {
'N' => Ok(Orientation::N),
'E' => Ok(Orientation::E),
'S' => Ok(Orientation::S),
'W' => Ok(Orientation::W),
_ => Err("Invalid character, does not match any orientations"),
}
}
2020-10-17 18:16:40 +02:00
/// Parse char and return corresponding instruction.
fn parse_instruction(c: char) -> Result<Instruction, &'static str> {
match c {
'L' => Ok(Instruction::L),
'R' => Ok(Instruction::R),
'F' => Ok(Instruction::F),
_ => Err("Invalid character, does not match any instructions"),
}
}
2020-10-17 18:16:40 +02:00
/// Retrieve the content of a file and return it as a string.
fn open_file(filename: &str) -> io::Result<String> {
let content = fs::read_to_string(filename)?;
Ok(content)
}
fn main() {
let conf = open_file("two_robots.txt");
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_orientation() {
assert!(parse_orientation('N').is_ok());
assert!(parse_orientation('E').is_ok());
assert!(parse_orientation('S').is_ok());
assert!(parse_orientation('W').is_ok());
assert!(parse_orientation('Z').is_err());
}
#[test]
fn test_parse_instruction() {
assert!(parse_instruction('L').is_ok());
assert!(parse_instruction('R').is_ok());
assert!(parse_instruction('F').is_ok());
assert!(parse_instruction('Z').is_err());
}
2020-10-13 12:15:04 +02:00
#[test]
fn test_open_file() {
assert!(open_file("two_robots.txt").is_ok());
assert!(open_file("test_unexisting_file.extension").is_err());
}
}