Finding the highest value in a dictionary

You can write your topic however you want, but you need to answer these questions:

  1. So I have a dictionary and it has a random rng value which is assigned to npc in my game and next to the rng number is a score the bot got, now I want to find which bot gets the best score

  2. The Issue is that I cant get the value of the bots score in the dictionary and compare it

game.ReplicatedStorage.BestFit.Event:Connect(function()
	local Highest = 0
	for Item, Cost in pairs(FitnessScores) do
		if Highest < Cost then
                        Highest = Cost
		end
		
	end
end)

The error I get is -

attempt to compare number < table

  1. I Have Tried putting a # before the Cost, but it don’t work

Is the “Cost” variable that you’re using a table? If so then you would need to compare it in the loop as:

for Item, Cost in pairs(FitnessScores) do
		if Highest < Cost[Item] then
                        Highest = Cost[Item]
		end
		
	end

this is the hole script

local Num = 1



local FitnessScores = {
	
	
	
	
}



game.ReplicatedStorage.SendFitness.Event:Connect(function(Fit, Bot)
	--print(Bot)
	FitnessScores["Name: " .. Bot .. " Num: " .. Num] = {Fit}
	--print(FitnessScores)
	Num += 1
end)

game.ReplicatedStorage.BestFit.Event:Connect(function()
	local Highest = 0
	for Item, Cost in pairs(FitnessScores) do
		if Highest < Cost[Num] then
			Highest = Cost
		end
	end
end)

Looks like from just a quick reading it’s maybe returning a table and not a number that it’s able to check. You will need to specify when checking the highest number that it checks the returned tables number and not just the table.

soooooooooooooooooooooooo how would i do this?

yea when i print the cost it returns [1] = “23.543123545345” but idk how to get just the number

Try tonumber() perhaps?

Also when using tonumber(), make sure the result isn’t nil.

1 Like

Omg ty, For people with same problem here is the script

game.ReplicatedStorage.BestFit.Event:Connect(function()
	local Highest = 0
	for Item, Cost in pairs(FitnessScores) do
		if Highest <  tonumber(Cost[1]) then
			Highest = tonumber(Cost[1])
			print(Highest)
		end
	end
end)

since the Cost was printing [1] = “34.65345” I changed “Cost” to ToNumber(Cost[1])

Make sure also, that tonumber() ~= nil, to avoid any errors:

game.ReplicatedStorage.BestFit.Event:Connect(function()
	local Highest = 0
	for Item, Cost in pairs(FitnessScores) do
		if tonumber(Cost[1]) and Highest <  tonumber(Cost[1]) then
			Highest = tonumber(Cost[1])
			print(Highest)
		end
	end
end)
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.