DEV Community

Discussion on: Assigned seats + missing ticket puzzle

Collapse
 
martinalexander profile image
Martin-Alexander • Edited

Here's my simulation in Ruby. I know that one million is overkill, Lol

Spoilers below ↓

class Threater
  def self.run(iterations = 1_000_000)
    last_person_got_seat = 0.0
    total_runs = 0.0

    iterations.times do |i|
      if i % 1000 == 0
        print("\rNΒΊ of iterations: #{i.to_s.ljust(iterations.to_s.length)}")
      end
      last_person_got_seat += 1 if new.last_person_got_seat
      total_runs += 1
    end

    last_person_got_seat / total_runs
  end

  def initialize(threater_size = 100)
    @seats = [nil] * threater_size
    @seats[random_seat] = 0 # 1st in line lost her 🎟

    (1...threater_size).to_a.each do |person_seat|
      seat_person(person_seat, person_seat)
    end
  end

  def last_person_got_seat
    @seats.last == 99
  end

  private

  def random_seat
    rand(0...@seats.length)
  end

  def seat_person(seat, person)
    if @seats[seat]
      seat_person(random_seat, person)
    else
      @seats[seat] = person
    end
  end
end


result = Threater.run
puts "\nResult: #{result}%"

It's 50%, apparently!