Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Main {
- public static void main(String[] args) {
- Train train = new Train(5000, 5000);
- Counter counter = new Counter(train);
- counter.countNumberOfCars();
- }
- }
- class Train {
- private boolean[] lightsInCar;
- private int size;
- private int currentCarIndex;
- private static Random random = new Random();
- Train(int minimalSize, int maximumSize) {
- size = minimalSize + (int) (Math.random() * (maximumSize - minimalSize + 1));
- lightsInCar = new boolean[size];
- for (int i = 0; i < size; i++) {
- lightsInCar[i] = random.nextBoolean();
- }
- currentCarIndex = 0;
- }
- void gotoNextCar() {
- currentCarIndex = (currentCarIndex + 1) % size;
- }
- void gotoPreviousCar() {
- currentCarIndex = (currentCarIndex + size - 1) % size;
- }
- boolean getLigtsStatusInCar() {
- return lightsInCar[currentCarIndex];
- }
- void setLigtsOnInCar(boolean status) {
- lightsInCar[currentCarIndex] = status;
- }
- }
- class Counter {
- private Train train;
- private int minimalNumberOfCars;
- Counter(Train train) {
- this.train = train;
- }
- void countNumberOfCars() {
- int guess = guessNumberOfCars();
- System.out.println("Number of cars where should stop: " + guess);
- int i = 0;
- while (true) {
- i++;
- if (i == guess) {
- train.setLigtsOnInCar(true);
- break;
- } else {
- train.setLigtsOnInCar(false);
- train.gotoNextCar();
- }
- }
- int numberOfCars = 0;
- while (true) {
- train.gotoPreviousCar();
- numberOfCars++;
- if (train.getLigtsStatusInCar()) {
- break;
- }
- if (numberOfCars == guess && !train.getLigtsStatusInCar()) {
- minimalNumberOfCars = numberOfCars + 1;
- countNumberOfCars();
- }
- }
- System.out.println("Number of cars: " + numberOfCars);
- }
- private int guessNumberOfCars() {
- int guess = minimalNumberOfCars + (int) (Math.random() * 10000);
- return guess;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement