pax_global_header00006660000000000000000000000064133706145300014514gustar00rootroot0000000000000052 comment=579662c1ac47bec954f29195a1d5fd9b4d5f5cb6 binaryheap.lua-version_0v4/000077500000000000000000000000001337061453000161365ustar00rootroot00000000000000binaryheap.lua-version_0v4/.busted000066400000000000000000000001351337061453000174240ustar00rootroot00000000000000return { default = { verbose = true, coverage = true, output = "gtest", }, } binaryheap.lua-version_0v4/.editorconfig000066400000000000000000000002331337061453000206110ustar00rootroot00000000000000root = true [*] end_of_line = lf insert_final_newline = true charset = utf-8 [*.lua] indent_style = space indent_size = 2 [Makefile] indent_style = tab binaryheap.lua-version_0v4/.gitignore000066400000000000000000000000231337061453000201210ustar00rootroot00000000000000.DS_Store luacov.* binaryheap.lua-version_0v4/.luacov000066400000000000000000000001701337061453000174260ustar00rootroot00000000000000modules = { ["binaryheap"] = "src/binaryheap.lua", ["binaryheap.*"] = "src" } runreport = true deletestats = true binaryheap.lua-version_0v4/README.md000066400000000000000000000022751337061453000174230ustar00rootroot00000000000000binaryheap.lua ============== [Binary heap](http://en.wikipedia.org/wiki/Binary_heap) implementation Both the [source code](https://github.com/Tieske/binaryheap.lua) as well as the [documentation](http://tieske.github.io/binaryheap.lua) are on github Based on [original code](http://lua-users.org/lists/lua-l/2015-04/msg00137.html) by Oliver Kroth, with [extras](http://lua-users.org/lists/lua-l/2015-04/msg00133.html) as proposed by Sean Conner. Contributions ============= This library was create by contributions from Oliver Kroth, Thijs Schreijer, Boris Nagaev History ======= Version 0.4, 7-Nov-2018 - [breaking] added additional tests, mostly on returning errors, minor behaviour changes - added `size` method - fixed a lot of linter issues Version 0.3, 15-Jul-2018 - bugfix `unique:pop` returning wrong order results (by Daurnimator) - change `unique:peek` returning same order as `pop` - added `unique:peekValue` returning just the value Version 0.2, 21-Apr-2015 - bugfix `remove` function (by Boris Nagaev) - configurable comparison function for the tree Version 0.1, 20-Apr-2015 - Initial release Copyright ========= Copyright 2015-2018 Thijs Schreijer License ======= MIT/X11 binaryheap.lua-version_0v4/binaryheap-0.4-1.rockspec000066400000000000000000000012461337061453000224530ustar00rootroot00000000000000package = "binaryheap" version = "0.4-1" source = { url = "https://github.com/Tieske/binaryheap.lua/archive/version_0v4.tar.gz", dir = "binaryheap.lua-version_0v4" } description = { summary = "Binary heap implementation in pure Lua", detailed = [[ Binary heaps are an efficient sorting algorithm. This module implements a plain binary heap (without reverse lookup) and a 'unique' binary heap (with unique payloads and reverse lookup). ]], license = "MIT/X11", homepage = "https://github.com/Tieske/binaryheap.lua" } dependencies = { "lua >= 5.1", } build = { type = "builtin", modules = { binaryheap = "src/binaryheap.lua" } } binaryheap.lua-version_0v4/config.ld000066400000000000000000000003141337061453000177220ustar00rootroot00000000000000project='binaryheap.lua' title='binaryheap' description='Module to create binary heaps' format='markdown' file='./src/' dir='docs' readme='readme.md' sort=true sort_modules=true all=false style='./docs/' binaryheap.lua-version_0v4/docs/000077500000000000000000000000001337061453000170665ustar00rootroot00000000000000binaryheap.lua-version_0v4/docs/index.html000066400000000000000000000403671337061453000210750ustar00rootroot00000000000000 binaryheap

Module binaryheap

Binary heap implementation

A binary heap (or binary tree) is a sorting algorithm.

The 'plain binary heap' is managed by positions. Which are hard to get once an element is inserted. It can be anywhere in the list because it is re-sorted upon insertion/deletion of items. The array with values is stored in field values:

peek = heap.values[1]

A 'unique binary heap' is where the payload is unique and the payload itself also stored (as key) in the heap with the position as value, as in;

heap.reverse[payload] = [pos]

Due to this setup the reverse search, based on payload, is now a much faster operation because instead of traversing the list/heap, you can do;

pos = heap.reverse[payload]

This means that deleting elements from a 'unique binary heap' is faster than from a plain heap.

All management functions in the 'unique binary heap' take payload instead of pos as argument. Note that the value of the payload must be unique!

Fields of heap object:

  • values - array of values
  • payloads - array of payloads (unique binary heap only)
  • reverse - map from payloads to indices (unique binary heap only)

Basic heap

binaryHeap (swap, erase, lt) Creates a new binary heap.

Plain heap

heap:insert (value) Inserts an element in the heap.
heap:peek () Returns the element at the top of the heap, without removing it.
heap:pop () Removes the top of the heap and returns it.
heap:remove (pos) Removes an element from the heap.
heap:size () Returns the number of elements in the heap.
heap:update (pos, newValue) Updates the value of an element in the heap.
maxHeap (gt) Creates a new max-heap, where the largest value is at the top.
minHeap (lt) Creates a new min-heap, where the smallest value is at the top.

Unique heap

heap:size () Returns the number of elements in the heap.
maxUnique (gt) Creates a new max-heap with unique payloads.
minUnique (lt) Creates a new min-heap with unique payloads.
unique:insert (value, payload) Inserts an element in the heap.
unique:peek () Returns the element at the top of the heap, without removing it.
unique:peekValue () Returns the element at the top of the heap, without removing it.
unique:pop () Removes the top of the heap and returns it.
unique:remove (payload) Removes an element from the heap.
unique:update (payload, newValue) Updates the value of an element in the heap.
unique:valueByPayload (payload) Returns the value associated with the payload


Basic heap

This is the base implementation of the heap. Under regular circumstances this should not be used, instead use a Plain heap or Unique heap.
binaryHeap (swap, erase, lt)
Creates a new binary heap. This is the core of all heaps, the others are built upon these sorting functions.

Parameters:

  • swap (function) swap(heap, idx1, idx2) swaps values at idx1 and idx2 in the heaps heap.values and heap.payloads lists (see return value below).
  • erase (function) swap(heap, position) raw removal
  • lt (function) in lt(a, b) returns true when a < b (for a min-heap)

Returns:

    table with two methods; heap:bubbleUp(pos) and heap:sinkDown(pos) that implement the sorting algorithm and two fields; heap.values and heap.payloads being lists, holding the values and payloads respectively.

Plain heap

A plain heap carries a single piece of information per entry. This can be any type (except nil), as long as the comparison function used to create the heap can handle it.
heap:insert (value)
Inserts an element in the heap.

Parameters:

  • value the value used for sorting this element

Returns:

    nothing, or throws an error on bad input
heap:peek ()
Returns the element at the top of the heap, without removing it.

Returns:

    value at the top, or nil if there is none
heap:pop ()
Removes the top of the heap and returns it.

Returns:

    value at the top, or nil if there is none
heap:remove (pos)
Removes an element from the heap.

Parameters:

  • pos the position to remove

Returns:

    value, or nil if a bad pos value was provided
heap:size ()
Returns the number of elements in the heap.

Returns:

    number of elements
heap:update (pos, newValue)
Updates the value of an element in the heap.

Parameters:

  • pos the position which value to update
  • newValue the new value to use for this payload
maxHeap (gt)
Creates a new max-heap, where the largest value is at the top.

Parameters:

  • gt (optional) comparison function (greater-than), see binaryHeap.

Returns:

    the new heap
minHeap (lt)
Creates a new min-heap, where the smallest value is at the top.

Parameters:

  • lt (optional) comparison function (less-than), see binaryHeap.

Returns:

    the new heap

Unique heap

A unique heap carries 2 pieces of information per entry.

  1. The value, this is used for ordering the heap. It can be any type (except nil), as long as the comparison function used to create the heap can handle it.
  2. The payload, this can be any type (except nil), but it MUST be unique.

With the 'unique heap' it is easier to remove elements from the heap.

heap:size ()
Returns the number of elements in the heap.

Returns:

    number of elements
maxUnique (gt)
Creates a new max-heap with unique payloads. A max-heap is where the largest value is at the top.

NOTE: All management functions in the 'unique binary heap' take payload instead of pos as argument.

Parameters:

  • gt (optional) comparison function (greater-than), see binaryHeap.

Returns:

    the new heap
minUnique (lt)
Creates a new min-heap with unique payloads. A min-heap is where the smallest value is at the top.

NOTE: All management functions in the 'unique binary heap' take payload instead of pos as argument.

Parameters:

  • lt (optional) comparison function (less-than), see binaryHeap.

Returns:

    the new heap
unique:insert (value, payload)
Inserts an element in the heap.

Parameters:

  • value the value used for sorting this element
  • payload the payload attached to this element

Returns:

    nothing, or throws an error on bad input
unique:peek ()
Returns the element at the top of the heap, without removing it.

Returns:

    payload, value, or nil if there is none
unique:peekValue ()
Returns the element at the top of the heap, without removing it.

Returns:

    value at the top, or nil if there is none

Usage:

    -- simple timer based heap example
    while true do
      sleep(heap:peekValue() - gettime())  -- assume LuaSocket gettime function
      coroutine.resume((heap:pop()))       -- assumes payload to be a coroutine,
                                           -- double parens to drop extra return value
    end
unique:pop ()
Removes the top of the heap and returns it. When used with timers, pop will return the payload that is due.

Note: this function returns payload as the first result to prevent extra locals when retrieving the payload.

Returns:

    payload, value, or nil if there is none
unique:remove (payload)
Removes an element from the heap.

Parameters:

  • payload the payload to remove

Returns:

    value, payload or nil if not found
unique:update (payload, newValue)
Updates the value of an element in the heap.

Parameters:

  • payload the payoad whose value to update
  • newValue the new value to use for this payload

Returns:

    nothing, or throws an error on bad input
unique:valueByPayload (payload)
Returns the value associated with the payload

Parameters:

  • payload the payload to lookup

Returns:

    value or nil if no such payload exists
generated by LDoc 1.4.6 Last updated 2018-11-07 17:56:33
binaryheap.lua-version_0v4/docs/ldoc.css000066400000000000000000000132641337061453000205270ustar00rootroot00000000000000body { color: #47555c; font-size: 16px; font-family: "Open Sans", sans-serif; margin: 0; background: #eff4ff; } a:link { color: #008fee; } a:visited { color: #008fee; } a:hover { color: #22a7ff; } h1 { font-size:26px; font-weight: normal; } h2 { font-size:22px; font-weight: normal; } h3 { font-size:18px; font-weight: normal; } h4 { font-size:16px; font-weight: bold; } hr { height: 1px; background: #c1cce4; border: 0px; margin: 15px 0; } code, tt { font-family: monospace; } span.parameter { font-family: monospace; font-weight: bold; color: rgb(99, 115, 131); } span.parameter:after { content:":"; } span.types:before { content:"("; } span.types:after { content:")"; } .type { font-weight: bold; font-style:italic } p.name { font-family: "Andale Mono", monospace; } #navigation { float: left; background-color: white; border-right: 1px solid #d3dbec; border-bottom: 1px solid #d3dbec; width: 14em; vertical-align: top; overflow: visible; } #navigation br { display: none; } #navigation h1 { background-color: white; border-bottom: 1px solid #d3dbec; padding: 15px; margin-top: 0px; margin-bottom: 0px; } #navigation h2 { font-size: 18px; background-color: white; border-bottom: 1px solid #d3dbec; padding-left: 15px; padding-right: 15px; padding-top: 10px; padding-bottom: 10px; margin-top: 30px; margin-bottom: 0px; } #content h1 { background-color: #2c3e67; color: white; padding: 15px; margin: 0px; } #content h2 { background-color: #6c7ea7; color: white; padding: 15px; padding-top: 15px; padding-bottom: 15px; margin-top: 0px; } #content h2 a { background-color: #6c7ea7; color: white; text-decoration: none; } #content h2 a:hover { text-decoration: underline; } #content h3 { font-style: italic; padding-top: 15px; padding-bottom: 4px; margin-right: 15px; margin-left: 15px; margin-bottom: 5px; border-bottom: solid 1px #bcd; } #content h4 { margin-right: 15px; margin-left: 15px; border-bottom: solid 1px #bcd; } #content pre { margin: 15px; } pre { background-color: rgb(50, 55, 68); color: white; border-radius: 3px; /* border: 1px solid #C0C0C0; /* silver */ padding: 15px; overflow: auto; font-family: "Andale Mono", monospace; } #content ul pre.example { margin-left: 0px; } table.index { /* border: 1px #00007f; */ } table.index td { text-align: left; vertical-align: top; } #navigation ul { font-size:1em; list-style-type: none; margin: 1px 1px 10px 1px; padding-left: 20px; } #navigation li { text-indent: -1em; display: block; margin: 3px 0px 0px 22px; } #navigation li li a { margin: 0px 3px 0px -1em; } #content { margin-left: 14em; } #content p { padding-left: 15px; padding-right: 15px; } #content table { padding-left: 15px; padding-right: 15px; background-color: white; } #content p, #content table, #content ol, #content ul, #content dl { max-width: 900px; } #about { padding: 15px; padding-left: 16em; background-color: white; border-top: 1px solid #d3dbec; border-bottom: 1px solid #d3dbec; } table.module_list, table.function_list { border-width: 1px; border-style: solid; border-color: #cccccc; border-collapse: collapse; margin: 15px; } table.module_list td, table.function_list td { border-width: 1px; padding-left: 10px; padding-right: 10px; padding-top: 5px; padding-bottom: 5px; border: solid 1px rgb(193, 204, 228); } table.module_list td.name, table.function_list td.name { background-color: white; min-width: 200px; border-right-width: 0px; } table.module_list td.summary, table.function_list td.summary { background-color: white; width: 100%; border-left-width: 0px; } dl.function { margin-right: 15px; margin-left: 15px; border-bottom: solid 1px rgb(193, 204, 228); border-left: solid 1px rgb(193, 204, 228); border-right: solid 1px rgb(193, 204, 228); background-color: white; } dl.function dt { color: rgb(99, 123, 188); font-family: monospace; border-top: solid 1px rgb(193, 204, 228); padding: 15px; } dl.function dd { margin-left: 15px; margin-right: 15px; margin-top: 5px; margin-bottom: 15px; } #content dl.function dd h3 { margin-top: 0px; margin-left: 0px; padding-left: 0px; font-size: 16px; color: rgb(128, 128, 128); border-bottom: solid 1px #def; } #content dl.function dd ul, #content dl.function dd ol { padding: 0px; padding-left: 15px; list-style-type: none; } ul.nowrap { overflow:auto; white-space:nowrap; } .section-description { padding-left: 15px; padding-right: 15px; } /* stop sublists from having initial vertical space */ ul ul { margin-top: 0px; } ol ul { margin-top: 0px; } ol ol { margin-top: 0px; } ul ol { margin-top: 0px; } /* make the target distinct; helps when we're navigating to a function */ a:target + * { background-color: #FF9; } /* styles for prettification of source */ pre .comment { color: #bbccaa; } pre .constant { color: #a8660d; } pre .escape { color: #844631; } pre .keyword { color: #ffc090; font-weight: bold; } pre .library { color: #0e7c6b; } pre .marker { color: #512b1e; background: #fedc56; font-weight: bold; } pre .string { color: #8080ff; } pre .number { color: #f8660d; } pre .operator { color: #2239a8; font-weight: bold; } pre .preprocessor, pre .prepro { color: #a33243; } pre .global { color: #c040c0; } pre .user-keyword { color: #800080; } pre .prompt { color: #558817; } pre .url { color: #272fc2; text-decoration: underline; } binaryheap.lua-version_0v4/docs/topics/000077500000000000000000000000001337061453000203675ustar00rootroot00000000000000binaryheap.lua-version_0v4/docs/topics/readme.md.html000066400000000000000000000053111337061453000231110ustar00rootroot00000000000000 binaryheap

binaryheap.lua

Binary heap implementation

Both the source code as well as the documentation are on github

Based on original code by Oliver Kroth, with extras as proposed by Sean Conner.

Contributions

This library was create by contributions from Oliver Kroth, Thijs Schreijer, Boris Nagaev

History

Version 0.4, 7-Nov-2018

  • [breaking] added additional tests, mostly on returning errors, minor behaviour changes
  • added size method
  • fixed a lot of linter issues

Version 0.3, 15-Jul-2018

Version 0.2, 21-Apr-2015

  • bugfix remove function (by Boris Nagaev)
  • configurable comparison function for the tree

Version 0.1, 20-Apr-2015

  • Initial release

Copyright

Copyright 2015-2018 Thijs Schreijer

License

MIT/X11

generated by LDoc 1.4.6 Last updated 2018-11-07 17:56:33
binaryheap.lua-version_0v4/examples/000077500000000000000000000000001337061453000177545ustar00rootroot00000000000000binaryheap.lua-version_0v4/examples/knight_dijkstra.lua000066400000000000000000000041251337061453000236400ustar00rootroot00000000000000-- Calculates shortest path of Knight from (1, 1) to (x, y). -- Prints matrix of shortest paths for all cells. -- Knight can't leave the rectangle from (1, 1) to (x, y). -- See https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm -- See http://stackoverflow.com/questions/2339101 -- Usage: -- $ lua knight_dijkstra.lua X Y local binaryheap = require 'binaryheap' local ROWS = tonumber(arg[2]) or 8 local COLS = tonumber(arg[1]) or 8 local unvisited = binaryheap.minUnique() local function Cell(x, y) return x .. '_' .. y end local function Coordinates(cell) local x, y = cell:match('(%d+)_(%d+)') return x, y end local function neighbours(cell) local x, y = Coordinates(cell) local gen = coroutine.wrap(function() coroutine.yield(x - 1, y - 2) coroutine.yield(x - 1, y + 2) coroutine.yield(x + 1, y - 2) coroutine.yield(x + 1, y + 2) coroutine.yield(x - 2, y - 1) coroutine.yield(x - 2, y + 1) coroutine.yield(x + 2, y - 1) coroutine.yield(x + 2, y + 1) end) return coroutine.wrap(function() for xx, yy in gen do if 1 <= xx and xx <= COLS and 1 <= yy and yy <= ROWS then coroutine.yield(Cell(xx, yy)) end end end) end for y = 1, ROWS do for x = 1, COLS do local cell = Cell(x, y) unvisited:insert(math.huge, cell) end end unvisited:update('1_1', 0) local final_distance = {} while unvisited:peek() do local current_distance, current = unvisited:peek() assert(not final_distance[current]) final_distance[current] = current_distance unvisited:remove(current) -- update neighbours local new_distance = current_distance + 1 for neighbour in neighbours(current) do if unvisited.reverse[neighbour] then local pos = unvisited.reverse[neighbour] local distance = unvisited.value[pos] if distance > new_distance then unvisited:update(neighbour, new_distance) end end end end for y = 1, ROWS do local row = {} for x = 1, COLS do local cell = Cell(x, y) local distance = final_distance[cell] table.insert(row, distance) end print(table.concat(row, ' ')) end binaryheap.lua-version_0v4/spec/000077500000000000000000000000001337061453000170705ustar00rootroot00000000000000binaryheap.lua-version_0v4/spec/binaryheap_spec.lua000066400000000000000000000474401337061453000227400ustar00rootroot00000000000000 local bh = require('binaryheap') local data = { { value = 98, payload = "pos08" }, -- 1 { value = 28, payload = "pos05" }, -- 2 { value = 36, payload = "pos06" }, -- 3 { value = 48, payload = "pos09" }, -- 4 { value = 68, payload = "pos10" }, -- 5 { value = 58, payload = "pos13" }, -- 6 { value = 80, payload = "pos15" }, -- 7 { value = 46, payload = "pos04" }, -- 8 { value = 19, payload = "pos03" }, -- 9 { value = 66, payload = "pos11" }, -- 10 { value = 22, payload = "pos02" }, -- 11 { value = 60, payload = "pos12" }, -- 12 { value = 15, payload = "pos01" }, -- 13 { value = 83, payload = "pos14" }, -- 14 { value = 59, payload = "pos07" }, -- 15 } local sort = function(t) table.sort(t, function(a,b) return (a.value < b.value) end) return t end local function check(heap) for pos = 2, #heap.values do local parent = math.floor(pos / 2) assert(not heap.lt(heap.values[pos], heap.values[parent])) end if heap.payloads then for pos in ipairs(heap.values) do local payload = heap.payloads[pos] assert(heap.reverse[payload] == pos) end end end local function newheap() -- create a heap with data local heap = bh.minUnique() for _, node in ipairs(data) do heap:insert(node.value,node.payload) check(heap) end -- create a sorted list with data, sorted by 'value' local sorted = {} for k,v in pairs(data) do sorted[k] = v end sort(sorted) -- create a reverse list of the sorted table; returns sorted-index, based on 'value' local sreverse = {} for i,v in ipairs(sorted) do sreverse[v.value] = i end return heap, sorted, sreverse end local function testheap(heap, sorted) while sorted[1] do local value1, payload1 if heap.reverse then -- it is a unique heap payload1, value1 = heap:pop() else -- it is a plain heap value1, payload1 = heap:pop() end local value2, payload2 = sorted[1].value, sorted[1].payload table.remove(sorted, 1) assert.are.equal(payload1, payload2) assert.are.equal(value1, value2) end end describe("[minUnique]", function() it("validates order of insertion", function() local h = newheap() assert.are.equal(h.payloads[1], data[13].payload) assert.are.equal(h.payloads[2], data[11].payload) assert.are.equal(h.payloads[3], data[9].payload) assert.are.equal(h.payloads[4], data[8].payload) assert.are.equal(h.payloads[5], data[2].payload) assert.are.equal(h.payloads[6], data[3].payload) assert.are.equal(h.payloads[7], data[15].payload) assert.are.equal(h.payloads[8], data[1].payload) assert.are.equal(h.payloads[9], data[4].payload) assert.are.equal(h.payloads[10], data[5].payload) assert.are.equal(h.payloads[11], data[10].payload) assert.are.equal(h.payloads[12], data[12].payload) assert.are.equal(h.payloads[13], data[6].payload) assert.are.equal(h.payloads[14], data[14].payload) assert.are.equal(h.payloads[15], data[7].payload) end) it("validates order of popping", function() testheap(newheap()) end) it("peek()", function() local heap, sorted = newheap() local payload, value = heap:peek() -- correct values? assert.are.equal(value, sorted[1].value) assert.are.equal(payload, sorted[1].payload) -- are they still on the heap? assert.are.equal(value, heap.values[1]) assert.are.equal(payload, heap.payloads[1]) end) it("peekValue()", function() local h = bh.minUnique() h:insert(1, 11) assert.equal(1, h:peekValue(11)) -- try again empty h:pop() assert.is_nil(h:peekValue(11)) end) it("pop()", function() local h = bh.minUnique() h:insert(3, 13) h:insert(2, 12) h:insert(1, 11) -- try again empty local pl, v pl, v = h:pop() assert.equal(v, 1) assert.equal(pl, 11) pl, v = h:pop() assert.equal(v, 2) assert.equal(pl, 12) pl, v = h:pop() assert.equal(v, 3) assert.equal(pl, 13) pl, v = h:pop() assert.is_nil(v) assert.is_nil(pl) end) describe("remove()", function() it("a middle item", function() local heap, sorted = newheap() local idx = 4 local value = sorted[idx].value local payload = sorted[idx].payload local v, pl = heap:remove(payload) check(heap) -- did we get the right ones? assert.are.equal(value, v) assert.are.equal(payload, pl) assert.is.Nil(heap[payload]) -- remove from test data and compare table.remove(sorted, idx) testheap(heap, sorted) end) it("the last item (of the array)", function() local heap, sorted = newheap() local idx = #heap.values local value = sorted[idx].value local payload = sorted[idx].payload local v, pl = heap:remove(payload) check(heap) -- did we get the right ones? assert.are.equal(value, v) assert.are.equal(payload, pl) assert.is.Nil(heap.reverse[payload]) -- remove from test data and compare table.remove(sorted, idx) testheap(heap, sorted) end) it("non existing payload returns nil", function() local heap = newheap() local v, pl = heap:remove({}) assert.is_nil(v) assert.is_nil(pl) end) it("nil payload returns nil", function() local heap = newheap() local v, pl = heap:remove(nil) assert.is_nil(v) assert.is_nil(pl) end) it("with repeated values", function() local h = bh.minUnique() h:insert(1, 11) check(h) h:insert(1, 12) check(h) local value, payload value, payload = h:remove(11) check(h) assert.equal(1, value) assert.equal(11, payload) payload, value = h:peek() assert.equal(1, value) assert.equal(12, payload) assert.same({1}, h.values) assert.same({12}, h.payloads) assert.same({[12]=1}, h.reverse) end) end) describe("insert()", function() it("a top item", function() local heap, sorted = newheap() local nvalue = sorted[1].value - 10 local npayload = {} table.insert(sorted, 1, {}) sorted[1].value = nvalue sorted[1].payload = npayload heap:insert(nvalue, npayload) check(heap) testheap(heap, sorted) end) it("a middle item", function() local heap, sorted = newheap() local nvalue = 57 local npayload = {} table.insert(sorted, { value = nvalue, payload = npayload }) sort(sorted) heap:insert(nvalue, npayload) check(heap) testheap(heap, sorted) end) it("a last item", function() local heap, sorted = newheap() local nvalue = sorted[#sorted].value + 10 local npayload = {} table.insert(sorted, {}) sorted[#sorted].value = nvalue sorted[#sorted].payload = npayload heap:insert(nvalue, npayload) check(heap) testheap(heap, sorted) end) it("a nil value throws an error", function() local heap = newheap() assert.has.error(function() heap:insert(nil, "something") end) end) it("a nil payload throws an error", function() local heap = newheap() assert.has.error(function() heap:insert(15, nil) end) end) it("a duplicate payload throws an error", function() local heap = newheap() local value = {} heap:insert(1, value) assert.has.error(function() heap:insert(2, value) end) end) end) describe("update()", function() it("a top item", function() local heap, sorted = newheap() local idx = 1 local payload = sorted[idx].payload local nvalue = sorted[#sorted].value + 1 -- move to end with new value sorted[idx].value = nvalue sort(sorted) heap:update(payload, nvalue) check(heap) testheap(heap, sorted) end) it("a middle item", function() local heap, sorted = newheap() local idx = 4 local payload = sorted[idx].payload local nvalue = sorted[idx].value * 2 sorted[idx].value = nvalue sort(sorted) heap:update(payload, nvalue) check(heap) testheap(heap, sorted) end) it("a last item", function() local heap, sorted = newheap() local idx = #sorted local payload = sorted[idx].payload local nvalue = sorted[1].value - 1 -- move to top with new value sorted[idx].value = nvalue sort(sorted) heap:update(payload, nvalue) check(heap) testheap(heap, sorted) end) it("a nil value throws an error", function() local heap, sorted = newheap() local idx = #sorted local payload = sorted[idx].payload assert.has.error(function() heap:update(payload, nil) end) end) it("an unknown payload throws an error", function() local heap = newheap() assert.has.error(function() heap:update({}, 10) end) end) end) describe("size()", function() it("returns number of elements", function() local h = bh.minUnique() assert.equal(0, h:size()) h:insert(1, -1) assert.equal(1, h:size()) h:insert(2, -2) assert.equal(2, h:size()) h:insert(3, -3) assert.equal(3, h:size()) h:insert(4, -4) assert.equal(4, h:size()) h:insert(5, -5) assert.equal(5, h:size()) h:pop() assert.equal(4, h:size()) h:pop() assert.equal(3, h:size()) h:pop() assert.equal(2, h:size()) h:pop() assert.equal(1, h:size()) h:pop() assert.equal(0, h:size()) end) end) describe("valueByPayload()", function() it("gets value by payload", function() local h = bh.minUnique() h:insert(1, -1) h:insert(2, -2) h:insert(3, -3) h:insert(4, -4) h:insert(5, -5) assert.equal(1, h:valueByPayload((-1))) assert.equal(2, h:valueByPayload((-2))) assert.equal(3, h:valueByPayload((-3))) assert.equal(4, h:valueByPayload((-4))) assert.equal(5, h:valueByPayload((-5))) h:remove(-1) assert.falsy(h:valueByPayload((-1))) end) it("non existing payload returns nil", function() local h = bh.minUnique() h:insert(1, -1) h:insert(2, -2) h:insert(3, -3) h:insert(4, -4) h:insert(5, -5) assert.is_nil(h:valueByPayload({})) end) it("nil payload returns nil", function() local h = bh.minUnique() h:insert(1, -1) h:insert(2, -2) h:insert(3, -3) h:insert(4, -4) h:insert(5, -5) assert.is_nil(h:valueByPayload(nil)) end) end) it("creates minUnique with custom less-than function", function() local h = bh.minUnique(function (a, b) return math.abs(a) < math.abs(b) end) h:insert(1, -1) check(h) h:insert(-2, 2) check(h) h:insert(3, -3) check(h) h:insert(-4, 4) check(h) h:insert(5, -5) check(h) local value, payload payload, value = h:peek() assert.equal(1, value) assert.equal(-1, payload) h:pop() check(h) payload, value = h:peek() assert.equal(-2, value) assert.equal(2, payload) end) end) describe("[maxUnique]", function() it("creates maxUnique with custom less-than function", function() local h = bh.maxUnique(function (a, b) return math.abs(a) > math.abs(b) end) h:insert(1, -1) check(h) h:insert(-2, 2) check(h) h:insert(3, -3) check(h) h:insert(-4, 4) check(h) h:insert(5, -5) check(h) local value, payload payload, value = h:peek() assert.equal(5, value) assert.equal(-5, payload) h:pop() check(h) payload, value = h:peek() assert.equal(-4, value) assert.equal(4, payload) end) end) describe("[minHeap]", function() it("creates minHeap", function() local h = bh.minHeap() check(h) end) describe("insert()", function() it("a number into minHeap", function() local h = bh.minHeap() h:insert(42) check(h) end) it("nil throws an error", function() local h = bh.minHeap() assert.has.error(function() h:insert(nil) end) end) end) describe("remove()", function() it("a position", function() local h = bh.minHeap() h:insert(42) h:insert(43) assert.equal(43, h:remove(2)) check(h) end) it("a bad position returns nil", function() local h = bh.minHeap() h:insert(42) h:insert(43) assert.is_nil(h:remove(0)) assert.is_nil(h:remove(3)) check(h) end) end) describe("size()", function() it("returns number of elements", function() local h = bh.minHeap() assert.equal(0, h:size()) h:insert(1) assert.equal(1, h:size()) h:insert(2) assert.equal(2, h:size()) h:insert(3) assert.equal(3, h:size()) h:insert(4) assert.equal(4, h:size()) h:insert(5) assert.equal(5, h:size()) h:pop() assert.equal(4, h:size()) h:pop() assert.equal(3, h:size()) h:pop() assert.equal(2, h:size()) h:pop() assert.equal(1, h:size()) h:pop() assert.equal(0, h:size()) end) end) describe("peek()", function() it("return nil in empty minHeap", function() local h = bh.minHeap() assert.is_nil(h:peek()) check(h) end) it("minHeap of one element", function() local h = bh.minHeap() h:insert(42) check(h) local value, payload = h:peek() assert.equal(42, value) assert.falsy(payload) end) it("minHeap of two elements", function() local h = bh.minHeap() h:insert(42) check(h) h:insert(1) check(h) local value, payload = h:peek() assert.equal(1, value) assert.falsy(payload) end) it("minHeap of 10 elements", function() local h = bh.minHeap() h:insert(10) h:insert(7) h:insert(1) h:insert(5) h:insert(6) h:insert(9) h:insert(8) h:insert(4) h:insert(2) h:insert(3) check(h) local value, payload = h:peek() assert.equal(1, value) assert.falsy(payload) end) it("removes peek in minHeap of 5 elements", function() local h = bh.minHeap() h:insert(1) h:insert(2) h:insert(3) h:insert(4) h:insert(5) local value value = h:pop() check(h) assert.equal(1, value) value = h:peek() assert.equal(2, value) end) end) describe("update()", function() it("in minHeap of 5 elements (pos 2 -> pos 1)", function() local h = bh.minHeap() h:insert(1) h:insert(2) h:insert(3) h:insert(4) h:insert(5) check(h) h:update(2, -100) check(h) local value = h:peek() assert.equal(-100, value) end) it("in minHeap of 5 elements (pos 1 -> pos 2)", function() local h = bh.minHeap() h:insert(1) h:insert(2) h:insert(3) h:insert(4) h:insert(5) check(h) h:update(1, 100) check(h) local value = h:peek() assert.equal(2, value) end) it("nil throws an error", function() local h = bh.minHeap() h:insert(10) assert.has.error(function() h:update(nil) end) end) it("bad position throws an error", function() local h = bh.minHeap() h:insert(10) assert.has.error(function() h:update(0) end) assert.has.error(function() h:update(2) end) end) end) it("creates minHeap with custom less-than function", function() local h = bh.minHeap(function (a, b) return math.abs(a) < math.abs(b) end) h:insert(1) check(h) h:insert(-2) check(h) h:insert(3) check(h) h:insert(-4) check(h) h:insert(5) check(h) assert.equal(1, h:peek()) h:pop() check(h) assert.equal(-2, h:peek()) end) end) describe("[maxHeap]", function() it("creates maxHeap", function() local h = bh.maxHeap() check(h) end) describe("insert()", function() it("inserts a number into maxHeap", function() local h = bh.maxHeap() h:insert(42) check(h) end) it("nil throws an error", function() local h = bh.maxHeap() assert.has.error(function() h:insert(nil) end) end) end) describe("remove()", function() it("a position", function() local h = bh.maxHeap() h:insert(42) h:insert(43) assert.equal(42, h:remove(2)) check(h) end) it("a bad position returns nil", function() local h = bh.maxHeap() h:insert(42) h:insert(43) assert.is_nil(h:remove(0)) assert.is_nil(h:remove(3)) check(h) end) end) describe("size()", function() it("returns number of elements", function() local h = bh.minHeap() assert.equal(0, h:size()) h:insert(1) assert.equal(1, h:size()) h:insert(2) assert.equal(2, h:size()) h:insert(3) assert.equal(3, h:size()) h:insert(4) assert.equal(4, h:size()) h:insert(5) assert.equal(5, h:size()) h:pop() assert.equal(4, h:size()) h:pop() assert.equal(3, h:size()) h:pop() assert.equal(2, h:size()) h:pop() assert.equal(1, h:size()) h:pop() assert.equal(0, h:size()) end) end) describe("peek()", function() it("return nil in empty maxHeap", function() local h = bh.maxHeap() assert.is_nil(h:peek()) check(h) end) it("maxHeap of one element", function() local h = bh.maxHeap() h:insert(42) check(h) local value = h:peek() assert.equal(42, value) end) it("maxHeap of two elements", function() local h = bh.maxHeap() h:insert(42) check(h) h:insert(1) check(h) local value = h:peek() assert.equal(42, value) end) it("maxHeap of 10 elements", function() local h = bh.maxHeap() h:insert(10) h:insert(7) h:insert(1) h:insert(5) h:insert(6) h:insert(9) h:insert(8) h:insert(4) h:insert(2) h:insert(3) check(h) local value = h:peek() assert.equal(10, value) end) it("removes peek in maxHeap of 5 elements", function() local h = bh.maxHeap() h:insert(1) h:insert(2) h:insert(3) h:insert(4) h:insert(5) check(h) local value value = h:pop() check(h) assert.equal(5, value) value = h:peek() assert.equal(4, value) end) end) describe("update()", function() it("in maxHeap of 5 elements (pos 2 -> pos 1)", function() local h = bh.maxHeap() h:insert(1) h:insert(2) h:insert(3) h:insert(4) h:insert(5) check(h) h:update(2, 100) check(h) local value = h:peek() assert.equal(100, value) end) it("in maxHeap of 5 elements (pos 1 -> pos 2)", function() local h = bh.maxHeap() h:insert(1) h:insert(2) h:insert(3) h:insert(4) h:insert(5) check(h) h:update(1, -100) check(h) local value = h:peek() assert.equal(4, value) end) it("nil throws an error", function() local h = bh.maxHeap() h:insert(10) assert.has.error(function() h:update(nil) end) end) it("bad position throws an error", function() local h = bh.maxHeap() h:insert(10) assert.has.error(function() h:update(0) end) assert.has.error(function() h:update(2) end) end) end) it("creates maxHeap with custom greater-than function", function() local h = bh.maxHeap(function (a, b) return math.abs(a) > math.abs(b) end) h:insert(1) check(h) h:insert(-2) check(h) h:insert(3) check(h) h:insert(-4) check(h) h:insert(5) check(h) assert.equal(5, (h:peek())) h:pop() check(h) assert.equal(-4, (h:peek())) end) end) binaryheap.lua-version_0v4/spec/dijkstras_algorithm_spec.lua000066400000000000000000000046761337061453000246660ustar00rootroot00000000000000describe("dijkstras algorithm with binaryheap", function() -- See https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm it("calculates knight's shortest path", function() -- See http://stackoverflow.com/questions/2339101 local binaryheap = require 'binaryheap' local ROWS = 8 local COLS = 8 local unvisited = binaryheap.minUnique() local function Cell(x, y) return x .. '_' .. y end local function Coordinates(cell) local x, y = cell:match('(%d+)_(%d+)') return x, y end local function neighbours(cell) local x, y = Coordinates(cell) local gen = coroutine.wrap(function() coroutine.yield(x - 1, y - 2) coroutine.yield(x - 1, y + 2) coroutine.yield(x + 1, y - 2) coroutine.yield(x + 1, y + 2) coroutine.yield(x - 2, y - 1) coroutine.yield(x - 2, y + 1) coroutine.yield(x + 2, y - 1) coroutine.yield(x + 2, y + 1) end) return coroutine.wrap(function() for xx, yy in gen do if 1 <= xx and xx <= COLS and 1 <= yy and yy <= ROWS then coroutine.yield(Cell(xx, yy)) end end end) end for y = 1, ROWS do for x = 1, COLS do local cell = Cell(x, y) unvisited:insert(math.huge, cell) end end unvisited:update('1_1', 0) local final_distance = {} while unvisited:peekValue() do local current, current_distance = unvisited:peek() assert(not final_distance[current]) final_distance[current] = current_distance unvisited:remove(current) -- update neighbours local new_distance = current_distance + 1 for neighbour in neighbours(current) do if unvisited.reverse[neighbour] then local pos = unvisited.reverse[neighbour] local distance = unvisited.values[pos] if distance > new_distance then unvisited:update(neighbour, new_distance) end end end end local rows = {} for y = 1, ROWS do local row = {} for x = 1, COLS do local cell = Cell(x, y) local distance = final_distance[cell] table.insert(row, distance) end table.insert(rows, table.concat(row, ' ')) end assert.equal([[ 0 3 2 3 2 3 4 5 3 4 1 2 3 4 3 4 2 1 4 3 2 3 4 5 3 2 3 2 3 4 3 4 2 3 2 3 4 3 4 5 3 4 3 4 3 4 5 4 4 3 4 3 4 5 4 5 5 4 5 4 5 4 5 6]], table.concat(rows, '\n')) end) end) binaryheap.lua-version_0v4/src/000077500000000000000000000000001337061453000167255ustar00rootroot00000000000000binaryheap.lua-version_0v4/src/binaryheap.lua000066400000000000000000000274451337061453000215660ustar00rootroot00000000000000------------------------------------------------------------------- -- Binary heap implementation -- -- A binary heap (or binary tree) is a [sorting algorithm](http://en.wikipedia.org/wiki/Binary_heap). -- -- The 'plain binary heap' is managed by positions. Which are hard to get once -- an element is inserted. It can be anywhere in the list because it is re-sorted -- upon insertion/deletion of items. The array with values is stored in field -- `values`: -- -- `peek = heap.values[1]` -- -- A 'unique binary heap' is where the payload is unique and the payload itself -- also stored (as key) in the heap with the position as value, as in; -- `heap.reverse[payload] = [pos]` -- -- Due to this setup the reverse search, based on payload, is now a -- much faster operation because instead of traversing the list/heap, -- you can do; -- `pos = heap.reverse[payload]` -- -- This means that deleting elements from a 'unique binary heap' is -- faster than from a plain heap. -- -- All management functions in the 'unique binary heap' take `payload` -- instead of `pos` as argument. -- Note that the value of the payload must be unique! -- -- Fields of heap object: -- -- * values - array of values -- * payloads - array of payloads (unique binary heap only) -- * reverse - map from payloads to indices (unique binary heap only) local M = {} local floor = math.floor --================================================================ -- basic heap sorting algorithm --================================================================ --- Basic heap. -- This is the base implementation of the heap. Under regular circumstances -- this should not be used, instead use a _Plain heap_ or _Unique heap_. -- @section baseheap --- Creates a new binary heap. -- This is the core of all heaps, the others -- are built upon these sorting functions. -- @param swap (function) `swap(heap, idx1, idx2)` swaps values at -- `idx1` and `idx2` in the heaps `heap.values` and `heap.payloads` lists (see -- return value below). -- @param erase (function) `swap(heap, position)` raw removal -- @param lt (function) in `lt(a, b)` returns `true` when `a < b` (for a min-heap) -- @return table with two methods; `heap:bubbleUp(pos)` and `heap:sinkDown(pos)` -- that implement the sorting algorithm and two fields; `heap.values` and -- `heap.payloads` being lists, holding the values and payloads respectively. M.binaryHeap = function(swap, erase, lt) local heap = { values = {}, -- list containing values erase = erase, swap = swap, lt = lt, } function heap:bubbleUp(pos) local values = self.values while pos>1 do local parent = floor(pos/2) if not lt(values[pos], values[parent]) then break end swap(self, parent, pos) pos = parent end end function heap:sinkDown(pos) local values = self.values local last = #values while true do local min = pos local child = 2 * pos for c = child, child + 1 do if c <= last and lt(values[c], values[min]) then min = c end end if min == pos then break end swap(self, pos, min) pos = min end end return heap end --================================================================ -- plain heap management functions --================================================================ --- Plain heap. -- A plain heap carries a single piece of information per entry. This can be -- any type (except `nil`), as long as the comparison function used to create -- the heap can handle it. -- @section plainheap do end -- luacheck: ignore -- the above is to trick ldoc (otherwise `update` below disappears) local update --- Updates the value of an element in the heap. -- @function heap:update -- @param pos the position which value to update -- @param newValue the new value to use for this payload update = function(self, pos, newValue) assert(newValue ~= nil, "cannot add 'nil' as value") assert(pos >= 1 and pos <= #self.values, "illegal position") self.values[pos] = newValue if pos > 1 then self:bubbleUp(pos) end if pos < #self.values then self:sinkDown(pos) end end local remove --- Removes an element from the heap. -- @function heap:remove -- @param pos the position to remove -- @return value, or nil if a bad `pos` value was provided remove = function(self, pos) local last = #self.values if pos < 1 then return -- bad pos elseif pos < last then local v = self.values[pos] self:swap(pos, last) self:erase(last) self:bubbleUp(pos) self:sinkDown(pos) return v elseif pos == last then local v = self.values[pos] self:erase(last) return v else return -- bad pos: pos > last end end local insert --- Inserts an element in the heap. -- @function heap:insert -- @param value the value used for sorting this element -- @return nothing, or throws an error on bad input insert = function(self, value) assert(value ~= nil, "cannot add 'nil' as value") local pos = #self.values + 1 self.values[pos] = value self:bubbleUp(pos) end local pop --- Removes the top of the heap and returns it. -- @function heap:pop -- @return value at the top, or `nil` if there is none pop = function(self) if self.values[1] ~= nil then return remove(self, 1) end end local peek --- Returns the element at the top of the heap, without removing it. -- @function heap:peek -- @return value at the top, or `nil` if there is none peek = function(self) return self.values[1] end local size --- Returns the number of elements in the heap. -- @function heap:size -- @return number of elements size = function(self) return #self.values end local function swap(heap, a, b) heap.values[a], heap.values[b] = heap.values[b], heap.values[a] end local function erase(heap, pos) heap.values[pos] = nil end --================================================================ -- plain heap creation --================================================================ local function plainHeap(lt) local h = M.binaryHeap(swap, erase, lt) h.peek = peek h.pop = pop h.size = size h.remove = remove h.insert = insert h.update = update return h end --- Creates a new min-heap, where the smallest value is at the top. -- @param lt (optional) comparison function (less-than), see `binaryHeap`. -- @return the new heap M.minHeap = function(lt) if not lt then lt = function(a,b) return (a < b) end end return plainHeap(lt) end --- Creates a new max-heap, where the largest value is at the top. -- @param gt (optional) comparison function (greater-than), see `binaryHeap`. -- @return the new heap M.maxHeap = function(gt) if not gt then gt = function(a,b) return (a > b) end end return plainHeap(gt) end --================================================================ -- unique heap management functions --================================================================ --- Unique heap. -- A unique heap carries 2 pieces of information per entry. -- -- 1. The `value`, this is used for ordering the heap. It can be any type (except -- `nil`), as long as the comparison function used to create the heap can -- handle it. -- 2. The `payload`, this can be any type (except `nil`), but it MUST be unique. -- -- With the 'unique heap' it is easier to remove elements from the heap. -- @section uniqueheap do end -- luacheck: ignore -- the above is to trick ldoc (otherwise `update` below disappears) local updateU --- Updates the value of an element in the heap. -- @function unique:update -- @param payload the payoad whose value to update -- @param newValue the new value to use for this payload -- @return nothing, or throws an error on bad input function updateU(self, payload, newValue) return update(self, self.reverse[payload], newValue) end local insertU --- Inserts an element in the heap. -- @function unique:insert -- @param value the value used for sorting this element -- @param payload the payload attached to this element -- @return nothing, or throws an error on bad input function insertU(self, value, payload) assert(self.reverse[payload] == nil, "duplicate payload") local pos = #self.values + 1 self.reverse[payload] = pos self.payloads[pos] = payload return insert(self, value) end local removeU --- Removes an element from the heap. -- @function unique:remove -- @param payload the payload to remove -- @return value, payload or nil if not found function removeU(self, payload) local pos = self.reverse[payload] if pos ~= nil then return remove(self, pos), payload end end local popU --- Removes the top of the heap and returns it. -- When used with timers, `pop` will return the payload that is due. -- -- Note: this function returns `payload` as the first result to prevent -- extra locals when retrieving the `payload`. -- @function unique:pop -- @return payload, value, or `nil` if there is none function popU(self) if self.values[1] then local payload = self.payloads[1] local value = remove(self, 1) return payload, value end end local peekU --- Returns the element at the top of the heap, without removing it. -- @function unique:peek -- @return payload, value, or `nil` if there is none peekU = function(self) return self.payloads[1], self.values[1] end local peekValueU --- Returns the element at the top of the heap, without removing it. -- @function unique:peekValue -- @return value at the top, or `nil` if there is none -- @usage -- simple timer based heap example -- while true do -- sleep(heap:peekValue() - gettime()) -- assume LuaSocket gettime function -- coroutine.resume((heap:pop())) -- assumes payload to be a coroutine, -- -- double parens to drop extra return value -- end peekValueU = function(self) return self.values[1] end local valueByPayload --- Returns the value associated with the payload -- @function unique:valueByPayload -- @param payload the payload to lookup -- @return value or nil if no such payload exists valueByPayload = function(self, payload) return self.values[self.reverse[payload]] end local sizeU --- Returns the number of elements in the heap. -- @function heap:size -- @return number of elements sizeU = function(self) return #self.values end local function swapU(heap, a, b) local pla, plb = heap.payloads[a], heap.payloads[b] heap.reverse[pla], heap.reverse[plb] = b, a heap.payloads[a], heap.payloads[b] = plb, pla swap(heap, a, b) end local function eraseU(heap, pos) local payload = heap.payloads[pos] heap.reverse[payload] = nil heap.payloads[pos] = nil erase(heap, pos) end --================================================================ -- unique heap creation --================================================================ local function uniqueHeap(lt) local h = M.binaryHeap(swapU, eraseU, lt) h.payloads = {} -- list contains payloads h.reverse = {} -- reverse of the payloads list h.peek = peekU h.peekValue = peekValueU h.valueByPayload = valueByPayload h.pop = popU h.size = sizeU h.remove = removeU h.insert = insertU h.update = updateU return h end --- Creates a new min-heap with unique payloads. -- A min-heap is where the smallest value is at the top. -- -- *NOTE*: All management functions in the 'unique binary heap' -- take `payload` instead of `pos` as argument. -- @param lt (optional) comparison function (less-than), see `binaryHeap`. -- @return the new heap M.minUnique = function(lt) if not lt then lt = function(a,b) return (a < b) end end return uniqueHeap(lt) end --- Creates a new max-heap with unique payloads. -- A max-heap is where the largest value is at the top. -- -- *NOTE*: All management functions in the 'unique binary heap' -- take `payload` instead of `pos` as argument. -- @param gt (optional) comparison function (greater-than), see `binaryHeap`. -- @return the new heap M.maxUnique = function(gt) if not gt then gt = function(a,b) return (a > b) end end return uniqueHeap(gt) end return M