Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- extern crate rand; // 0.6.0
- use rand::prelude::*;
- const NUMBER_BATCHES : usize = 10;
- const BATCH_SIZE : usize = 10000;
- fn main() {
- let mut hits_vec = Vec::with_capacity(NUMBER_BATCHES);
- for _ in 0..NUMBER_BATCHES {
- let mut hits = 0;
- for _ in 0..BATCH_SIZE {
- let mut chess_piece = ChessPiece{ position:(0,0) };
- for i in 0..64 {
- chess_piece.move_randomly();
- }
- if chess_piece.position == (0,0) {
- hits += 1;
- }
- }
- hits_vec.push(hits);
- }
- let average_hits : usize = hits_vec.iter().sum::<usize>() / hits_vec.len();
- println!("Average Hits per Batch: {}/{}", average_hits, BATCH_SIZE);
- }
- struct ChessPiece{
- position : (i8,i8)
- }
- impl ChessPiece {
- fn move_randomly(&mut self) {
- let moves = self.possible_moves();
- let mov = moves.choose(&mut rand::thread_rng()).unwrap();
- self.position = (self.position.0+mov.0,self.position.1+mov.1);
- }
- fn possible_moves(&self) -> Vec<(i8,i8)> {
- let mut moves = [Some((-1,0)),Some((0,1)),Some((1,0)),Some((0,-1)),Some((1,1)),Some((-1,-1)),Some((-1,1)),Some((1,-1))];
- if self.position.0 == 0 {
- moves[0] = None;
- moves[5] = None;
- moves[6] = None;
- }
- if self.position.1 == 0 {
- moves[1] = None;
- moves[5] = None;
- moves[7] = None;
- }
- if self.position.0 == 7 {
- moves[2] = None;
- moves[4] = None;
- moves[7] = None;
- }
- if self.position.1 == 7 {
- moves[3] = None;
- moves[4] = None;
- moves[6] = None;
- }
- let moves : Vec<(i8,i8)> = moves.iter().filter_map(|m| *m).collect();
- moves
- }
- }
Add Comment
Please, Sign In to add comment