So for example, If I had
local set = {"1","2","3","4","5",6"}
--Can I do something like this to find a median of the data?
print(set[Median])
I just wonder if there is a way to find maybe the average of data and be able to apply them in-game.
So for example, If I had
local set = {"1","2","3","4","5",6"}
--Can I do something like this to find a median of the data?
print(set[Median])
I just wonder if there is a way to find maybe the average of data and be able to apply them in-game.
function Median(...)
local nums = {...}
table.sort(nums)
local mid = #nums/2
local median
if math.floor(mid)==mid then
median = nums[mid]
else
median = (nums[math.floor(mid)]+nums[math.ceil(mid)])/2
end
return median
end
function Mean(...)
local nums = {...}
local sum = 0
for _,v in pairs(nums) do
sum = sum + v
end
return sum/#nums
end
Call them like so:
print(Mean(5,10,20,2,1,4))
print(Median(5,10,20,2,1,4))
If you would prefer to use tables, change the '...' parameters to 'nums' and remove the lines that say local nums = {...}
Oh okay, thanks.
Your implementation of Median is off-by-one. You should compute mid as (#nums+1)/2.
You should probably accept the answer.
This discussion is preserved as it was. New answers, comments, and votes are closed.
2 comments
Careful -- those are strings (text), not numbers. Drop the quotes if you mean numbers!
Woops, thanks you.