So basically a mode is the most frequently said value in a table. How would I find that in roblox? Heres a code I found from another post, I can’t seem to get it to work. What am I doing wrong?
Im trying to make a voting system where the person with the most votes is chosen.
This is inside a script:
local mostvotedplr = ""
local voteenabled = false
local playersvoted = {
}
local function countvotes()
table.sort(playersvoted, function(a, b)
print(b) -- this doesnt show in output
mostvotedplr = b
return a < b
end)
end
--inside a function
local plr2 = game:GetService("Players"):FindFirstChild(plr)
if plr2 then
table.insert(playersvoted, plr) -- plr is a string value
else
rs.Warn:FireClient(player, "[server]: this player cannot be found")
end
--in another function
countvotes()
It might help if you filled in the playersvoted table with some example data.
This is the kind of thing I might expect to see for mode:
local votes = {}
local function vote(option)
votes[option] = votes[option] and votes[option] + 1 or 1
end
local function countVotes()
local winner = {}
local bestVal = 0
for k,v in pairs(votes) do
if v > bestVal then
winner = {k}
bestVal = v
elseif v == bestVal then
table.insert(winner, k)
else
-- lower do nothing
end
end
return winner
end
vote('fred')
vote('fred')
vote('fred')
vote('red')
vote('red')
vote('red')
vote('ed')
vote('ed')
vote('ed')
vote('ed')
vote('cindy')
vote('cindy')
vote('cindy')
vote('cindy')
-- this accounts for ties
for _,winner in ipairs(countVotes()) do
print(winner)
end
local function GetTableMode(Table)
local Dictionary = {}
for _, Value in ipairs(Table) do
Dictionary[Value] = if Dictionary[Value] then Dictionary[Value] + 1 else 1
end
local Array = {}
for Key, Value in pairs(Dictionary) do
table.insert(Array, {Key, Value})
end
table.sort(Array, function(Left, Right) return Left[2] > Right[2] end)
return Array[1][1]
end
local Mode = GetTableMode{1, 2, 3, 4, 5, 5, 6, 7, 8, 9}
print(Mode) --5
Before you ask about the function call’s syntax.
If the function has one single argument and this argument is either a literal string or a table constructor, then the parentheses are optional