I want to generate iterations terms of a Van Eck sequence with a custom starting term.
The result of the function is an incorrect sequence and I have no clue why.
I’ve tried looking at the Rosetta Code example’s, but the code for the solutions don’t make sense to me.
I understand how to do the sequence on paper, but I’m really struggling to implement it into code for some reason.
Here is my current code:
local function van(number, iterations)
local sequence = {}
local positions = {}
for i = 1, iterations do
local last = positions[number]
if (last) then
number = i - last
else
number = 0
end
sequence[i] = number
positions[number] = i
end
return sequence
end
local sequence = van(0, 9)
print(table.concat(sequence, ", "))
And the outputted sequence: 0, 1, 1, 1, 1, 1, 1, 1, 1
And here is what it should output: 0, 0, 1, 0, 2, 0, 2, 2, 1, 6
I’ve remade your code with a bunch of debug prints so you can easily figure out what is happening
Not exactly sure what makes your code break but I believe it’s positions[number] = i giving the wrong position of the last position.
local function van(number, iterations)
local sequence = {}
local prevPos = {}
local lastPos = {}
local wasFirstOne = false
for i = 1, iterations do
print("checking number ", number)
if wasFirstOne then
print("before it was the first one")
number = 0
wasFirstOne = false
else
if lastPos[number] then
print("found it before at pos ", prevPos[number])
number = i - prevPos[number] - 1
if not lastPos[number] then
print("but hey,", number, "wasn't found before")
wasFirstOne = true
end
else
print("wow it was the first one")
wasFirstOne = true
end
end
sequence[i] = number
prevPos[number] = lastPos[number]
lastPos[number] = i
print(table.concat(sequence, ", "))
print("--------")
end
return sequence
end
local sequence = van(0, 10)
print(table.concat(sequence, ", "))
I used this video to figure out what is happening with the algorithm, perhaps it may also help you.