% PROGRAM level2.m
% This MATLAB code simulates tosses of a coin with probability p
% of getting a Head and 1-p of getting a Tail and 
% determines the fraction of experiments in which k heads
% occur before m tails occur. Thus, this is the level-crossing
% calculation in which, starting with a capital $Q, and for which
% you gain $1 for each Head and lose $1 for each tail, you determine
% the fraction of games in which you obtain a capital of
% $Q+k before your capital is reduced to $Q-m.
% You are prompted to supply
% the probability p, the number k, and the number m. 
% At the end, output will be a vector, x, giving the times til
% the kth Head occurs (given that the kth head occurs before
% the mth tail), a vector y giving the times til the mth
% tail occurs (given that mth tail occurs before the kth head), 
% and a vector z giving the time til either the kth head occurs 
% or the mth tail. 
% A total of 200 simulations are made.
% A histogram summarizes the data, as well as the mean and
% variance being calculated 
%
!c:
p=input('probability of heads on a single toss:     ')
k=input('count time until what number of Heads occur:   ')
m=input('or until what number of tails occur:')
% nh will count the number of heads, nt the number of tails
x=[ ];
y=[ ];
z=[ ];
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;
 end;
% The vector z contains the times til the kth head or mth tail
% occurred, x contains just these times when the kth Head occurred
% first and y contains just these times when the mth Tail occurred
% first. 
 z=[z i];
 if nh==k
   x=[x i];
   hcount=hcount+1;
  else
   y=[y i];
   tcount=tcount+1;
 end;
end;
pr=hcount/(hcount+tcount);
disp('probability of k heads before m tails is: k,m,prob')
k,m,pr,pause
me=mean(x);
s=std(x);
md=median(x);
disp('mean, median and standard deviation of time to ')
k
disp('occurrence of head are ')
me,md,s,pause
hist(x)
title('histogram of time distribution til kth Head'),pause
me=mean(y);
s=std(y);
md=median(y);
disp('mean, median and standard deviation of time to ')
m
disp('occurrence of tail are ')
me,md,s,pause
hist(y)
title('histogram of time distribution til mth Tail'),pause
me=mean(z);
s=std(z);
md=median(z);
disp('mean, median and standard deviation of time to exit')
me,md,s,pause
hist(z)
title('histogram of time distribution to exit'),pause


