function Lab6()

% (a)
clc
disp('Part (a)')
disp(' ')
% Number of trials used to estimate the happy exit probability...
nWalks = 10000;
for N = 10:5:25
% Determine the probability of a happy exit for this N.
happyCount = 0;
% Count how many times we have a happy exit...
for i=1:nWalks
% (xc,yc) is the location of the tokem at the end..
[x,y] = RandWalk(N);
xc = x(length(x));
yc = y(length(y));
% There are four possibilities to check...
if (xc==N&&yc==0) || (xc==0&&yc==N) || (xc==-N&&yc==0) || (xc==0 && yc==-N)
happyCount = happyCount+1;
end
end
prob = happyCount/nWalks;
fprintf('N = %2d ProbHappy= %5.3f\n',N,prob)
end

% (b)
disp(' ')
disp('Part (b)')
N = 20;
rand('seed',0)
m = CrossThe45(N);
disp(' ')
fprintf('m = %1d\n',m)

% (c)
countN = 0; countE = 0; countS = 0; countW = 0;
for i= 1:100000
[x,y] = RandWalkMod(20);
xc = x(length(x));
yc = y(length(y));
if yc==20
countN=countN+1;
elseif xc==20
countE=countE+1;
elseif yc==-20
countS=countS+1;
else
countW=countW+1;
end
end
disp(' ')
disp('Part (c):')
disp(' ')
fprintf('NorthExits = %5d\nEastExits = %5d\nSouthExits = %5d\nWestExits = %5d\n',countN,countE,countS,countW)

function m = CrossThe45(N)
% For a length-N random walk, m is the number of times that the token
% crosses the 45 degree line.
[x,y] = RandWalk(N);
count = 0;
for k=2:length(x)-1
% There may be a crossing if the token is on the line
if x(k)==y(k)
% Crossing if before the token is above the line and is below
% after, OR, if before it is below the line and after it is
% above...
if ((x(k-1)>y(k-1))&&(x(k+1)<y(k+1))) || ((x(k-1)<y(k-1))&&(x(k+1)>y(k+1)))
count=count+1;
end
end
end
m = count;

function [x,y] = RandWalkMod(N)
% Simulate a 2D random walk in an (2N+1)-by-(2N+1) grid.
% N is a positive integer.
% Walk starts from the origin and continues until the an edge, abs(N),
% is reached.
% x and y are row vectors with the property that (x(k),y(k)) is the
% location of the token after k hops, k=1:length(x).

% Initializations...
k = 0; xc = 0; yc=0;

% (xc,yc) is the location after k hops.
pN = 2/9; pE = 1/9; pS = 4/9; pW = 2/9;
while abs(xc)<N && abs(yc)<N
% Standing at (xc,yc), randomly select a step
r = rand(1);
if r < pN
yc = yc + 1; % north
elseif r < pN+pE
xc = xc + 1; % east
elseif r < pN+pE+pS
yc = yc - 1; % south
else
xc = xc - 1; % west
end
% Record location...
k= k + 1; x(k)= xc; y(k)= yc;
end