Skip to content

Instantly share code, notes, and snippets.

@ddimtirov
Created October 30, 2013 15:01
Show Gist options
  • Save ddimtirov/7234126 to your computer and use it in GitHub Desktop.
Save ddimtirov/7234126 to your computer and use it in GitHub Desktop.
Imagine people boarding a plane and the first one sits at the wrong place. Every next one sits at his own place if it is available, or at a random place if not. What is the chance that the last person boarded sits at his own place?
import java.util.Arrays;
import java.util.Random;
public class WrongSeatSimulation {
private static final int AVAILABLE = -1;
static boolean simulate(Random rnd, int numberOfSeats) {
int[] seats = new int[numberOfSeats];
Arrays.fill(seats, AVAILABLE);
seats[rnd.nextInt(numberOfSeats-1) + 1] = 0;
boolean ownSeat;
for (int i=1; i<seats.length; i++) {
int available;
if (seats[i]==AVAILABLE) {
available = i;
} else {
do {
available = rnd.nextInt(numberOfSeats);
} while (seats[available]!=AVAILABLE);
}
seats[available] = i;
for (int j = 0; j < seats.length; j++) System.out.print(
seats[j]==j ? "O" :
seats[j]==AVAILABLE ? "." : "X"
);
System.out.println();
}
return seats[numberOfSeats-1] == numberOfSeats-1;
}
private static double simulateMany(Random rnd, int numberOfSeats, int rounds) {
double pct = 0;
for (int i=1; i<rounds; i++) {
if (simulate(rnd, numberOfSeats)) pct++;
}
return pct / rounds * 100;
}
public static void main(String[] args) {
Random rnd = new Random();
System.out.printf("%.2f\n", simulateMany(rnd, 100, 100));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment