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
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.
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)
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.