Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

heapqueue.nim: Add toHeapQueue proc #15459

Merged
merged 2 commits into from
Oct 2, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,10 @@

- Add `readLines(p: Process)` to `osproc` module for `startProcess` convenience.

- Added `heapqueue.toHeapQueue`, which creates a HeapQueue from an openArray.
The usage is similar to procs such as `sets.toHashSet` and `tables.toTable`.
Previously, it was necessary to create an empty HeapQueue and add items
manually.
- Added `intsets.toIntSet`, which creates an IntSet from an openArray. The usage
is similar to procs such as `sets.toHashSet` and `tables.toTable`. Previously,
it was necessary to create an empty IntSet and add items manually.
Expand Down
18 changes: 18 additions & 0 deletions lib/pure/collections/heapqueue.nim
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ type HeapQueue*[T] = object

proc initHeapQueue*[T](): HeapQueue[T] =
## Create a new empty heap.
##
## See also:
## * `toHeapQueue proc <#toHeapQueue,openArray[T]>`_
discard

proc len*[T](heap: HeapQueue[T]): int {.inline.} =
Expand Down Expand Up @@ -115,6 +118,20 @@ proc push*[T](heap: var HeapQueue[T], item: T) =
heap.data.add(item)
siftdown(heap, 0, len(heap)-1)

proc toHeapQueue*[T](x: openArray[T]): HeapQueue[T] {.since: (1, 3).} =
## Creates a new HeapQueue that contains the elements of `x`.
##
## See also:
## * `initHeapQueue proc <#initHeapQueue>`_
runnableExamples:
var heap = toHeapQueue([9, 5, 8])
assert heap.pop() == 5
assert heap[0] == 8

result = initHeapQueue[T]()
for item in items(x):
result.push(item)

proc pop*[T](heap: var HeapQueue[T]): T =
## Pop and return the smallest item from `heap`,
## maintaining the heap invariant.
Expand Down Expand Up @@ -195,6 +212,7 @@ when isMainModule:
let data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
for item in data:
push(heap, item)
doAssert(heap == data.toHeapQueue)
doAssert(heap[0] == 0)
doAssert(heap.toSortedSeq == @[0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

Expand Down