so i have a table with bools right? and i want to see what bool is most common. for example:
1 = true
2 = true
3 = fale
in this case “true” would be the most common and therefore the output would be true
1 = false
2 = true
3 = false
In this case false would be most common, so the output would be false
How do i do this? can i do this?
i think i found a solution atleast for tables of 3:
A loop for the table, then add toa number. when a bool is true.
If that number is greater than 1 then make the output true, else make it false
I still dont have a solution for more than 3 tho
CZXPEK
(czo)
July 6, 2024, 12:40am
#3
local TestTable = {
[1] = true,
[2] = true,
[3] = false,
[4] = false,
[5] = false,
[6] = false
}
local GetAvg = function(Table)
local Values = {["true"] = 0, ["false"] = 0}
for i,v in pairs(Table) do
Values[tostring(v)] += 1
end
if (Values["true"] == Values["false"]) then
return nil --// both are equal, return nil
elseif (Values["true"] > Values["false"]) then
return true
else
return false
end
end
print(GetAvg(TestTable))
Prototrode
(Vernumerator)
July 6, 2024, 12:44am
#4
If true is 1 and false is -1, you just add everything up and see if the final number is positive or negative. If it’s zero, then both are equally common.
local sum: number = 0
for _, v in t do --t is the table with your booleans
sum += if v then 1 else -1
end
local mostCommon: boolean? = if sum == 0 then nil else sum > 0 --nil if both are equally common
1 Like