Advertisement
Guest User

Untitled

a guest
Dec 6th, 2019
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class Main {
  4. static final int MAX_NUMBERS = 100;
  5. static final int GOAL = 100;
  6. static final int NUMBER_OF_RUNS = 1000;
  7.  
  8. static int current = 0;
  9. static int numMoves = 0;
  10.  
  11. public static void main(String[] args) {
  12. int totalNumMoves = 0;
  13.  
  14. // run the simulation multiple times
  15. for (int i = 0; i < NUMBER_OF_RUNS; i++) {
  16. int numMovesForRun = run();
  17. totalNumMoves += numMovesForRun;
  18. }
  19.  
  20. // average out the number of moves it took per run to reach the goal
  21. double averageNumMoves = 1.0 * totalNumMoves / NUMBER_OF_RUNS;
  22. System.out.println("Average number of moves: " + averageNumMoves);
  23. }
  24.  
  25. // runs the simluation once, starting from 0
  26. private static int run() {
  27. current = 0;
  28. numMoves = 0;
  29.  
  30. while (current != GOAL) {
  31. if (shouldRandom()) {
  32. random();
  33. } else {
  34. next();
  35. }
  36. numMoves++;
  37. }
  38.  
  39. return numMoves;
  40. }
  41.  
  42. // this method is the strategy that determines whether the simulation should
  43. // random or next; overwrite this method to implement your own strategy
  44. private static boolean shouldRandom() {
  45. double distanceToGoal = computeDistanceToGoal();
  46.  
  47. // where X is distance to goal
  48. double oddsOfGettingFartherAfterXRandoms = Math.pow(1 - distanceToGoal / MAX_NUMBERS, distanceToGoal);
  49. if (oddsOfGettingFartherAfterXRandoms < 1.0 * distanceToGoal / MAX_NUMBERS) {
  50. return true;
  51. } else {
  52. return false;
  53. }
  54. }
  55.  
  56. private static void next() {
  57. current++;
  58. }
  59.  
  60. private static void random() {
  61. Random rng = new Random();
  62. current = rng.nextInt(100) + 1; // +1 beacuse Random starts at 0
  63. }
  64.  
  65. private static int computeDistanceToGoal() {
  66. if (GOAL > current) {
  67. return GOAL - current;
  68. } else {
  69. return MAX_NUMBERS - current + GOAL;
  70. }
  71. }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement