Find Lowest not Taken Number in Table

Hello! I need help because I am smoll brain.

I need a function that can find the lowest possible not taken number in a table.

For Example:

table = {1, 2, 4, 6, 7}

I want the function to find the lowest, non-taken number. So the number the function should find would be 3.

I had a crack at it. My steps are

  1. Copy the table. We wouldn’t want to modify the original if it’s being used elsewhere.
  2. Sort the table. This enables step 4.
  3. Remove duplicates.
  4. 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
2 Likes

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
1 Like

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.

2 Likes