Generate Recamán's sequence Recamán's sequence (A005132) is a mathematical sequence, defined as such:

A(0) = 0
A(n) = A(n-1) - n if A(n-1) - n &gt; 0 and is new, else
A(n) = A(n-1) + n


A pretty LaTex version of the above (might be more readable):

$$A(n) = \begin{cases}0 &amp; \textrm{if } n = 0 \\
A(n-1) - n &amp; \textrm{if } A(n-1) - n \textrm{ is positive and not already in the sequence} \\
% Seems more readable than
%A(n-1) - n &amp; \textrm{if } A(n-1) &gt; n \wedge \not\exists m &lt; n: A(m) = A(n-1)-n \\
A(n-1) + n &amp; \textrm{otherwise}
\end{cases}$$

The first few terms are 0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11

To clarify, is new means whether the number is already in the sequence.

Given an integer n, via function argument or STDIN, return the first n terms of the Recamán sequence.



This is a code-golf challenge, so shortest code wins.
CJam, 34 33 bytes

0ali{_W=_I-__0&lt;4$@#)|@I+@?+}fI1&gt;`


Try it online.

Example run

$ cjam &lt;(echo '0ali{_W=_I-__0&lt;4$@#)|@I+@?+}fI1&gt;`') &lt;&lt;&lt; 33
[0 1 3 6 2 7 13 20 12 21 11 22 10 23 9 24 8 25 43 62 42 63 41 18 42 17 43 16 44 15 45 14 46]


How it works

0ali                               " Push S := [ 0 ] and read an integer N from STDIN.    ";
    {                      }fI     " For each I in [ 0 ... (N - 1) ]:                     ";
     _W=                           "   X := S[-1].                                        ";
        _I-                        "   Y := X - I                                         ";
            _0&lt;                    "   A := (Y &lt; 0)                                       ";
           _   4$@#)               "   B := (Y ∊ S)                                       ";
                     @I+           "   Z := X + I                                         ";
                    |   @?         "   C := (A || B) ? Z : Y                              ";
                          +        "   S += [C]                                           ";
                              1&gt;`  " Push str(S[1:]).                                     ";