# How do I simulate the drunken sailor with limits?

on
I wish to simulate the motion of a drunken sailor. Imagine a very inebriated sailor standing on the edge of a pier. The pier is X paces long and 2Y paces wide. His ship is at the end of the pier. He is located at the shore end of the pier directly in the center of the width. He starts walking toward (he thinks) the ship, but because of his condition he only has a 50% chance of moving toward the ship for each step. He has a 25% chance of moving directly left and a 25% chance of moving directly right.
A random number, r, equally distributed between 0 and 1 can be generated with the MATLAB rand function. The value of this random number will determine which way the sailor moves at each step. Remember he has a better chance of moving forward than left-right.
If during his journey the sailor’s position exceeds Y paces right or left he falls off the pier. If he exceeds X paces, he makes it safely back to the ship.
The basic algorithm is to have the sailor take a step by calling the random number generator and then incrementing the right/left/forward position of the sailor. This process is continued while the sailor is still on the pier. A single walk simulation ends when the sailor either falls off a side or reaches the ship. At this point the function will record a success or failure. The function then repeats the walk until n simulations have been executed. Then the function returns the fraction of successful walks.
I'm looking for a function sailor(X,Y,n) where the arguments are the length of the pier, the half width of the pier, and the number of times the simulation is to be repeated. The function should return the fraction of successful trips.
Comment
Watch Question

Do more with

EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
Here is my version.
``````function success_fraction = sailor(X,Y,n)
%Drunken sailor simulation.
%   X - length of the pier
%   Y - half width of the pier
%   n = number of trials
%   Sailor has 50% chance of moving toward the ship, and 25%
%   chance of moving to each side.
%
N_failure = 0;
steps = [1 0; 1 0; 0 -1; 0 1];
for ii=1:n
distX = 0;
distY = 0;
while distX < X
step = steps(randi(4,1),:);
distX = distX + step(1);
distY = distY + step(2);
if abs(distY) > Y
N_failure = N_failure +1;
break
end
end
end
success_fraction = (n - N_failure)/n;
``````

Commented:
I have to mention that RANDI function that I'm using to generate random integer numbers was introduced to MATLAB only in version 2008b.
http://www.mathworks.com/help/techdoc/rn/brqyzsl-1.html#brqyzsl-3

If you have older version you will have to substitute this function. Let me know if it's the case.

Do more with