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, and—due 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; endendif 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;endenddisp(['The pirate fell off to the left ',num2str(leftfall),' times.']) disp(['This was ',num2str(leftfall/(leftfall+rightfall)*100),'% of the time.'])
Best Answer