0, 0, 1, 0, 2, 0, 2, 2, 1, 6, 0, 5, 0, 2, 6, 5, 4, 0, 5, 3, 0, 3, …
That is the Van Eck’s Sequence.
Let’s undergo it step-by-step.
Time period 1: The primary time period is 0.
Time period 2: Since we haven’t seen 0 earlier than, the second time period is 0.
Time period 3: Since we had seen a 0 earlier than, one step again, the third time period is 1
Time period 4: Since we haven’t seen a 1 earlier than, the fourth time period is 0
Time period 5: Since we had seen a 0 earlier than, two steps again, the fifth time period is 2.
And so forth…
Your job is to seek out the n_th quantity in Van Eck’s Sequence. (1-based)
The Answer in Python
Choice 1
from collections import Counter
c=Counter()
SEQ = [0]
for i in vary(1000):
n = SEQ[-1]
if not c[n]: c[n]=i
SEQ.append(i-c[n])
c[n]=i
seq=SEQ.__getitem__
Choice 2
def dist(arr):
for i in vary (1, len(arr)):
if arr[-1-i] == arr[-1]:
return i
return 0
def seq(n):
s = [0, 0]
for _ in vary (n):
s.append(dist(s))
return s[n-1]
def seq(n):
van, eck = [0], 0
whereas n := n - 1:
van.insert(0, eck := van.index(eck, 1) if eck in van[1:] else 0)
return eck
Take a look at instances to validate the answer
from resolution import seq
import take a look at
from random import randint
@take a look at.describe("Pattern exams:")
def exams():
@take a look at.it("Small numbers")
def _():
s = [0, 0, 1, 0, 2, 0, 2, 2, 1, 6, 0, 5, 0, 2, 6]
for i in vary (len(s)):
take a look at.assert_equals(seq(i+1), s[i])
@take a look at.it('Bigger numbers')
def __():
s = [3, 1, 42, 0, 5, 15, 20, 0, 4, 32, 0, 3, 11,
18, 0, 4, 7, 0, 3, 7, 3, 2, 31, 0, 6, 31, 3,
6, 3, 2, 8, 33, 0, 9, 56, 0, 3, 8, 7, 19, 0,
5, 37, 0, 3, 8, 8, 1, 46, 0, 6, 23, 0]
for i in vary (len(s)):
take a look at.assert_equals(seq(i+50), s[i])
@take a look at.describe('Random exams:')
def r():
def dist(arr):
for i in vary (1, len(arr)):
if arr[-1-i] == arr[-1]:
return i
return 0
def ref_sol(n):
s = [0, 0]
for _ in vary (n):
s.append(dist(s))
return s[n-1]
@take a look at.it('200 random exams:')
def _():
for _ in vary (200):
a = randint(100, 1000)
exp = ref_sol(a)
take a look at.assert_equals(seq(a), exp)