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.


get "libhdr"
 
// Generate the N'th term of the Recaman sequence
// given terms 0 to N-1.
let generate(a, n) be 
    a!n := n=0 -> 0, valof
    $(  let subterm = a!(n-1) - n
        let addterm = a!(n-1) + n
        if subterm <= 0 resultis addterm
        for i=0 to n-1 
            if a!i = subterm resultis addterm
        resultis subterm
    $)      
 
let start() be
$(  let a = vec 50 and n = 15 and rep = ?
 
    writef("First %N members:*N", n)
    for i = 0 to n-1
    $(  generate(a, i)
        writef("%N ", a!i)
    $)
 
    writef("*NFirst repeated term:*N")
    rep := valof 
    $(  generate(a, n)
        for i = 0 to n-1
            if a!i = a!n resultis n
        n := n + 1
    $) repeat
 
    writef("a!%N = %N*N", rep, a!rep)
$)