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's sequence - smallbasic - 05/08/2015
    nn=15
    TextWindow.WriteLine("Recaman's sequence for the first " + nn + " numbers:")
    recaman()
    TextWindow.WriteLine(Text.GetSubTextToEnd(recaman,2))
    nn="firstdup"
    recaman()
    TextWindow.WriteLine("The first duplicated term is a["+n+"]="+a[n])
 
Sub recaman
    a=""
    b=""
    dup=""
    recaman=""
    firstdup=""
    If nn="firstdup" Then
        nn=1000
        firstdup="True"
    EndIf
    For n=0 To nn-1
        ap=a[n-1]+n 
        If a[n-1]<=n Then 
            a[n]=ap  'a[n]=a[n-1]+n
            b[ap]=1
        Else
            am=a[n-1]-n
            If b[am]=1 Then
                a[n]=ap  'a[n]=a[n-1]+n
                b[ap]=1
            Else
                a[n]=am  'a[n]=a[n-1]-n
                b[am]=1
            EndIf
        EndIf
        If firstdup Then
            If dup[a[n]]=1 Then
                Goto exitsub
            EndIf
            dup[a[n]]=1
        EndIf
        recaman=recaman+","+a[n]
    EndFor
    exitsub:
EndSub 