Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

What is the most efficient way to find the smallest value in a table?

Example Table

{{"Random String", 8},{"Random String2", 14},{"Random String3", 3}}

What is the best way to sort the table so it returns {"Random String3", 3} because it's second value is the smallest?

Currently I am using this script, but it seems very inefficient

		local smallestF = math.huge
		for mynodeSpot,mynode in pairs(specificOpenList) do
			if mynode[9] < smallestF then
				smallestF = mynode[9]
				currentNode = mynode
				currentNodeSpot = mynodeSpot
			end
		end

I did some research and found this

> mytable = {2,4,6,24,7,5}
> print(math.min(unpack(mytable)))
2

However, when using the type of table that I am using, it doesn't work. For some reason it returns the 8, which isn't the smallest value, and even if it did I would want the whole table so I can access the string attached to it.

> mytable = {{"Random String", 8},{"Random String2", 14},{"Random String3", 3}}
> print(math.min(unpack(mytable)[2]))
8

What is the best way to do this?

2 comments

1

Why don't you use a dictionary instead of what you're doing currently?

0

How would I do it? Maybe I could, but I use the table for other things so reorganizing it would cause a lot more problems than it would solve.

2 answers

✓ Accepted answer

You can use table.sort for this.

The second parameter allows you to further define the sort function.

local mytable = {{"Random String", 8}, {"Random String2", 14}, {"Random String3",3}};
table.sort(mytable, function(a, b) return a[2] < b[2]; end);

-- table now sorted from least to greatest by sub tables second value.
print(mytable[1][1], mytable[1][2]);
print(mytable[2][1], mytable[2][2]);
print(mytable[3][1], mytable[3][2]);

--[[
Output:
Random String3  3
Random String   8
Random String2  14
--]]

2 comments

0

Sorting the table is much more inefficient than finding the minimum.

0

This may be true adark, but for what I am doing sorting the table once is much more efficient than finding the minimum hundreds of times.

Your code is actually the best way to find the minimum Value in the table. However, you can make it slightly more efficient by moving currentNode = mynode to outside the loop:

local smallestF = math.huge
for mynodeSpot,mynode in pairs(specificOpenList) do
    if mynode[9] < smallestF then
        smallestF = mynode[9]
        currentNodeSpot = mynodeSpot
    end
end
currentNode = specificOpenList[currentNodeSpot]

This discussion is preserved as it was. New answers, comments, and votes are closed.