Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Is there a way to find the Median or Average from a set of data in a table and use 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.

2 comments

2

Careful -- those are strings (text), not numbers. Drop the quotes if you mean numbers!

0

Woops, thanks you.

1 answer

✓ Accepted 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 = {...}

3 comments

0

Oh okay, thanks.

1

Your implementation of Median is off-by-one. You should compute mid as (#nums+1)/2.

0

You should probably accept the answer.

This discussion is preserved as it was. New answers, comments, and votes are closed.