Nth term of Van Eck Sequence

Output the Nth term of the Van Eck Sequence.

Van Eck Sequence is defined as:

• Starts with 0.
• If the last term is the first occurrence of that term the next term is 0.
• If the last term has occurred previously the next term is how many steps back was the most recent occurrence.

https://oeis.org/A181391

Sequence: 0,0,1,0,2,0,2,2,1,6,0,5,0,2,...

Tests:

Input | Output

• 1 | 0
• 8 | 2
• 19 | 5
• 27 | 9
• 52 | 42
• 64 | 0

EDIT

1 indexed is preferred, 0 indexed is acceptable; that might change some of the already submitted solutions.

Same (except for the seeing it already posted part), it seems code golfers and numberphile watchers have a decent overlap.

• Watched the numpherphile video at work and was going to post this when I got home. Curse you for getting there first. :P Jun 10 '19 at 21:27
• Does it have to be 1-indexed, or may we use 0-indexing? Jun 10 '19 at 22:02
• May we return or output the infinite sequence instead?
– Jo King
Jun 11 '19 at 2:10
• ... or the first n terms? Jun 11 '19 at 15:11
• @Draco18s The same thing happened to me. :P Jul 5 '19 at 16:31

JavaScript (ES6),  46 41  37 bytes

n=>(g=p=>--n?g(g[p]-n|0,g[p]=n):p)(0)

Try it online!

How?

We don't need to store the full sequence. We only need to keep track of the last position of each integer that appears in the sequence. We use the underlying object of the recursive function $$\g\$$ for that purpose.

For a given term $$\p\$$, we don't need either to set $$\g[p]\$$ to its actual absolute position in the sequence because we're only interested in the distance with the current position. That's why we can just store the current value of the input $$\n\$$, which is used as a decrementing counter in the code.

Therefore, the distance is given by $$\g[p]-n\$$. Conveniently, this evaluates to NaN if this is the first occurrence of $$\p\$$, which can be easily turned into the expected $$\0\$$.

Commented

n => (             // n = input
g = p =>         // g = recursive function taking p = previous term of the sequence
//     g is also used as an object to store the last position of
//     each integer found in the sequence
--n ?          // decrement n; if it's not equal to 0:
g(           //   do a recursive call:
g[p] - n   //     subtract n from the last position of p
//     if g[p] is undefined, the above expression evaluates to NaN
| 0,       //     in which case we coerce it to 0 instead
g[p] = n   //     update g[p] to n
)            //   end of recursive call
:              // else:
p            //   we've reached the requested term: stop recursion and return it
)(0)               // initial call to g with p = 0

Python 3, 6963 62 bytes

f=lambda n,l=0,*s:f(n-1,l in s and~s.index(l),l,*s)if n else-l

Try it online!

Note: as Erik the Outgolfer mentioned, this code works fine in Python 2 as well.

0-indexed (although, just to be utterly perverse, you can make it -1-indexed by changing if n to if~n :P)

Makes use of Python's gorgeous unpacking "star operator", to recursively build up the series, until n reaches zero.

The function builds up the series in the reverse order, to avoid having to reverse it for the search. Additionally, it actually stores the negations of all the elements, because converting them back at the end was free (else the - would have had to be a space) and it saves us a byte along the way, by using ~s.index(l) instead of -~s.index(l).

Could be 51 bytes if Python tuples had the same find functions strings do (returning -1 if not found, instead of raising an error), but no such luck...

• Actually, the "star operator" you're using isn't Python 3's unpacking operator, but rather the vararg operator which also exists in Python 2. Jun 10 '19 at 22:56
• The first one is, but isn't the second one unpacking s for the recursive call?
– ArBo
Jun 10 '19 at 23:08
• I've tested it in Python 2 and it works. Jun 11 '19 at 11:06
• @EriktheOutgolfer hmm, but isn't the second use unpacking though? The function doesn't have to support varargs to use such syntax.
– ArBo
Jun 11 '19 at 12:43
• @ArBo: It's no different than def func(f, *args): f(*args); unpacking inside function calls is valid py2. What's py3-only is unpacking inside list/dict comprehensions (i.e. [1, 2, *s]) or unpacking variables: a, *b = [1,2,3,4]. Jun 13 '19 at 17:27

R, 62 bytes

function(n){while(sum(F|1)<n)F=c(match(F,F[-1],0),F)
+F}

Try it online!

Builds the list in reverse; match returns the first index of F (the previous value) in F[-1] (the remainder of the list), returning 0 if no match is found.

F is initialized to FALSE and is coerced to 0 on the first pass of the while loop.

• I'm kind of in awe of how good match is for this problem when you construct it this way. Really clean. Jun 12 '19 at 9:50
• Does the plus on the second line do anything here? I assumed it fixed an edge case, but I can't find one for it. Jun 12 '19 at 9:56
• @CriminallyVulgar it should coerce F to 0 when n==1 else it would return FALSE. Jun 12 '19 at 11:20
• Ahh, I see. Makes sense, I was trying lots of ranges but not the single value. Jun 12 '19 at 12:20

Perl 6, 47 42 bytes

-5 bytes thanks to nwellnhof

{({+grep(@_[*-1],:k,[R,] @_)}...*)[$_]} Try it online! Anonymous codeblock that outputs the 0-indexed element in the sequence. Explanation: { } # Anonymous codeblock ( )[$_]  # Return the nth element
...*       # Of the infinite sequence
{                            }  # Where each element is
grep(        :k        )   # The key of the second occurrence
@_[*-1],                 # Of the most recent element
,[R,] @_       # In the reversed sequence so far
+     # And numify the Nil to 0 if the element is not found

Try it online!

0-indexed.

Charcoal, 23 bytes

≔⁰θＦ⊖Ｎ«≔⊕⌕⮌υθη⊞υθ≔ηθ»Ｉθ

Try it online! Link is to verbose version of code. Explanation:

≔⁰θ

Set the first term to 0.

Ｆ⊖Ｎ«

Loop n-1 times. (If 0-indexing is acceptable, the can be removed for a 1-byte saving.)

≔⊕⌕⮌υθη

The next term is the incremented index of the current term in the reversed list of previous terms.

⊞υθ

Add the current term to the list of previous terms.

≔ηθ

Set the current term to the next term.

»Ｉθ

Print the current term at the end of the loop.

f n=last$0:[n-j-1|j<-[0..n-2],f j==f(n-1)] Try it online! Other Haskell answers: 66 bytes by flawr and 61 bytes by nimi. Jelly, 8 bytes ẎiḢ$;µ¡Ḣ

A monadic Link accepting a positive integer, $$\n\$$, which yields the $$\n^{th}\$$ term of the Van Eck Sequence.

Try it online!

How?

ẎiḢ$;µ¡Ḣ - Link: n µ¡ - repeat this monadic link n times - i.e. f(f(...f(n)...)): - (call the current argument L) Ẏ - tighten (ensures we have a copy of L, so that Ḣ doesn't alter it)$     -   last two links as a monad:
Ḣ      -     head (pop off & yield leftmost of the copy)
i       -     first index (of that in the rest) or 0 if not found
;    -   concatenate with L

Note that without the final we've actually collected [a(n), a(n-1), ..., a(2), a(1), n]

C (gcc), 63 bytes

f(n){n=g(n,--n);}g(n,i){n=n>0?f(--n)-f(i)?g(n,i)+!!g(n,i):1:0;}

Try it online!

0-indexed.

Perl 5 (-p), 42 bytes

map{($\,$\{$\})=0|$\{$\};$_++for%\}1..\$_}{

Try it online!

Quite straightforward implementation (using 0 based indexing).

f n|all((/=f(n-1)).f)[0..n-2]=0|m<-n-1=[k|k<-[1..],f(m-k)==f m]!!0

Try it online!

(([]#0)1!!)
(l#n)i=n:(((n,i):l)#maybe 0(i-)(lookup n l))(i+1)

0-based indexing.

Try it online!

@ÒZÔÅbX}hTo

Try it

C# (Visual C# Interactive Compiler), 77 bytes

n=>{int i,v=0;for(var m=new int[n];--n>0;m[v]=n,v=i<1?0:i-n)i=m[v];return v;}

Try it online!

Pretty much a port of the Java answer at this point.

Python 3, 128114111102 99 bytes

102 -> 99 bytes, thanks to Jonathan Frech

f=lambda n,i=1,l=:f(n,i+1,l+[l[i-2::-1].index(l[-1])+1if l[-1]in l[:-1]else 0])if n>i else l[-1]

Try it online!

• You can negate your condition and use - instead of != to save a byte. Jun 13 '19 at 15:03
• Also, since your golf appears to be side-effect-less, you can use lists instead of tuples. Jun 13 '19 at 15:04
• @JonathanFrech But if I have a list as default argument it will not work correctly for consecutive calls? Jun 13 '19 at 15:05
• Why should it not? Jun 13 '19 at 15:07
• Most likely because your previous script modified the list, i.e. was not side-effect-less: example. Jun 13 '19 at 15:15

Husk, 8 7 bytes

!¡oΓ€↔ø

Try it online! The behavior of is surprisingly helpful here.

Python 3, 112 bytes

a=
for _ in a*int(input()):k=a[-1];a+=k in a[:-1]and[a[::-1].index(k)+~a[-2::-1].index(k)]or
print(-a[-2])

Try it online!

-3 bytes thanks to mypetlion

• Second line can become for _ in a*int(input()):k=a[-1];a+=k in a[:-1]and[a[::-1].index(k)+~a[-2::-1].index(k)]or to save 3 bytes. Jun 11 '19 at 16:38
• @mypetlion thanks Jun 11 '19 at 16:52

Red, 106 95 bytes

func[n][b: copyloop n[insert b either not find t: next b
b/1[-1 + index? find t b/1]]b/2]

Try it online!

CJam (15 bytes)

0a{_(#)\+}qi*0=

Online demo. This is a full program and 0-indexed.

Dissection

0a      e# Push the array 
{       e# Loop...
_(#   e#   Copy the array, pop the first element, and find its index in the array
)\+   e#   Increment and prepend
}qi*    e# ... n times, where n is read from stdin
0=      e# Take the first element of the array

Pyth, 18 bytes

VQ=Y+?YhxtYhY0Y;hY

Try it online!

Builds up the sequence in reverse and prints the first element (last term of the sequence).

VQ                 # for N in range(Q) (Q=input)
=Y+         Y    # Y.prepend(
xtY        #   Y[1:].index(    )
hY      #               Y
h           #                     +1
?Y      0     #                        if Y else 0)
;hY # end for loop and print Y

Arn-f, 13 bytes

f→S›J⁻åƒƒN5═%

Try it! 0-indexed

Explained

Unpacked: &.{++.{:i:{)|}[

&.            Mutate S N times
{             With block, key of _
++        Increment
_   Implicit
:i      Index of
_   Implicit