% Drunk Sailor Problem. Calculation of probability for m and N
x=[];k=0;
m=5;%number of steps in the bar
Nmax=100;%for plotting graph
N=20;%number of steps given to sailor 
x(1)=1;% initial position of sailor
Ntest=50;%number of tests, the bigger the better 
for q=1:Ntest;
% individual test (realization)
    for i=1:N
        if x(i)==1;x(i+1)=2;
    else z=rand;if z<.5;x(i+1)=x(i)+1;else x(i+1)=x(i)-1;end;end
if x(i+1)==m+1;K=i+1;break;end
end
if i+1<N;k(q)=1;else;k(q)=0;end;%indication of exit
end
probab=sum(k)/Ntest %probability
%Plot the results
figure(1);plot(N,probab,'*k');axis([0 Nmax 0 1]);xlabel('number of steps given');
ylabel('probability to leave');hold on    