Help me get highest value

ive looked around the forum for a bit and cannot find a solution

i need to get the highest value from a dictionary that would look something like this

{
   ["A"] = 2,
   ["B"] = 1,
   ["C"] = 2,
   ["D"] = 0
}

they could sometimes have a tie between 2 numbers since this is a voting type system so i’d like it to just pick a random one
please dont make a script or tell me how to order the example as thats just an example

thanks

First you sort the dictionary by putting the values as a array.

Then you check through the table for the maps with the same amount of highest votes (maps with tie) then put those in another table.

Similar problem to what I described and solved before:

1 Like

IDK why u dont want a script so ill just try and explain without one.

You want to create a for loop that iterates through all the keys. Prime the loop with a variable called highest or something. Set highest to 0. For every key check if the value is greater than the highest, and if it is set the highest to that key.

1 Like

hey im getting error invalid argument #2 to 'random' (interval is empty) at:

	local answerWithHighestVotes = {}
	for i = 2, #Result do
		local currentResultBeingChecked = Result[i]
		local answerVote = currentResultBeingChecked.Value
		if answerVote == answerWithHighestVotes  then -- check for tie
			table.insert(answerWithHighestVotes ,currentResultBeingChecked)
		end
	end

	local chosen = answerWithHighestVotes[math.random(1,#answerWithHighestVotes)] -- here
	print(chosen)

Check if length of answerWithHighestVotes is equal to 0. I think the error is saying the dictionary is empty?

yeah apparently its empty so nothing was added to it

i tried running the original code w/o changing the variable names and still no luck

Here is a reworked version of your own script:

local Result = {
   ["A"] = 2,
   ["B"] = 1,
   ["C"] = 2,
   ["D"] = 0
}

local Values = {}

for _, v in pairs(Result) do
   table.insert(Values,v)
end

table.sort(Value,function(a,b)
   return a > b
end)

local Highest = Values[1]
local Choices = {}

for i, v in pairs(Result) do
   if v == Highest then
      table.insert(Choices,i)
   end
end

local Chosen = Choices[math.random(#Choices)]

print(Chosen)

Oh yeah just realized it’ll error if the table is empty like @Com3t_06 said. This happens when no maps are tied and there is only one winner which I forgot.

To avoid this you can change the starting position to add the map with the highest vote first.

i=1
1 Like

Edit: I realized you were using a different method, so disregard what was previously here. Check out the code I posted earlier!

i know its been years but if anyone has issues with this i think you can use math.max