Skip to content

Instantly share code, notes, and snippets.

@jonelf
Created May 24, 2012 06:41
Show Gist options
  • Save jonelf/2779846 to your computer and use it in GitHub Desktop.
Save jonelf/2779846 to your computer and use it in GitHub Desktop.
A line of 100 airline passengers is waiting to board a plane.
=begin
A line of 100 airline passengers is waiting to board a plane. They
each hold a ticket to one of the 100 seats on that flight. (For
convenience, let's say that the nth passenger in line has a ticket for
the seat number n.)
Unfortunately, the first person in line is crazy, and will ignore the
seat number on their ticket, picking a random seat to occupy. All of
the other passengers are quite normal, and will go to their proper
seat unless it is already occupied. If it is occupied, they will then
find a free seat to sit in, at random.
What is the probability that the last (100th) person to board the
plane will sit in their proper seat (#100)?
=end
def place_passenger(n)
if @seats[n] == :free
@seats[n] = :taken
else
new_seat = rand (1..Max_seat)
until (@seats[new_seat] == :free)
new_seat = rand (1..Max_seat)
end
@seats[new_seat] = :taken
end
end
Samples = 53280
Max_seat = 100
@seats = Array.new(Max_seat+1) {:free}
got_seat = 0
1.upto(Samples) do |i|
crazy_seat = rand (1..Max_seat)
@seats[crazy_seat] = :taken
2.upto(Max_seat-1) {|n| place_passenger(n) }
got_seat += 1 if @seats[Max_seat] == :free
@seats.fill(:free)
end
puts "The chance of getting the seat is about #{got_seat/Samples.to_f}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment