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.


recaman: procedure options(main);
    declare A(0:30) fixed;
 
    /* is X in the first N terms of the Recaman sequence? */
    find: procedure(x, n) returns(bit);
        declare (x, n, i) fixed;
        do i=0 to n-1;
            if A(i)=x then return('1'b);
        end;
        return('0'b);
    end find;
 
    /* generate the N'th term of the Recaman sequence */
    generate: procedure(n) returns(fixed);
        declare n fixed;
        if n=0 then
            A(0) = 0;
        else do;
            declare (sub, add) fixed;
            sub = A(n-1) - n;
            add = A(n-1) + n;
            /* A(n-1) - n not positive? */
            if sub <= 0 then 
                A(n) = add;
            /* A(n-1) - n already generated? */
            else if find(sub, n) then
                A(n) = add;
            else 
                A(n) = sub;
        end;
        return(A(n));
    end generate;
 
    declare i fixed;
    put skip list('First 15 members:');
    do i=0 to 14;
        put edit(generate(i)) (F(3));
    end;
 
    put skip list('First repeated term: ');
    do i=15 repeat(i+1) while(^find(generate(i), i)); end;
    put edit('A(',i,') = ',A(i)) (A,F(2),A,F(2));
end recaman;