Copy the table. We wouldn’t want to modify the original if it’s being used elsewhere.
Sort the table. This enables step 4.
Remove duplicates.
March through the table. If the next number isn’t the current number + 1, then it is missing.
If the table is empty or there isn’t a number missing, it returns nil.
local t = {4, 2, 2, 2, 4, 1, 5, 7, 9, 10, 12, 15}
local function GetFirstMissing(t)
-- Copy the table
local copy = {}
for i, v in ipairs(t) do
copy[i] = v
end
-- Sort the table
table.sort(copy)
-- Remove duplicates
local hash = {}
local basis = {}
for i, v in ipairs(copy) do
if not hash[v] then
hash[v] = true
table.insert(basis, v)
end
end
-- Find first missing number
local len = #basis
for i, v in ipairs(basis) do
if i < len and basis[i + 1] ~= v + 1 then
return v + 1
end
end
end
print("Missing: ", GetFirstMissing(t))
--> 3
I made this simple script in a couple of seconds might be able to help you only works if the numbers are in order and one of each or you could use @AstroCode’s but its a bit more advanced but also better but wasn’t sure you needed all of that.
local function findSmallest(tableValue)
for i = 1, #tableValue do
if i ~= tableValue[i] then
return i
end
end
end
local myTable = {1,2,3,4,5,10}
print(findSmallest(myTable)) -- prints 6
All you have to do is return i. Your solution assumes that the first entry is 1, the second is 2, etc. So if the sixth entry isn’t 6, then you’re missing 6.