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.


with javascript_semantics
bool found_duplicate = false
sequence a = {0}, used = {} -- (grows to 1,942,300 entries)
integer all_used = 0, n = 1, next, prev = 0
while n<=15 or not found_duplicate or all_used<1000 do
    next = prev - n
    if next<1 or (next<=length(used) and used[next]) then
        next = prev + n
    end if
    a &= next
    integer padlen = next-length(used)
    bool already_used = padlen<=0 and used[next]
    if not already_used then
        if padlen>0 then used &= repeat(false,padlen) end if
        used[next] = true
        while all_used<length(used) and used[all_used+1] do
            all_used += 1
        end while
    end if
    if length(a)=15 then
        printf(1,"The first 15 terms of the Recaman sequence are: %v\n",{a})
    end if
    if already_used and not found_duplicate then
        printf(1,"The first duplicated term is a[%d] = %d\n", {n, next})
        found_duplicate = true;
    end if
    if all_used>=1000 then
        printf(1,"Terms up to a[%d] are needed to generate 0 to 1000\n", {n});
    end if
    prev = next
    n += 1
end while
