MATLAB: Near sighted pirate while loop

while loop

An incredibly near-sighted pirate has just finished burying his gold on an island and now must get back to his boat at the far end of a dock. He is having a difficult time getting to his boat.
The dock is 80 feet long and 16 feet wide
Each step he takes has a 75% chance of going forward towards his ship, anddue to a peg leg a 14% chance of going directly to the right, and an 11% chance of going directly to the left. Each step = 1 foot.
Write a script that uses the rand command to randomly generate a direction for the pirate to take for each step. Does he make it to the end of the dock to find his ship or does he fall off one of the sides before he gets there? (Assume the pirate can stand right on the edge of the dock)
Run up to 1 million trials and calculate a percent chance that he makes it to his boat using the trial results. Display this percentage back to the user.
stepx=0; %At zero he's centered on the dock
%When stepx<=-5, he falls off to the left
%When stepx>=5, he falls off to the right
leftfall=0;
rightfall=0;
for i=1:10^6 %1 million trials
stepx=0;
while stepx>-5 && stepx<5
chance=rand;
if chance<=0.75
stepx=stepx-1;
else
stepx=stepx+1;
end
end
if stepx<=-5
%I know that I fell off the dock to the left
leftfall=leftfall+1;
elseif stepx>=5
%I know that I fell of the dock to the right
rightfall=rightfall+1;
end
end
disp(['The pirate fell off to the left ',num2str(leftfall),' times.'])
disp(['This was ',num2str(leftfall/(leftfall+rightfall)*100),'% of the time.'])

Best Answer

In addition to keeping track of the pirate's position left or right of the center of the dock you need to keep track of how far from the shore he's walked. You don't have just a 1-dimensional random walk, you have a (constrained, since the pirate can't go backwards) 2-dimensional walk.
So from (0, 0) [representing the center of the dock, on the shore] the pirate has:
  • a 75% chance of going to (0, 1) [one step closer to the ship]
  • a 14% chance of going to (1, 0) [directly to the right, no closer to the ship] and
  • an 11% chance of going to (-1, 0) [directly to the left, no closer to the ship]
If you were to represent the pirate's location as a set of coordinates like this, what are the three termination conditions in terms of the coordinates?
The pirate reaches the boat if ...
The pirate falls off the right side of the dock if ...
The pirate falls off the left side of the dock if ...