  function [x y] = BoundedRandomWalk2D(N, ns)
% N is a positive integer.
% Simulates a ns-step 2D random walk that is bounded in
% a (2N-1)-by-(2N-1) square.  
% 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:ns.

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

  % In general, (xc,yc) is the location after k hops.

  x = zeros(ns, 1);
  y = zeros(ns, 1);

  for k = 1:ns
      
%    Token at (xc,yc). 
     first = 1;     % Run the while loop for at least once
     nextx = xc;
     nexty = yc;
     
     % Repeatedly try until the token lies within the boundary
     while abs(nextx) >= N || abs(nexty) >= N || first
         first = 0;     % once the while loop is run, quit the loop if the 
                        % token lies within the boundary
         r = rand;
         if r <= .25
            nexty = yc+1; % Try hop North
         elseif r<=.50
            nextx = xc+1; % Try hop East
         elseif r < .75
            nexty = yc-1; % Try hop South
         else
            nextx = xc-1; % Try hop West
         end
     end
     
     xc = nextx;
     yc = nexty;

%    Save new location...
     x(k) = xc; y(k) = yc; 
  end
  