The Recamán's sequence generates Natural numbers.

Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated.


If the conditions don't hold then a(n) = a(n-1) + n.



Task

 Generate and show here the first 15 members of the sequence.
 Find and show here, the first duplicated number in the sequence.
 Optionally: Find and show here, how many terms of the sequence are needed until all the integers 0..1000, inclusive, are generated.


References

 A005132, The On-Line Encyclopedia of Integer Sequences.
 The Slightly Spooky Recamán Sequence, Numberphile video.
 Recamán's sequence, on Wikipedia.


proc nonrec find([*] int A; word top; int n) bool:
    word i;
    bool found;
    i := 0;
    found := false;
    while i < top and not found do
        found := A[i] = n;
        i := i + 1
    od;
    found
corp
 
proc nonrec gen_next([*] int A; word n) int:
    int add, sub;
    add := A[n-1] + n;
    sub := A[n-1] - n;
    A[n] := 
        if sub > 0 and not find(A, n, sub) 
            then sub
            else add
        fi;
    A[n]
corp
 
proc nonrec main() void:
    [30] int A;
    word i;
 
    A[0] := 0;
    write("First 15 items:  0");
    for i from 1 upto 14 do write(gen_next(A, i):3) od;
    writeln();
 
    while not find(A, i, gen_next(A, i)) do i := i + 1 od;  
    writeln("First repeated item: A(", i:2, ") = ", A[i]:2)
corp 