Merge branch 'rand-orintation' into 'master'

generate random Orientation enum

See merge request mhart/DancingDroids!47
This commit is contained in:
Martin HART 2020-11-03 14:41:10 +01:00
commit dc98eddcf6
2 changed files with 29 additions and 0 deletions

View File

@ -8,3 +8,4 @@ edition = "2018"
[dependencies]
clap = "2.33.3"
rand = "0.7.3"

View File

@ -1,5 +1,10 @@
/// A Robot *aka droid* is represented here.
/// Each robot must have a unique id.
use rand::{
distributions::{Distribution, Standard},
Rng,
};
pub struct Robot {
pub id: u32,
pub o: Orientation,
@ -42,6 +47,7 @@ impl Robot {
}
/// Enum to store all possible orientations.
#[derive(Debug)]
pub enum Orientation {
N,
E,
@ -49,6 +55,17 @@ pub enum Orientation {
W,
}
impl Distribution<Orientation> for Standard {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Orientation {
match rng.gen_range(0, 3) {
0 => Orientation::N,
1 => Orientation::E,
2 => Orientation::S,
_ => Orientation::W,
}
}
}
/// Struct to store robot position.
#[derive(PartialEq, Eq, Hash)]
pub struct Position {
@ -101,6 +118,17 @@ pub fn print_robots(robot_pool: &Vec<Robot>) {
#[cfg(test)]
mod tests {
use super::*;
use std::any::type_name;
fn type_of<T>(_: T) -> &'static str {
type_name::<T>()
}
#[test]
fn test_rand_orientation() {
let o: Orientation = rand::random();
assert_eq!(type_of(o), "dancing_droid::robot::Orientation");
}
#[test]
fn test_new_robot() {