Problem 35 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 35: After imbibing a few too many, a drunk man finds himself stumbling at the edge of a cliff. One step to the left will send him over, so he's trying to move right as well as he can. Except that he's drunk, so he only moves to the right with probability 2/3. What are his chances of living into sobriety?
#!/usr/bin/env ruby


POS_START=1  # Initial position

# Probability of a step in the positive direction

# What position he should be at to "get away"
# Note that this doesn't actually guarantee that our friend
# lives to the morrow, but it's close enough.
GOT_AWAY = 100000

MAX_STEPS = 1000000 # How long do we wait?


TRIALS.times do
  pos = POS_START
  steps = 0

  while (pos > 0 && pos < GOT_AWAY && steps < MAX_STEPS)
    pos += rand() < P_POSITIVE ? 1 : -1
    steps += 1

  losses += 1 if (pos == 0)
  wins += 1 if (pos > 0)


print "Wins: #{wins}, losses: #{losses}"

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.