Problem 15 of Monte Carlo solutions to Fifty Challenging Problems...

(This is another part of the Fifty Problems series, a set of example applications of Monte Carlo methods. In each post, I present source code which answers a probabilistic question using simulated models of the underlying system.)

Problem 15: 8 boys and 7 girls are seated at random in a row of 15 seats. On the average, how many pairs of adjacent seats are taken by cootie-transmitting couples? (boys next to girls)
#!/usr/bin/env ruby


# The original problem is heteronormative bachelors
# and models.  I don't like that for various reasons,
# and cooties is funnier anyway.
# But, my code represents the "bachelors and models in
# marriagable couples" model of the original problem.
# We need a pool of bachelors and models:

class Pool
  def initialize
    @b = N_BACHELORS
    @m = N_MODELS

  def draw
    left = @b+@m
    return nil if left == 0
    r = rand(left)
    if r > @b
      @m -= 1
      return "M"
      @b -= 1
      return "B"

n_couples = 0

TRIALS.times do
  p =
  last_d = nil

  while d = p.draw()
    n_couples += 1 if last_d && last_d != d
    last_d = d

puts "After #{TRIALS}, got #{n_couples}."
puts "So, #{n_couples/TRIALS.to_f} on average"

I've been coding my way through Fifty Challenging Problems in Statistics with Solutions. This post is a part of the Fifty Challenging Problems series.

This was brought to you by Josh Myer. He has other fun things at his homepage.