% Program  levelcrs.m
%
% This MATLAB code simulates tosses of a coin with probability p
% of getting a Head and 1-p of getting a Tail and counts the time
% until either the kth Head occurs or the mth Tail. 
%     You are prompted to supply the probability p, the 
% number k, the number m and the maximum number of tosses. 
% At the end, output will be a vector giving the times til
% either the kth Head or the mth Tail occurs. A total of 200 
% simulations are made. Also output are the fraction of 
% these simulations in which the kth Head occured before
% the mth Tail occured.
% A histogram summarizes the data on how long it took for
% the kth Head or mth Tail to occur, as well as the mean, median 
% and variance for this time. 
%
!c:
n=input('maximum times to toss the coin:    ')
p=input('probability of heads on a single toss:     ')
k=input('count time until what number of Heads occur:   ')
m=input('count time until what number of Tails occur:   ')
% nh will count the number of heads, nt the number of tails
x=[ ];
hcount=0;
tcount=0;
for j=1:200
nh=0;
nt=0;
i=0;
 while (nh < k & nt < m),
   i=i+1;
   a=rand(1,1);
      if a <= p
         nh=nh+1;
      else
         nt=nt+1;
      end;
  if i >= n
     i=k+10000;
     nh=k;  
  else;
  end;
 end;
 x=[x i];
 if nh==k
    hcount=hcount+1;
 else 
    tcount=tcount+1;
 end;
end;
me=mean(x);
s=std(x);
md=median(x);
prob=hcount/(hcount+tcount);
disp('number of simulations reaching k heads first is ') 
hcount,pause
disp('number of simulations reaching m tails first is ') 
tcount,pause
disp('fraction of time reach k heads first is ')
prob,pause
disp('mean, median and standard deviation of time to ')
k
disp('occurrence of head or  ')
m
disp('occurrence of tail are ')
me,md,s,pause
hist(x)
title('histogram of time distribution'),pause

