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
9 years ago

So for example, If I had

1local set = {"1","2","3","4","5",6"}
2--Can I do something like this to find a median of the data?
3 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 — 9y
0
Woops, thanks you. AmVolt 60 — 9y

1 answer

Log in to vote
1
Answered by 9 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.
01function Median(...)
02    local nums = {...}
03    table.sort(nums)
04    local mid = #nums/2
05    local median
06    if math.floor(mid)==mid then
07        median = nums[mid]
08    else
09        median = (nums[math.floor(mid)]+nums[math.ceil(mid)])/2
10    end
11    return median
12end
13 
14function Mean(...)
15    local nums = {...}
View all 21 lines...

Call them like so:

1print(Mean(5,10,20,2,1,4))
2print(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 — 9y
1
Your implementation of `Median` is off-by-one. You should compute `mid` as `(#nums+1)/2`. BlueTaslem 18071 — 9y
0
You should probably accept the answer. MechaScripter 35 — 9y
Ad

Answer this question