• Source
    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.  
    7. counter.countNumberOfCars();
    8. }
    9. }
    10.  
    11. class Car {
    12. private boolean isLightOn;
    13.  
    14. Car() {
    15. switch((int) (Math.random() * 2)) {
    16. case 0:
    17. setLightOn(false);
    18.  
    19. break;
    20. case 1:
    21. setLightOn(true);
    22.  
    23. break;
    24. }
    25. }
    26.  
    27. void setLightOn(boolean isLightOn) {
    28. this.isLightOn = isLightOn;
    29. }
    30.  
    31. boolean isLightOn() {
    32. return isLightOn;
    33. }
    34. }
    35.  
    36. public class Train {
    37. private Car[] cars;
    38.  
    39. private int size;
    40.  
    41. Train(int minimalSize, int maximumSize) {
    42. size = minimalSize + (int) (Math.random() * (maximumSize - minimalSize + 1));
    43.  
    44. cars = new Car[size];
    45.  
    46. for(int i = 0; i < size; i++)
    47. cars[i] = new Car();
    48. }
    49.  
    50. Car getCar() {
    51. return cars[0];
    52. }
    53.  
    54. void goToNextCar() {
    55. Car temp = cars[0];
    56.  
    57. for(int i = 0; i < size - 1; i++)
    58. cars[i] = cars[i + 1];
    59.  
    60. cars[size - 1] = temp;
    61. }
    62.  
    63. void goToPreviousCar() {
    64. Car temp = cars[size - 1];
    65.  
    66. for(int i = size - 1; i > 0; i--)
    67. cars[i] = cars[i - 1];
    68.  
    69. cars[0] = temp;
    70. }
    71. }
    72.  
    73. public class Counter {
    74. private Train train;
    75.  
    76. Counter(Train train) {
    77. this.train = train;
    78. }
    79.  
    80. private int minimalNumberOfCars;
    81.  
    82. void countNumberOfCars() {
    83. int guess = guessNumberOfCars();
    84.  
    85. System.out.println("Number of cars where should stop: " + guess);
    86.  
    87. int i = 0;
    88.  
    89. while(true) {
    90. Car car = train.getCar();
    91.  
    92. i++;
    93.  
    94. if(i == guess) {
    95. car.setLightOn(true);
    96.  
    97. break;
    98. } else {
    99. car.setLightOn(false);
    100.  
    101. train.goToNextCar();
    102. }
    103. }
    104.  
    105. int numberOfCars = 0;
    106.  
    107. while(true) {
    108. train.goToPreviousCar();
    109.  
    110. Car car = train.getCar();
    111.  
    112. numberOfCars++;
    113.  
    114. if(car.isLightOn())
    115. break;
    116.  
    117. if(numberOfCars == guess && !car.isLightOn()) {
    118. minimalNumberOfCars = numberOfCars + 1;
    119.  
    120. countNumberOfCars();
    121. }
    122. }
    123.  
    124. System.out.println("Number of cars: " + numberOfCars);
    125. }
    126.  
    127. private int guessNumberOfCars() {
    128. int guess = minimalNumberOfCars + (int) (Math.random() * 10000);
    129.  
    130. return guess;
    131. }
    132. }