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.


 
  [ stack 0 ]              is seennumbers (     --> s   )
 
  [ bit seennumbers take 
    | seennumbers put ]    is seen        (   n -->     )
 
  [ dup 0 < iff
      [ drop true ] done
    bit seennumbers share
    & 0 != ]                is seen?       (   n --> b   )
 
  [ 1+ bit 1 - 
    seennumbers share
    over & = ]              is allseen?    (   n --> b   )
 
  [ stack [ ] ]             is repeats     (     --> s   )
 
  [ 1 seennumbers replace
    [] repeats replace
    ' [ 0 ] 1 ]             is startseq    (     --> [ n )
 
  [ over -1 peek 
    over - dup seen? if
      [ over 2 * +
        dup seen? if
          [ repeats take
            over join 
            repeats put ] ]
    dup seen
    swap dip join 
    1+ ]                    is nextterm    ( [ n --> [ n )
 
  say "first 15 terms: "
  startseq
  14 times nextterm
  drop echo cr
 
  say "first duplicated term: "
  startseq
  [ repeats share [] = while
    nextterm
    again ]
  drop -1 peek echo cr
 
  say "terms needed to generate 0 to 1000: "
  startseq
  [ nextterm
    1000 allseen? until ] 
  nip 1 - echo cr
 