diff options
author | ee7 <45465154+ee7@users.noreply.github.com> | 2020-10-02 22:01:03 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-10-02 16:01:03 -0400 |
commit | 0a05176057dd0f98793b41e18f5599d662ab1672 (patch) | |
tree | 7a3dbbe9e26f20630620fd2306e921b380a8acf3 | |
parent | d48b356e493a7a7f6e2cf9855de893f811b2e9ad (diff) | |
download | Nim-0a05176057dd0f98793b41e18f5599d662ab1672.tar.gz |
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>
-rw-r--r-- | changelog.md | 4 | ||||
-rw-r--r-- | lib/pure/collections/heapqueue.nim | 18 |
2 files changed, 22 insertions, 0 deletions
diff --git a/changelog.md b/changelog.md index 7d1217f97..5a439285c 100644 --- a/changelog.md +++ b/changelog.md @@ -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. diff --git a/lib/pure/collections/heapqueue.nim b/lib/pure/collections/heapqueue.nim index c2952cf1b..ca0666651 100644 --- a/lib/pure/collections/heapqueue.nim +++ b/lib/pure/collections/heapqueue.nim @@ -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]) |