Created
January 3, 2013 13:21
-
-
Save anonymous/4443428 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local sliding = require("sliding") | |
local avg = sliding.new('taps', 'dt', 10) | |
avg:add({ dt = 5, taps = 5}) | |
print(tostring(avg)) | |
avg:add({ dt = 3, taps = 1}) | |
print(tostring(avg)) | |
avg:add({ dt = 1, taps = 1}) | |
print(tostring(avg)) | |
avg:add({ dt = 3, taps = 1}) | |
print(tostring(avg)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local sliding = {} | |
local slidingMt = { | |
__index = sliding, | |
__tostring = function(self) | |
return "Avg: " .. self.avg .. | |
" Total: " .. self.total .. | |
" LimTotal: " .. self.limTotal .. | |
" Items: " .. #self.items | |
end | |
} | |
function sliding.new(avgField, limField, limit) | |
local slide = setmetatable({ | |
items = {}, | |
limField = limField, | |
avgField = avgField, | |
limit = limit, | |
avg = nil, | |
total = 0, | |
limTotal = 0, | |
}, slidingMt) | |
return slide | |
end | |
function sliding:add(val) | |
-- Check which values this new one pushes off the end, if any | |
local diff = self.limTotal + val[self.limField] - self.limit | |
if diff > 0 then | |
print("Over limit! ", diff) | |
-- Pop off the right number of things | |
-- Although table.remove is expensive :( | |
-- have to remove at least one | |
local limRemoved = self.items[1][self.limField] | |
local valRemoved = self.items[1][self.avgField] | |
table.remove(self.items, 1) | |
local numRemoved = 1 | |
while limRemoved < diff do | |
numRemoved = numRemoved + 1 | |
limRemoved = limRemoved + self.items[i][self.limField] | |
valRemoved = valRemoved + self.items[i][self.avgField] | |
table.remove(self.items, 1) -- Remove the first element again. Slow? | |
end | |
print("Done! Removed ", numRemoved, " with total ", valRemoved) | |
self.total = self.total - valRemoved | |
self.limTotal = self.limTotal - limRemoved | |
end | |
print("Adding item with val ", val[self.avgField], " and limit ", val[self.limField]) | |
self.items[#self.items+1] = val | |
self.total = self.total + val[self.avgField] | |
self.limTotal = self.limTotal + val[self.limField] | |
self.avg = self.total / #self.items | |
end | |
return sliding | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment