Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2017
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.18 KB | None | 0 0
  1. public class Main {
  2. public static void main(String[] args) {
  3. Train train = new Train(5000, 5000);
  4.  
  5. Counter counter = new Counter(train);
  6. counter.countNumberOfCars();
  7. }
  8. }
  9.  
  10. class Train {
  11. private boolean[] lightsInCar;
  12. private int size;
  13. private int currentCarIndex;
  14. private static Random random = new Random();
  15.  
  16. Train(int minimalSize, int maximumSize) {
  17. size = minimalSize + (int) (Math.random() * (maximumSize - minimalSize + 1));
  18.  
  19. lightsInCar = new boolean[size];
  20.  
  21. for (int i = 0; i < size; i++) {
  22. lightsInCar[i] = random.nextBoolean();
  23. }
  24. currentCarIndex = 0;
  25. }
  26.  
  27. void gotoNextCar() {
  28. currentCarIndex = (currentCarIndex + 1) % size;
  29. }
  30.  
  31. void gotoPreviousCar() {
  32. currentCarIndex = (currentCarIndex + size - 1) % size;
  33. }
  34.  
  35. boolean getLigtsStatusInCar() {
  36. return lightsInCar[currentCarIndex];
  37. }
  38.  
  39. void setLigtsOnInCar(boolean status) {
  40. lightsInCar[currentCarIndex] = status;
  41. }
  42. }
  43.  
  44. class Counter {
  45. private Train train;
  46. private int minimalNumberOfCars;
  47.  
  48. Counter(Train train) {
  49. this.train = train;
  50. }
  51.  
  52. void countNumberOfCars() {
  53. int guess = guessNumberOfCars();
  54.  
  55. System.out.println("Number of cars where should stop: " + guess);
  56.  
  57. int i = 0;
  58.  
  59. while (true) {
  60.  
  61. i++;
  62.  
  63. if (i == guess) {
  64. train.setLigtsOnInCar(true);
  65. break;
  66. } else {
  67. train.setLigtsOnInCar(false);
  68. train.gotoNextCar();
  69. }
  70. }
  71.  
  72. int numberOfCars = 0;
  73.  
  74. while (true) {
  75. train.gotoPreviousCar();
  76.  
  77. numberOfCars++;
  78.  
  79. if (train.getLigtsStatusInCar()) {
  80. break;
  81. }
  82.  
  83. if (numberOfCars == guess && !train.getLigtsStatusInCar()) {
  84. minimalNumberOfCars = numberOfCars + 1;
  85. countNumberOfCars();
  86. }
  87. }
  88.  
  89. System.out.println("Number of cars: " + numberOfCars);
  90. }
  91.  
  92. private int guessNumberOfCars() {
  93. int guess = minimalNumberOfCars + (int) (Math.random() * 10000);
  94. return guess;
  95. }
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement