Guest User

Untitled

a guest
Nov 21st, 2018
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. extern crate rand; // 0.6.0
  2. use rand::prelude::*;
  3.  
  4. const NUMBER_BATCHES : usize = 10;
  5. const BATCH_SIZE : usize = 10000;
  6.  
  7. fn main() {
  8. let mut hits_vec = Vec::with_capacity(NUMBER_BATCHES);
  9. for _ in 0..NUMBER_BATCHES {
  10. let mut hits = 0;
  11. for _ in 0..BATCH_SIZE {
  12. let mut chess_piece = ChessPiece{ position:(0,0) };
  13. for i in 0..64 {
  14. chess_piece.move_randomly();
  15. }
  16. if chess_piece.position == (0,0) {
  17. hits += 1;
  18. }
  19. }
  20. hits_vec.push(hits);
  21. }
  22. let average_hits : usize = hits_vec.iter().sum::<usize>() / hits_vec.len();
  23. println!("Average Hits per Batch: {}/{}", average_hits, BATCH_SIZE);
  24. }
  25.  
  26. struct ChessPiece{
  27. position : (i8,i8)
  28. }
  29.  
  30. impl ChessPiece {
  31. fn move_randomly(&mut self) {
  32. let moves = self.possible_moves();
  33. let mov = moves.choose(&mut rand::thread_rng()).unwrap();
  34. self.position = (self.position.0+mov.0,self.position.1+mov.1);
  35. }
  36.  
  37. fn possible_moves(&self) -> Vec<(i8,i8)> {
  38. 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))];
  39. if self.position.0 == 0 {
  40. moves[0] = None;
  41. moves[5] = None;
  42. moves[6] = None;
  43. }
  44. if self.position.1 == 0 {
  45. moves[1] = None;
  46. moves[5] = None;
  47. moves[7] = None;
  48. }
  49. if self.position.0 == 7 {
  50. moves[2] = None;
  51. moves[4] = None;
  52. moves[7] = None;
  53. }
  54. if self.position.1 == 7 {
  55. moves[3] = None;
  56. moves[4] = None;
  57. moves[6] = None;
  58. }
  59. let moves : Vec<(i8,i8)> = moves.iter().filter_map(|m| *m).collect();
  60. moves
  61. }
  62. }
Add Comment
Please, Sign In to add comment