Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- heap = {
- new = function()
- return {
- size = 0,
- elements = {}
- }
- end,
- _exch = function(h, x, y)
- assert(type(x) == "number")
- assert(type(y) == "number")
- local temp = h.elements[x]
- h.elements[x] = h.elements[y]
- h.elements[y] = temp
- end,
- _sink = function(h, parentIndex)
- local N = h.size
- while (parentIndex*2) <= N do
- local childIndex = parentIndex * 2
- if childIndex < N and lowerPriority(h.elements[childIndex],
- h.elements[childIndex+1]) then
- childIndex = childIndex + 1
- end
- if not lowerPriority(h.elements[parentIndex], h.elements[childIndex]) then
- break
- else
- heap._exch(h, parentIndex, childIndex)
- parentIndex = childIndex
- end
- end
- end,
- _swim = function(h, childIndex)
- while childIndex > 1 and lowerPriority(h.elements[math.floor(childIndex/2)],
- h.elements[childIndex]) do
- local parentIndex = math.floor(childIndex / 2)
- heap._exch(h, childIndex, parentIndex)
- childIndex = parentIndex
- end
- end,
- insert = function(h, element)
- table.insert(h.elements, element)
- h.size = h.size + 1
- heap._swim(h, h.size)
- end,
- extract = function(h)
- heap._exch(h, 1, h.size)
- h.size = h.size - 1
- local ret = table.remove(h.elements)
- heap._sink(h, 1)
- return ret
- end,
- head = function(h)
- local element = h.elements[1]
- return element
- end
- }
- function action(name, balance, priority, command)
- assert(type(name) == "string")
- assert(type(balance) == "string")
- assert(type(priority) == "number")
- assert(type(command) == "function" or type(command) == "string")
- local actionCommand = function() end
- if type(command) == "string" then
- actionCommand = function()
- send(command)
- end
- else
- actionCommand = command
- end
- local action = {
- name = name,
- balance = balance,
- priority = priority,
- command = actionCommand
- }
- setmetatable(action, {
- __lt = function(a, b)
- return a.priority < b.priority
- end
- })
- return action
- end
- function lowerPriority(x, y)
- assert(type(x) == "table")
- assert(type(y) == "table")
- assert(type(x.priority) == "number")
- assert(type(y.priority) == "number")
- return x.priority >= y.priority
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement