Created
October 30, 2013 15:01
-
-
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?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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