Question: Break to form new lines

Working on a code to create random lines. Here is the code: 

M:=1; N:=1500; R3:=rand(1..3): # M=lines, N=steps

for i from 1 to M do
   for j from 0 to N do
   if j=1 then X[i,1]:=1; Y[i,1]:=0;
    elif j>1 then
        if r=1 then X[i,j]:=2*X[i,j-1]-X[i,j-2]; Y[i,j]:=2*Y[i,j-1]-Y[i,j-2]
        elif r=2 then X[i,j]:=X[i,j-1]+Y[i,j-1]-Y[i,j-2]; Y[i,j]:=Y[i,j-1]-X[i,j-1]+X[i,j-2];
        elif r=3 then X[i,j]:=X[i,j-1]-Y[i,j-1]+Y[i,j-2]; Y[i,j]:=Y[i,j-1]+X[i,j-1]-X[i,j-2];
      end if;
    end if;
  end do:
end do:

Now the code works fine. But I don't want the lines to cross its own path. I want it to stop if R[i,j]=R[i,k] for any 0<k<i-2 for j=0..N. What I have so far is:

for i from 1 to M do
  for j from 1 to 40 do
    for k from 1 to j-2 do
     if R[i,j]=K[i,k] then x:=j; print(b[i]=j); break; end if;
     end do;
   end do;
end do;

Now it works aswell, but it doesn't stop when it hits the crossing point. I want it to stop so i get one b[i]=j per M. So I need it to break two for loops so that it goes through i M times and stops everytime it reaches a crossing point

Please Wait...