% Random walk in 2 dimensions in a city with n*n blocks
% with a trap
% Goal: find average number of steps to get out the city
%       if the initial position is random
itests = 5000;       % number of tests
rng('shuffle');      % seed random number generator
fprintf('   Random Walk 3 \n')
fprintf('    L     free    trapped \n')
% fileID = fopen('random2.txt','w');      %writing to a file

ncity=0;

while ncity < 20
   free = 0;
   trap = 0;
   ncity = ncity+2;
   stotal = 0;
   for it=1:itests 
    x = randi([0 ncity],1,1);  %initial random position along x
    y = randi([0 ncity],1,1);  %initial random position along y
    trapx = ncity/2;
    trapy = ncity/2;
    nsteps = 0;
    out = 0;
    while (out == 0)
        nsteps = nsteps+1;
        iway = randi([0 3],1,1);
        switch iway
            case 0
            x = x + 1;
            case 1
            x = x - 1;
            case 2
            y = y + 1;
            case 3
            y = y - 1;
        end  %switch
        if x < 0 || x > ncity || y < 0 || y > ncity % if out of city
            out=1;
            free = free+1;
            break;
        end
        if x==trapx && y==trapy
            out=1;
            trap = trap + 1;
        end
    end %while
    stotal = stotal + nsteps;
end %for
%  average number of steps
asteps = double(stotal)/double(itests);
afree =  double(free)/double(itests);
atrap =  double(trap)/double(itests);
fprintf('%5i     %5.3f   %5.3f\n', ncity, afree, atrap)  
%fprintf(fileID,'%5i     %5.2f\n', ncity, asteps);
end %while



