# 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 > 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 & \textrm{if } n = 0 \\ A(n-1) - n & \textrm{if } A(n-1) - n \textrm{ is positive and not already in the sequence} \\ % Seems more readable than %A(n-1) - n & \textrm{if } A(n-1) > n \wedge \not\exists m < n: A(m) = A(n-1)-n \\ A(n-1) + n & \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.

• What does 'is new' mean? Sep 11 '14 at 16:53
• If a number is new, it means it is not yet in the sequence. Just realized I have typed out the sequence wrong, give me a min to correct it. Sep 11 '14 at 16:56
• Corrected the sequence. Sep 11 '14 at 17:06
• Can you add the first values of the sequence? Sep 11 '14 at 17:15
• Added the first few numbers! (And a link to its OEIS page) Sep 11 '14 at 17:50

# CJam, 34 33 bytes

0ali{_W=_I-__0<4$@#)|@I+@?+}fI1>  Try it online. ### Example run $ cjam <(echo '0ali{_W=_I-__0<4$@#)|@I+@?+}fI1>') <<< 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< " A := (Y < 0) "; _ 4$@#)               "   B := (Y ∊ S)                                       ";
@I+           "   Z := X + I                                         ";
|   @?         "   C := (A || B) ? Z : Y                              ";
+        "   S += [C]                                           ";
1>  " Push str(S[1:]).                                     ";

• What change did you make? Sep 11 '14 at 19:55
• My first approach prepended negative numbers to the sequence, so I didn't have to explicitly check if A(i) - i > 0. However, I didn't prepend enough numbers for small values of n. Now, I just do exactly what the spec says. Sep 11 '14 at 19:58
• 33 vs. 45. So close and yet so far. :) Sep 12 '14 at 21:07
• Wow, comment without e# in Cjam... tasty cherry. Jun 21 '18 at 8:04

# Hexagony, 212 bytes

?\..$@.=.'">'_<>}/..&\_.._!\.\].\"&"&=(<_...>\[.+.<_$|_...{.|.....}'.../<..|&.....'/..".>$/{.<\.\$\>\._?...><?.\[._\_}$&..~.|"$\./..{&_$....$'.|_...$}|_.-..;_....'}".'...2.....$?&....3..=.<_.....?.-+{......}\</$.}  Try it online! Input: a single, positive integer $$\n\$$ on stdin. Output: all terms of Recaman's sequence up to and including $$\A(n)\$$, separated by spaces (note that this means the program will print a total of $$\n + 1\$$ terms). # Expanded # Explanation Apologies if this is confusing, but it's my first time with Hexagony, so rest assured that it confuses me too. Let $$\n = 6\$$. The instruction pointer (IP) starts out in the NW corner, moving along the black path. ? reads $$\n\$$ from stdin and stores it in the current memory edge. Next, we copy $$\n\$$ three times while backing up the memory pointer. We also flip the memory pointer and decrement the edge it points to. "&"&"&=(  The IP eventually wraps around to the upper left corner again, jumping over \ and looping through the rest of the black path. This loop continues until the current edge is 0, at which point the graph looks like so: This forms the skeleton of our memory layout. Each vertical edge now stores a value $$\i\$$ from 0 to 6; later, these same edges will store the terms $$\A(i)\$$ of the sequence as they are computed. Each vertical edge also has 4 contiguous edges that are used for later computations. Let's explain them now: • head is used for several purposes, but never to store anything permanently because it is frequently overwritten by other operations. • tail is generally used as a temporary variable, but it remains 0 for the last $$\i\$$ in the sequence, telling the program when to stop. • prev stores the value of $$\A(i - 1)\$$ • copy straightforwardly stores a copy of $$\i\$$ or, later, $$\A(i)\$$ Once the program is done initializing its memory graph, it branches off the black path and onto the red path near the NE corner. First, ! prints the decimal representation of vertical to stdout. Next, we move the memory pointer to tail and test for zero: '<  If it is zero, @ terminates the program immediately; otherwise, we move to head and set it to 32 (an ASCII space): }=}?32 ; then prints this space to stdout. Finally, we copy vertical to the next prev: "?&"& Now that the memory pointer is on the next term, we copy this term's vertical to its copy before moving to its vertical: '&{= - computes prev - copy, which is really $$\A(i - 1) - i\$$, and stores it in vertical: If vertical is not positive, < deflects the IP onto the green path, where + instead computes prev + copy ($$\A(i - 1) + i\$$) and stores it in vertical: The IP then wraps around to the SW corner, eventually returning to the beginning of the red path and starting the cycle over again. However, if vertical is positive, we have to make sure it doesn't already exist in the sequence before printing it. In this case, the < in the SE corner branches to the SE, wrapping around and staying on the red path. First, we copy vertical to head: "?&  This puts the memory pointer in a position so that successive loops can enter at the next | mirror. Next, we copy head to the previous term's tail and move to its head. "?&'  - computes vertical - tail ($$\A(i - 1) - A(i)\$$) and stores it in head. Hexagony treats zero as a negative number, so we have to do some convoluted branching to test if head is exactly zero. All that's necessary to know is that if head is zero, we've found a duplicate term, and the program will branch onto the yellow path. Otherwise, it will return to the red path at the { instruction. If head is zero, we return to the latest term of the sequence with [, which executes the subroutine along the pink and blue paths, before + computes $$\A(i - 1) + i\$$) like above. We then return to the red path. If head is not zero, we check if the current term is zero: {<  If it is, we call the subroutine and go back to the red path through a convoluted series of mirrors. If it isn't, we move to compare the next term, returning to the aforementioned | mirror. Images created using Timwi's Hexagony Colorer and Esoteric IDE. • For what its worth, your image with colored paths seems to show that the curly bracket at the end doesn't do anything, you should be able to remove it and the preceding space for an easy -2. Apr 28 at 15:14 • @jeje Shoot, you're right. I can't believe I didn't see that! It's been so long that I'm not sure I even have the Hexagony Colorer project for the image, but I might correct it when I get the time. May 1 at 4:16 # Haskell, 74 l=0:0#1 a§v|a<0||aelemr v=v|1<2=0-v a#b=a+(a-b)§b:l!!b#(b+1) r=(takel)  Example usage: λ> r 20 [0,1,3,6,2,7,13,20,12,21,11,22,10,23,9,24,8,25,43,62]  ## Ruby, 71 70 bytes f=->n{a=;(n-1).times{|i|a+=[[b=a[-1]-i-1]-a!=[]&&b>0?b:b+2*i+2]};a}  A very "word-for-word" implementation of the definition. ## Python 2, 787573 69 Bytes Kudos to xnor and flornquake Now almost 10 bytes shorter than the initial answer m=p,=0, exec"p+=1;k=m[-1]-p;m+=k+2*p*(k*(k>0)in m),;"*input() print m  • You can shorten [k,k+2*p][bool] to k+2*p*(bool). – xnor Sep 11 '14 at 19:04 • @xnor Thanks, saved 3 Bytes. Sep 11 '14 at 19:16 • Also, k in m or k<0 can be k*(k>=0)in m since if k<0, the product is 0, which is in m. – xnor Sep 11 '14 at 19:22 • @xnor Brilliant! Thanks again Sep 11 '14 at 19:36 • You can write -1 instead of p-1. Edit: You can also make m a tuple and write m=0, and m+=k+2*p*(k*(k>0)in m),. Sep 12 '14 at 13:14 # Golfscript (41 45) Try it online here: (,1,\{:~1$=~)-:^1<\.^?)!!@|^\{~)2*+}*+}/


## Explanation

This is for the original 45 bytes solution, but it's still pretty much the same:

(,              # push array [0 .. n-1]
\            # push sequence elements as  and reverse stack
{               # foreach element in [0 .. n-1] do:
:m;           # store current element in m and discard
.m=           # get the previous sequence element
m)-:^         # subtract the current index from it and store in ^
0>            # is that number greater than 0?
\.^?)!        # is that number new to our sequence?
@&            # logically and both checks
{^}           # if true, push ^
{^m)2*+}      # otherwise, add the index twice and push
if
+             # add new element to our sequence
}/
# make output pretty


Edit #1: Thanks to Dennis for shaving off 4 bytes.

# dc, 46 bytes

sn[z+z+d0r:a]sF0[pz-d1>Fd;a0<Fddd:azln!<M]dsMx


Try it online!

This program takes input from an otherwise empty stack and outputs to stdout (newline delimited).

I'm really proud of this one - it's beating everything that isn't a dedicated golfing language, and showcases three of my favorite dc golfing tricks:

• Stack size used as an index variable
• Refactoring "if A then B else C" into "unconditionally C, and if A then D" where C and D combine to make B
• the little-used random access array feature to solve a uniqueness constraint

# Explanation

sn             Stores the input in register n
[z+z+0r:a]sF   Defines the macro F, which:
z+z+         adds twice the stack size/index variable
0r:a         resets the "uniqueness" flag to 0 in the array a
In context, F is the "D" in my description above,
changing A(z-1)-z to A(z-1)+z
0              The main loop starts with the previous sequence member on top of
the stack and total stack depth equal to the next index.
Pushing a zero accomplishes both of these things.
[              Start of the main loop M
p               Print the previous sequence member, with newline (no pop)
z-             Calculate A(z-1)-z
d1>F           If that's nonpositive, (F)ix it to be A(z-1)+z
d;a            a is my array of flags to see if we've hit this value before
0<F            If we have, (F)ix it! (nonzero = flag, since ;a is zero by
default, and also zero if we just (F)ixed and therefore
don't care about uniqueness right now)
ddd            Make one copy to keep and two to eat
:a             Flag this entry as "used" in the uniqueness array a
zln!<M         If our "index variable" is n or less, repeat!
]dsMx          End of main loop - store it and execute

• that's wild, i had no idea dc even existed Dec 31 '18 at 7:08

## JavaScript - 81 80 79 70

Kudos to edc65 for helping me save 9 bytes

f=n=>{for(a=[x=i=0];++i<n;)a[i]=x+=x>i&a.indexOf(x-i)<0?-i:i;return a}

• -9 :g=n=>{for(a=[x=i=0];++i<n;)a[i]=x+=x>i&a.indexOf(x-i)<0?-i:i;return a} Sep 11 '14 at 18:48
• @edc65 Grazie mille :) Sep 11 '14 at 19:22

## JavaScript, ES6, 74 69 characters

Run the below code in latest Firefox's Web Console.

G=n=>(i=>{for(r=[t=0];++i<n;)r[i]=t+=i>t|~r.indexOf(t-i)?i:-i})(0)||r


Will try to golf it more later.

Example usage:

G(11) -> 0,1,3,6,2,7,13,20,12,21,11


# MATLAB, 83 78 Bytes

Save the below as f.m (73 Bytes)

A=0;for i=1:n-1 b=A(i)-i;A(i+1)=b+2*i;if b>0&&~any(A==b) A(i+1)=b;end;end


Run from command window (5 bytes)

n=9;f


If the above is not legal, then it requires 90 bytes.

function A=f(n)
A=0;for i=1:n-1 b=A(i)-i;A(i+1)=b+2*i;if b>0&&~any(A==b) A(i+1)=b;end;end


# R: 96 characters

Golfed:

A=function(s,n,m,i){if(m==n){return(s)}else{t=i-m;if(t%in%s||t<0){t=i+m};s=c(s,t);A(s,n,m+1,t)}}


Ungolfed:

A = function(s,n,m,i) {
if(m==n){return(s)}
else{
t=i-m
if(t%in%s||t<0){t=i+m}
s=c(s,t)
A(s,n,m+1,t)
}
}


Sample Run:

> An(0,34,1)
   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  79


# JavaScript, 63 bytes

n=>(g=y=>n-x?g(a[++x]=a.includes(z=y-x)|z<0?+y+x:z):a)(a=[x=0])


Try it online

# Perl 6, 62 57 bytes

{(0,{$-@+@*2*($!>@||$-@∈@)given @[*-1]}...*)[^$]}

{(0,{($!=@_[*-1])+@_-@_*2*($!>@_&&$!-@_∉@_)}...*)[^$_]}


-5 bytes thanks to Jo King

Try it online!

• that's amazing... that literally looks like my cat walked across my keyboard. Dec 31 '18 at 7:10

# 05AB1E, 19 bytes

¾ˆG¯¤N-DŠD0›*åN·*+ˆ


Try it online!

Explanation

¾ˆ                    # Initialize the global list with 0
G                   # for N in [1, input-1] do:
¯                  # push the global list
¤N-               # subtract N from the last item in the list
D              # duplicate
Š             # move the copy down 2 spots on the stack
D            # duplicate again
0›          # check if it is positive
*         # multiply, turning negative results to zero
å        # is the result already present in the list?
N·*     # multiply by N*2
+    # add to the result
ˆ   # add this to the list


# K (oK), 53 bytes

Solution:

{$[y>c:#x;o[x,(r;*|x+c)(r in x)|0>r:*|x-c;y];x]}[,0;]  Try it online! Explanation: Recursive solution. {$[y>c:#x;o[x,(r;*|x+c)(r in x)|0>r:*|x-c;y];x]}[,0;] / the solution
{                                              }[,0;] / lambda with first arg set as list containing 0
$[ ; ; ] / if[condition;true;false] #x / length of x c: / save as c y> / y greater than? (ie have we produced enough results?) x / return x if we are done o[ ;y] / recurse with new x and existing y x-c / subtract c from x *| / reverse first, aka last r: / save result as r 0> / 0 greater than? | / or ( ) / do together r in x / r in x? ( ; ) / use result to index into this 2-item list x+c / add c to x *| / reverse first, aka last r / result x, / append to x  ## Java, 144 int[]f(int n){int[]a=new int[n];a=0;int i,j,k,m;for(i=0;i<n-1;){k=a[i++]-i;m=0;for(j=0;j<i;)if(k==a[j++])m=1;a[i]=m<1&k>0?k:k+2*i;}return a;}  ## Lua - 141 135 139 135 function s(n)a,b={1},{=0}for i=1,n do k=b[i-1]-i c=k+i+i if(k>0)and(a[k]==nil)then b[i],a[k]=k,1 else b[i],a[c]=c,1 end end return b end  readable version: function s(n) a,b={1},{=0} for i=1,n do k=b[i-1]-i c=k+i+i if (k>0) and (a[k]==nil) then b[i],a[k]=k,1 else b[i],a[c]=c,1 end end return b end  I use 2 tables, the first one is called a and it is built so that a[i]=1 iff i has already appeared in the sequence, nil otherwise, while the second table actually holds the sequence • Your sequence should start with 0, though Sep 11 '14 at 18:06 • You're right, I didn't look at the question very carefully and assumed it had the same definition at mathworld (starting with 1), I think that won't cost any more character, I'll test and correct it later, I'm writing from my phone now! – user25169 Sep 11 '14 at 19:26 ## Python, 73 def f(x,t=0): if x:t=f(x-1);t+=2*x*(t*(t>0)in map(f,range(x))) return t  Edit 1: Thanks to @xnor's tips on the other Python answer! (I just realised that both look very similar.) Edit 2: Thanks again, @xnor. • This gives an infinite loop. You need some sort of control flow so that f(x) doesn't always immediately call f(x-1). – xnor Sep 11 '14 at 19:25 • @xnor fixed the code. Sep 11 '14 at 19:36 • This seems to return the nth term, not the first n terms. Sep 11 '14 at 19:55 • Some minor saves: t=0 can go as an optional parameter to f, and t=t+ can be t+=. – xnor Sep 11 '14 at 20:21 ## Groovy : 122118 111 chars Golfed: m=args as int a= (1..m-1).each{n->b=a[n-1];x=b-n;(x>0&!(x in a))?a[n]=x:(a[n]=b+n)} a.each{print "$it "}


Ungolfed:

m = args as int
a = 
(1..m-1).each { n->
b = a[n-1]
x = b-n
( x>0 & !(x in a) ) ? a[n] = x : (a[n] = b+n)
}
a.each{print "$it "}  Sample Run: bash$ groovy Rec.groovy 14
0 1 3 6 2 7 13 20 12 21 11 22 10 23


## Clojure : 174 chars

Golfed:

(defn f[m a](let[n(count a)b(last a)x(- b n)y(if(and(> x 0)(not(.contains a x)))x(+ b n))](if(= m n)a(f m(conj a y)))))(println(f(read-string(first *command-line-args*))))


Ungolfed:

(defn f[m a]
(let [n (count a)
b (last a)
x (- b n)
y (if (and (> x 0) (not (.contains a x))) x (+ b n)) ]
(if (= m n) a (f m (conj a y))) ) )

(println (f (read-string (first *command-line-args*)) ) )


Sample run:

bash$java -jar clojure-1.6.0.jar rec.clj 14 [0 1 3 6 2 7 13 20 12 21 11 22 10 23]  • I suggest you not to read from STDIN but instead just take an integer argument to the function :) Also you don't get any benefits from defining y on the let form, you can use the expression directly where the value is needed. Jul 26 '19 at 11:07 # Mathcad, 54 "bytes" From user perspective, Mathcad is effectively a 2D whiteboard, with expressions evaluated from left-to-right,top-to-bottom. Mathcad does not support a conventional "text" input, but instead makes use of a combination of text and special keys / toolbar / menu items to insert an expression, text, plot or component. For example, type ":" to enter the definition operator (shown on screen as ":=") or "ctl-shft-#" to enter the for loop operator (inclusive of placeholders for the iteration variable, iteration values and one body expression). What you see in the image above is exactly what appears on the user interface and as "typed" in. For golfing purposes, the "byte" count is the equivalent number of keyboard operations required to enter an expression. • That's all well and good, but what are the actual keystrokes? – Jo King Jun 18 '18 at 13:14 # C (gcc), 116 111 109 bytes *f(n){int*a=calloc(4,n),i=0,j,k,m;for(;~i+n;a[i]=k+(m|k<1)*2*i)for(k=a[i++]-i,m=0,j=i;j--;)m=k-a[j]?m:1;n=a;}  Try it online! # Stax, 19 bytes É╖C8½ΔL▄░▬L+≡ΩSa⌂¼╧  Run and debug it Unpacked, ungolfed, and commented, it looks like this. It keeps the sequence so far on the stack, and remembers A(n - 1) in the X register. The iteration index is used for n. The first time through, it's 0, but in that iteration it generates the 0 without any special cases, so there's no need to adjust for the off-by-1 index. 0X push 0 to main stack and store it in X register, which will store A(n - 1) z push an empty array that will be used to store the sequence ,D pop input from input stack, execute the rest of the program that many times xi-Y push (x-register - iteration-index) and store it in the Y register this is (A(n - 1) - n) 0> test if (A(n - 1) - n) is greater than 0 (a) ny# count number of times (A(n - 1) - n) occurs in the sequence so far (b) > test if (a) > (b) y (A(n - 1) - n) xi+ A(n - 1) + n ? if/else; choose between the two values based on the condition X store the result in the X register Q print without popping + append to sequence array  Run and debug this one ## Pyth, 31 bytes VQ=+Y?Y?|>NeYhxY-eYN+eYN-eYNZ)Y  • Welcome to the site! Jul 19 '19 at 17:02 • Welcome. Code-only answers are discouraged because they tend to be automatically flagged as low-quality. Add an explanation, and consider adding a link to an online interpreter, like this: tio.run/##K6gsyfj/PyzQVjvSPtK@xs4vNTKjIlI3NdJPG4hBdJRm5P//hoYA Jul 19 '19 at 18:32 # Pyth, 24 bytes tu+G-eG_W|g0J-eGH}JGHQ]0  Try it online! tu+G-eG_W|g0J-eGH}JGHQ]0 Implicit: Q=eval(input()) u Q Reduce [0-Q)... ]0 ... with initial value G=, next value as H: eG Last value of G (sequence so far) - H Take H from the above J Store in J g0J 0 >= J }JG Is J in G? | Logical OR of two previous results _W H If the above is true, negate H, otherwise leave as positive -eG Subtract the above from last value in G +G Append the above to G The result of the reduction is the sequence with an extra leading 0 t Remove a leading 0, implicit print  # x86 machine code, 29 bytes 00000034: 89 fe 31 c0 99 eb 11 29 d0 78 0a 60 89 f7 89 d1 ..1....).x..... 00000044: f2 af 61 75 03 8d 04 50 ab 42 e2 eb c3 ..au...P.B...  Commented assembly:  .intel_syntax noprefix .globl recaman // input: ECX: n, EDI: u32[n] // output: stored to EDI recaman: // Save the array pointer to ESI mov esi, edi // EAX (A(n)) = 0 xor eax, eax // EDX (n) = 0 cdq // Store first word jmp .Lstore .Lloop: // A(n - 1) - n sub eax, edx // if negative, do A(n - 1) + n js .Lneg_or_dup .Lnot_neg_or_dup: // We need to save both EDI and ECX, so we do a lazy PUSHA/POPA. pusha // EDI = start of array mov edi, esi // ECX = current output length mov ecx, edx // Search for A(n - 1) - n repnz scasd // restore registers popa // If the zero flag is set, we found a match. // If not, go directly to store jnz .Lstore .Lneg_or_dup: // Convert A(n - 1) - n to A(n - 1) + n by adding n * 2 // EAX = EAX + EDX * 2 lea eax, [eax + 2 * edx] .Lstore: // Store a u32 to EDI and autoincrement stosd // Increment length inc edx // Decrement counter and loop if non zero loop .Lloop // Return ret  Try it online! The input is a pointer to an int32_t array of n elements in edi, with n being in ecx. The output will be stored into edi. # Python 2, 65 bytes n=a=0 v=[] exec'a+=[n,-n][a+n in v];print a;n-=1;v+=a,n;'*input()  Try it online! Avoids negative numbers by adding them to the list of already visited numbers. ### Powershell (103) $n=Read-Host;$a=@(0);$n-=1;1..$n|%{$x=$a[-1]-$_;if($x-gt0-and!($a-like$x)){$a+=$x}else{$a+=$x+2*$_}};$a  Another 'word-for-word' implementation down here as well. Surprisingly readable for PowerShell, too. Sequence is stored in the array$a, and printed out one term per line.

For $n=20 if we run the statement $a-join"," we get

0,1,3,6,2,7,13,20,12,21,11,22,10,23,9,24,8,25,43,62


# C#: 140 characters

int i,w,t,y;int[]F(int n){var r=new int[n--];for(;i<n;y=0){w=r[i++]-i;for(t=0;y<i&&t<1;)t=w==r[y++]?1:0;r[i]=w>0&&t<1?w:r[i-1]+i;}return r;}


# C++: 180 characters (158 without cin and cout statements)

int a={0},i,k,l;a=0;a=1;cin>>k;for(i=1;i<=k;i++){l=a[i-1];if(l-i>0&&a[l-i]!=1){ a[i]=l-i;a[l-i]=1;}else{ a[i]=l+i;a[l+i]=1;}cout<<a[i]<<endl;
`
• Welcome to Programming Puzzles & Code Golf Stack Exchange! Please edit the character/byte count of your solution into your header, as shown in the other answers here. Also, please golf your code (ex. remove whitespace to reduce the character count) as much as possible. Thanks!
– Doorknob
Aug 17 '15 at 16:00
• Sure thing, I'll do that. Aug 18 '15 at 17:41