Recamán's Sequence is defined as follows:
\$a_n=\begin{cases}0\quad\quad\quad\quad\text{if n = 0}\\a_{n-1}-n\quad\text{if }a_{n-1}-n>0\text{ and is not already in the sequence,}\\a_{n-1}+n\quad\text{otherwise}\end{cases}\$
or in pseudo-code:
a(0) = 0, if (a(n - 1) - n) > 0 and it is not already included in the sequence, a(n) = a(n - 1) - n else a(n) = a(n - 1) + n. The first numbers are (OEIS A005132):
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 If you study this sequence, you'll notice that there are duplicates, for instance a(20) = a(24) = 42 (0-indexed). We'll call a number a duplicate if there is at least one identical number in front of it in the sequence.
Challenge:
Take an integer input k, and output either the first k duplicate numbers in the order they are found as duplicates in Recamán's Sequence, or only the k'th number.
This first duplicated numbers are:
42, 43, 78, 79, 153, 154, 155, 156, 157, 152, 265, 261, 262, 135, 136, 269, 453, 454, 257, 258, 259, 260, 261, 262 A few things to note:
- a(n) does not count as a duplicate if there are no identical numbers in a(0) ... a(n-1), even if a(n+m)==a(n).
- 42 will be before 43, since its duplicate occurs before 43's duplicate
- The sequence is not sorted
- There are duplicate elements in this sequence too. For instance the 12th and the 23rd numbers are both 262 (0-indexed).
Test cases (0-indexed)
k Output 0 42 9 152 12 262 23 262 944 5197 945 10023 10000 62114 This is code-golf, so the shortest code in each language wins!
Explanations are encouraged!
43output before42? It appears first in Recamán's sequence. Do you mean output first the one that is first found to be a duplicate? \$\endgroup\$