Question: Random walk problem

I have made an algorithm for producing random walks (only possible to walk one step to either direction except downwards(EDIT: It is possible to go downwards, but it has to be when making a turn to the right or left). The walks are determined by the rand function:

R3:=rand(1..3): (1: go straight on; 2: turn right; 3: turn left)
M:=15; N:=1500;

 

Randwalk3:=proc(R3)
  local i,j,r,X,Y,L;
  for j from 1 to M do
    X[0,j]:=0;                                # Initialization
    Y[0,j]:=0;
    X[1,j]:=1;                                # The first step should still be taken to the point (1,0)
    Y[1,j]:=0;
    for i from 2 to N do
      r:=R3();
      if r=1 then X[i,j]:=2*X[i-1,j]-X[i-2,j]; Y[i,j]:=2*Y[i-1,j]-Y[i-2,j];                   # go straight on
      elif r=2 then X[i,j]:=X[i-1,j]+Y[i-1,j]-Y[i-2,j]; Y[i,j]:=Y[i-1,j]-X[i-1,j]+X[i-2,j];    # turn right
      else X[i,j]:=X[i-1,j]-Y[i-1,j]+Y[i-2,j]; Y[i,j]:=Y[i-1,j]+X[i-1,j]-X[i-2,j];             # turn left
      end if;
      if (X[i,j]=X[j,j] and Y[i,j]=Y[j,j]) then L[j]:=i; break; end if; (This is wrong)
    end do;
  end do:
  return [X,Y,L];
end proc:
 

The question from is like this:
Modify the algorithm such that it stops at r[i] if r[i] = r[j] for any 0 <= j <= i-2. r=(xi,yi). M is the number of random walks and N is the number of steps. The length of the paths should be stored in L[m] (m=1..M). How do I implement the if-test correctly?

Please Wait...