mirror of
https://github.com/nim-lang/Nim.git
synced 2026-04-21 14:55:24 +00:00
heapqueue.nim: Add toHeapQueue proc (#15459)
Similar to: - `critbits.toCritBitTree` - `deques.toDeque` - `sets.toHashSet` - `tables.toTable` Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
This commit is contained in:
@@ -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.
|
||||
|
||||
@@ -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.} =
|
||||
@@ -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.
|
||||
@@ -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])
|
||||
|
||||
|
||||
Reference in New Issue
Block a user