Why am I getting nil?

I have no idea what I’m doing

local n = 41

function josephus(n)
	local positions = {}
	local tokill = 2
	local nextkiller = 1
	
	for i = 1, n do
		positions[i] = i
	end
	
	while #positions>1 do
		tokill = next(positions, nextkiller)
		print(tokill)
		nextkiller = next(positions, tokill)
		table.remove(positions, tokill)
		wait()
	end
end

josephus(n)

If anyone isn’t familiar with this, I’m basically trying to remove every other item in a table over and over until I’m only left with one (Like the below image), at least thats the intended effect.

image

In the script where n is 41 (40 numbers I have to remove in that fashion), the execution order should be 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 1, 5, 9, 13, etc, but obviously it’s not turning out that way.

So can someone tell me what I did wrong? It does it right until it has to remove number 30, which from that point it does all of it wrong, Maybe I’m not using next right? Thanks in advance.

image

Instead of using next() you can find out every other number by using the number % 2
Example:

print(1%2) 
-- Prints 1 
print(4%2)
-- Prints 0

You could loop through the table and use table.remove on everything that equals 0 when you do number % 2. Do this over and over, as you intended.
I am not fully sure if this is what your looking for but it may help.

1 Like

I like this idea of using modulus but…
image

It’s doing the same thing unfortunately

local n = 41

local function geteveryOther(interval, startpos)
    local item = 1
    local tab = {}
    
    for i = 1, n do
        tab[i] = i
    end

    for i, v in ipairs(tab) do
        if i >= startpos and (i - startpos) % interval == 0 then
            table.remove(tab, i)
            print(i)
            item = item + 1
        end
    end
end

geteveryOther(2, 0)

This is what I got. It removes every other index until the end.
The values of the indexes that are removed matches the execution order.

local n = 41

function josephus(n)
	local positions = {}
	local tokill = 2

	for i = 1, n do
		table.insert(positions, i)
	end

	while #positions > 1 do
		if tokill > #positions then
			tokill = tokill % 2 + 1
		end
		print(positions[tokill])
		table.remove(positions, tokill)
		tokill = tokill + 1
	end
end

josephus(n)

Instead of using table.remove(positions, tokill), try positions[tokill] = nil.