Task[edit]
Write a program to find the mode value of a collection.

The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.

If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriate or possible to support an unspecified value type, use integers.

See also
Tasks for calculating statistical measures



in one go
moving (sliding window)
moving (cumulative)

Mean
Arithmetic

Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means


Averages/Simple moving average




Geometric

Averages/Pythagorean means




Harmonic

Averages/Pythagorean means




Quadratic

Averages/Root mean square




Circular

Averages/Mean angle
Averages/Mean time of day




Median

Averages/Median




Mode

Averages/Mode




Standard deviation

Statistics/Basic



Cumulative standard deviation




function mode(tbl) -- returns table of modes and count
	assert(type(tbl) == 'table')
	local counts = { }
	for _, val in pairs(tbl) do
		-- see http://lua-users.org/wiki/TernaryOperator
		counts[val] = counts[val] and counts[val] + 1 or 1
	end
	local modes = { }
	local modeCount = 0
	for key, val in pairs(counts) do
		if val > modeCount then
			modeCount = val
			modes = {key}
		elseif val == modeCount then
			table.insert(modes, key)
		end
	end
	return modes, modeCount
end
 
modes, count = mode({1,3,6,6,6,6,7,7,12,12,17})
for _, val in pairs(modes) do io.write(val..' ') end
print("occur(s) ", count, " times")
 
modes, count = mode({'a', 'a', 'b', 'd', 'd'})
for _, val in pairs(modes) do io.write(val..' ') end
print("occur(s) ", count, " times")
 