Skip to content

Instantly share code, notes, and snippets.

@kuanb
Last active January 10, 2023 17:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kuanb/db7fe8a0a36416bf735a5316dfe7dcb3 to your computer and use it in GitHub Desktop.
Save kuanb/db7fe8a0a36416bf735a5316dfe7dcb3 to your computer and use it in GitHub Desktop.
Quick and gross sketch to play out logic puzzle about probability of last pax on plane getting their seat if a random pax goes "rogue" and takes seat not assigned to them
import random
class Passenger:
"""Passenger with seating ticket."""
def __init__(self, seat: int):
self.seat_assigned = seat
self.seat_taken = None
self.is_rogue = False # if rogue, pax will sit in wrong seat
def make_rogue(self):
self.is_rogue = True
def take_seat(self, seat_num: int):
self.seat_taken = seat_num
# we can check later if correct seat was taken for what portion of riders
self.took_correct_seat = self.seat_assigned == self.seat_taken
class Plane:
"""Class for plane object."""
def __init__(self, seat_count: int):
# initally no one is seated anywhere, plane empty
self.seats = [None] * seat_count
def seat_pax(self, pax: Passenger):
"""Check if seat is available for passenger and seat else seat elsewhere."""
if self.seats[pax.seat_assigned] is None and not pax.is_rogue:
# this means the seat is not yet taken so assign the pax to that seat
seat_num = pax.seat_assigned
else:
# otherwise we have rogue pax that took the wrong seat
remaining_seats = [i for i, s in enumerate(self.seats) if s is None]
random.shuffle(remaining_seats)
# grab a random next seat
seat_num = remaining_seats[0]
if pax.is_rogue and pax.seat_assigned == seat_num:
seat_num = remaining_seats[1]
# finally seat pax with secured open seat
pax.take_seat(seat_num)
self.seats[seat_num] = pax
def simulate(seat_count: int) -> bool:
"""Run simulation and return result of seating assing of last pax."""
# create the plane and passengers
plane = Plane(seat_count)
passengers = [Passenger(x) for x in range(seat_count)]
# the first passenger is the rule breaker
passengers[0].make_rogue()
# start seating process
[plane.seat_pax(p) for p in passengers]
last_pax = passengers[-1]
last_pax_got_assigned_seat = last_pax.seat_assigned == last_pax.seat_taken
return last_pax_got_assigned_seat
if __name__ == "__main__":
results = [simulate(100) for _ in range(5000)]
pct_last_pass_success = float(sum([1 for r in results if r]))/len(results)
print(f"Percent of times last passenger got their seat: {pct_last_pass_success}")
@kuanb
Copy link
Author

kuanb commented Jan 10, 2023

Results distribution will normalize around 50% of the time passenger will not get their assigned seat.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment