public class Main {
public static void main
(String[] args
) { Train train = new Train(5000, 5000);
Counter counter = new Counter(train);
counter.countNumberOfCars();
}
}
class Car {
private boolean isLightOn;
Car() {
switch((int) (Math.
random() * 2)) { case 0:
setLightOn(false);
break;
case 1:
setLightOn(true);
break;
}
}
void setLightOn(boolean isLightOn) {
this.isLightOn = isLightOn;
}
boolean isLightOn() {
return isLightOn;
}
}
public class Train {
private Car[] cars;
private int size;
Train(int minimalSize, int maximumSize) {
size
= minimalSize
+ (int) (Math.
random() * (maximumSize
- minimalSize
+ 1));
cars = new Car[size];
for(int i = 0; i < size; i++)
cars[i] = new Car();
}
Car getCar() {
return cars[0];
}
void goToNextCar() {
Car temp = cars[0];
for(int i = 0; i < size - 1; i++)
cars[i] = cars[i + 1];
cars[size - 1] = temp;
}
void goToPreviousCar() {
Car temp = cars[size - 1];
for(int i = size - 1; i > 0; i--)
cars[i] = cars[i - 1];
cars[0] = temp;
}
}
public class Counter {
private Train train;
Counter(Train train) {
this.train = train;
}
private int minimalNumberOfCars;
void countNumberOfCars() {
int guess = guessNumberOfCars();
System.
out.
println("Number of cars where should stop: " + guess
);
int i = 0;
while(true) {
Car car = train.getCar();
i++;
if(i == guess) {
car.setLightOn(true);
break;
} else {
car.setLightOn(false);
train.goToNextCar();
}
}
int numberOfCars = 0;
while(true) {
train.goToPreviousCar();
Car car = train.getCar();
numberOfCars++;
if(car.isLightOn())
break;
if(numberOfCars == guess && !car.isLightOn()) {
minimalNumberOfCars = numberOfCars + 1;
countNumberOfCars();
}
}
System.
out.
println("Number of cars: " + numberOfCars
); }
private int guessNumberOfCars() {
int guess
= minimalNumberOfCars
+ (int) (Math.
random() * 10000);
return guess;
}
}