2013-02-19 03:57:14 +00:00
|
|
|
--[[
|
|
|
|
Simple math helper function
|
|
|
|
]]--
|
|
|
|
|
2013-10-18 20:38:07 +00:00
|
|
|
local Math = {}
|
|
|
|
|
|
|
|
function Math.roundAwayFromZero(num)
|
2013-02-19 03:57:14 +00:00
|
|
|
if num > 0 then
|
|
|
|
return math.ceil(num)
|
|
|
|
else
|
|
|
|
return math.floor(num)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2013-10-18 20:38:07 +00:00
|
|
|
function Math.round(num)
|
2013-02-19 03:57:14 +00:00
|
|
|
return math.floor(num + 0.5)
|
|
|
|
end
|
|
|
|
|
2013-10-18 20:38:07 +00:00
|
|
|
function Math.oddEven(number)
|
2013-02-19 03:57:14 +00:00
|
|
|
if number % 2 == 1 then
|
|
|
|
return "odd"
|
|
|
|
else
|
|
|
|
return "even"
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2013-10-18 20:38:07 +00:00
|
|
|
local function tmin_max(tab, func, op)
|
2013-02-21 05:16:47 +00:00
|
|
|
if #tab == 0 then return nil, nil end
|
|
|
|
local index, value = 1, tab[1]
|
|
|
|
for i = 2, #tab do
|
|
|
|
if func then
|
|
|
|
if func(value, tab[i]) then
|
|
|
|
index, value = i, tab[i]
|
|
|
|
end
|
|
|
|
elseif op == "min" then
|
|
|
|
if value > tab[i] then
|
|
|
|
index, value = i, tab[i]
|
|
|
|
end
|
|
|
|
elseif op == "max" then
|
|
|
|
if value < tab[i] then
|
|
|
|
index, value = i, tab[i]
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
return index, value
|
|
|
|
end
|
|
|
|
|
|
|
|
--[[
|
|
|
|
Return the minimum element of a table.
|
|
|
|
The optional argument func specifies a one-argument ordering function.
|
|
|
|
]]--
|
2013-10-18 20:38:07 +00:00
|
|
|
function Math.tmin(tab, func)
|
2013-02-21 05:16:47 +00:00
|
|
|
return tmin_max(tab, func, "min")
|
|
|
|
end
|
2013-02-19 03:57:14 +00:00
|
|
|
|
2013-02-21 05:16:47 +00:00
|
|
|
--[[
|
|
|
|
Return the maximum element of a table.
|
|
|
|
The optional argument func specifies a one-argument ordering function.
|
|
|
|
]]--
|
2013-10-18 20:38:07 +00:00
|
|
|
function Math.tmax(tab, func)
|
2013-02-21 05:16:47 +00:00
|
|
|
return tmin_max(tab, func, "max")
|
|
|
|
end
|
2013-10-18 20:38:07 +00:00
|
|
|
|
|
|
|
return Math
|