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.


var a = [0]
var used = { 0: true }
var used1000 = { 0: true }
var foundDup = false
var n = 1
while (n <= 15 || !foundDup || used1000.count < 1001) {
    var next = a[n-1] - n
    if (next < 1 || used[next]) next = next + 2*n
    var alreadyUsed = used[next]
    a.add(next)
    if (!alreadyUsed) {
        used[next] = true
        if (next >= 0 && next <= 1000) used1000[next] = true
    }
    if (n == 14) System.print("The first 15 terms of the Recaman's sequence are:\n%(a)")
    if (!foundDup && alreadyUsed) {
        System.print("The first duplicated term is a[%(n)] = %(next)")
        foundDup = true
    }
    if (used1000.count == 1001) {
        System.print("Terms up to a[%(n)] are needed to generate 0 to 1000")
    }
    n = n + 1
}