Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Is there a way to find the Median or Average from a set of data in a table and use them in game?

Asked by
AmVolt 60
8 years ago

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.

2
Careful -- those are strings (text), not numbers. Drop the quotes if you mean numbers! BlueTaslem 18071 — 8y
0
Woops, thanks you. AmVolt 60 — 8y

1 answer

Log in to vote
1
Answered by 8 years ago

Please provide explanation with your answers. Simply posting code does not spread knowledge of integral scripting processes which helps people understand the logic and reasoning behind your answer.
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 = {...}

0
Oh okay, thanks. AmVolt 60 — 8y
1
Your implementation of `Median` is off-by-one. You should compute `mid` as `(#nums+1)/2`. BlueTaslem 18071 — 8y
0
You should probably accept the answer. MechaScripter 35 — 8y
Ad

Answer this question