function Crossing()
N = 20;
rand('seed',0)
m = CrossThe45(N)

function m = CrossThe45(N)
% Run the simulation...
[x,y] = RandWalk(N);
% The number of robot hops...
n = length(x);
% A counter for the number of crossings...
m = 0;
% Fact: It takes two hops to cross the 45 degree line. In between
% those two hops the robot is ON the 45 degree line.
% So we basically ask, if after k hops the robot is currently on the
% 45 degree line, where was it before and where is it after?
% (This check makes no sense if k = 1 or k=n)
for k=2:n-1
% Check to see if (x(k),y(k)) is on the 45 degree
% line and that (x(k-1),y(k-1)) and (x(k+1),y(k+1))
% are on different sides...
if x(k)==y(k)
% On the line!
% The following is true if the robot was below during the
% prior step...
Before = x(k-1)>y(k-1);
% The following is true if the robot was below during the
% following step...
After = x(k+1)>y(k+1);
% These have to be different for there to be a crossing...
if (Before && ~After) || (~Before && After)
m = m+1;
end
end
end