-
Notifications
You must be signed in to change notification settings - Fork 9
feat: Add PriorityQueue #392
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
Merged
Merged
Changes from all commits
Commits
Show all changes
25 commits
Select commit
Hold shift + click to select a range
5984fc0
Partial implementation.
0eb4b27
Fix bug and add peek.
da8404b
Started with tests, and more functions.
99dda56
Towards more tests, adding SetPriorityQueue.
e8914ee
Completing first implementation, with tests.
f4372c1
Add comments to PriorityQueue.mo
de65817
Move set implementation and add benchmark.
7eae3b3
Better holes.
dc9ff20
Extra benchmark.
52961ac
More tests.
319951a
.
267cfe9
Comments.
f6a4353
Optimization.
5d7fd0e
Comments for SetWrapper.
cd260ab
Move SetWrapper.
59df102
Run format.
c1233e4
.
a0d3a1d
npm run validate
435fc31
Fix imports in docstrings.
665c8c4
Add Changelog entry.
95f5223
Fix Changelog entry.
664d092
Remove inefficient push and pop operations (and benchmarks for them).
153895f
Move PriorityQueueSet.mo
f19cf41
Fix validation.
e912dfd
Update Changelog.
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,226 @@ | ||
| import Bench "mo:bench"; | ||
|
|
||
| import Array "../src/Array"; | ||
| import Nat "../src/Nat"; | ||
| import PriorityQueue "../src/PriorityQueue"; | ||
| import PriorityQueueSet "utils/PriorityQueueSet"; | ||
| import Random "../src/Random"; | ||
| import Runtime "../src/Runtime"; | ||
| import Map "../src/Map"; | ||
| import Text "../src/Text"; | ||
|
|
||
| module { | ||
|
|
||
| type PriorityQueueUpdateOperation<T> = { | ||
| #Push : T; | ||
| #Pop; | ||
| #Clear | ||
| }; | ||
|
|
||
| // Generates a randomized sequence of PriorityQueueUpdateOperations on Nat values. | ||
| // The distribution of operations is controlled by weights. | ||
| // | ||
| // randomSeed - seed for reproducible RNG | ||
| // operationsCount – total number of operations to generate | ||
| // maxValueExclusive – upper bound (exclusive) for values pushed into the queue | ||
| // wPush – relative weight of #Push operations (values in [0, maxValueExclusive)) | ||
| // wPop – relative weight of #Pop operations | ||
| // wClear – relative weight of #Clear operations | ||
| func genOpsNatRandom( | ||
| randomSeed : Nat64, | ||
| operationsCount : Nat, | ||
| maxValueExclusive : Nat, | ||
| wPush : Nat, | ||
| wPop : Nat, | ||
| wClear : Nat | ||
| ) : [PriorityQueueUpdateOperation<Nat>] { | ||
| let rng = Random.seed(randomSeed); | ||
| Array.tabulate<PriorityQueueUpdateOperation<Nat>>( | ||
| operationsCount, | ||
| func(_) { | ||
| let aux = rng.natRange(0, wPush + wPop + wClear); | ||
| if (aux < wPush) { | ||
| #Push(rng.natRange(0, maxValueExclusive)) | ||
| } else if (aux < wPush + wPop) { | ||
| #Pop | ||
| } else { | ||
| #Clear | ||
| } | ||
| } | ||
| ) | ||
| }; | ||
|
|
||
| // Generates a sequence of PriorityQueueUpdateOperations on Nat values: | ||
| // 1. pushOperationsCount pushes, followed by | ||
| // 2. pushOperationsCount pops. | ||
| // | ||
| // randomSeed - seed for reproducible RNG | ||
| // pushOperationsCount – total number of push operations to generate | ||
| // maxValueExclusive – upper bound (exclusive) for values pushed into the queue | ||
| func genOpsPushThenPop( | ||
| randomSeed : Nat64, | ||
| pushOperationsCount : Nat, | ||
| maxValueExclusive : Nat | ||
| ) : [PriorityQueueUpdateOperation<Nat>] { | ||
| let rng = Random.seed(randomSeed); | ||
| Array.tabulate<PriorityQueueUpdateOperation<Nat>>( | ||
| 2 * pushOperationsCount, | ||
| func(i) { | ||
| switch (i < pushOperationsCount) { | ||
| case true #Push(rng.natRange(0, maxValueExclusive)); | ||
| case false #Pop | ||
| } | ||
| } | ||
| ) | ||
| }; | ||
|
|
||
| // Generates a sequence of PriorityQueueUpdateOperations on Nat values: | ||
| // 1. size pushes, followed by | ||
| // 2. popPushCount instances of a pop followed by a push. | ||
| // | ||
| // randomSeed - seed for reproducible RNG | ||
| // size – initial size | ||
| // popPushCount - number of times to pop and then push | ||
| // maxValueExclusive – upper bound (exclusive) for values pushed into the queue | ||
| func genOpsKeepConstantSize( | ||
| randomSeed : Nat64, | ||
| size : Nat, | ||
| popPushCount : Nat, | ||
| maxValueExclusive : Nat | ||
| ) : [PriorityQueueUpdateOperation<Nat>] { | ||
| let rng = Random.seed(randomSeed); | ||
| Array.tabulate<PriorityQueueUpdateOperation<Nat>>( | ||
| size + 2 * popPushCount, | ||
| func(i) { | ||
| if (i < size or (i - size) % 2 == 1) { | ||
| #Push(rng.natRange(0, maxValueExclusive)) | ||
| } else { | ||
| #Pop | ||
| } | ||
| } | ||
| ) | ||
| }; | ||
|
|
||
| public func init() : Bench.Bench { | ||
| let bench = Bench.Bench(); | ||
|
|
||
| bench.name("Different priority queue implementations"); | ||
| bench.description("Compare the performance of the following priority queue implementations: | ||
| - `PriorityQueue`: Binary heap implementation over `List`. | ||
| - `PriorityQueueSet`: Wrapper over `Set<(T, Nat)>`."); | ||
|
|
||
| let testInstances : Map.Map<Text, [PriorityQueueUpdateOperation<Nat>]> = Map.fromIter( | ||
| [ | ||
| ( | ||
| "1.) 100000 operations (push:pop = 1:1)", | ||
| genOpsNatRandom( | ||
| /* randomSeed = */ 23, | ||
| /* operationsCount = */ 100000, | ||
| /* maxValueExclusive = */ 100000, | ||
| /* wPush = */ 1, | ||
| /* wPop = */ 1, | ||
| /* wClear = */ 0 | ||
| ) | ||
| ), | ||
| ( | ||
| "2.) 100000 operations (push:pop = 2:1)", | ||
| genOpsNatRandom( | ||
| /* randomSeed = */ 24, | ||
| /* operationsCount = */ 100000, | ||
| /* maxValueExclusive = */ 100000, | ||
| /* wPush = */ 2, | ||
| /* wPop = */ 1, | ||
| /* wClear = */ 0 | ||
| ) | ||
| ), | ||
| ( | ||
| "3.) 100000 operations (push:pop = 10:1)", | ||
| genOpsNatRandom( | ||
| /* randomSeed = */ 42, | ||
| /* operationsCount = */ 100000, | ||
| /* maxValueExclusive = */ 100000, | ||
| /* wPush = */ 10, | ||
| /* wPop = */ 1, | ||
| /* wClear = */ 0 | ||
| ) | ||
| ), | ||
| ( | ||
| "4.) 100000 operations (only push)", | ||
| genOpsNatRandom( | ||
| /* randomSeed = */ 33, | ||
| /* operationsCount = */ 100000, | ||
| /* maxValueExclusive = */ 100000, | ||
| /* wPush = */ 1, | ||
| /* wPop = */ 0, | ||
| /* wClear = */ 0 | ||
| ) | ||
| ), | ||
| ( | ||
| "5.) 50000 pushes, then 50000 pops", | ||
| genOpsPushThenPop( | ||
| /* randomSeed = */ 13, | ||
| /* pushOperationsCount = */ 50000, | ||
| /* maxValueExclusive */ 100000 | ||
| ) | ||
| ), | ||
| ( | ||
| "6.) 50000 pushes, then 25000 \"pop;push\"es", | ||
| genOpsKeepConstantSize( | ||
| /* randomSeed = */ 55, | ||
| /* size = */ 50000, | ||
| /* popPushCount = */ 25000, | ||
| /* maxValueExclusive = */ 100000 | ||
| ) | ||
| ) | ||
| ].values(), | ||
| Text.compare | ||
| ); | ||
| bench.rows(Map.keys<Text, [PriorityQueueUpdateOperation<Nat>]>(testInstances) |> Array.fromIter(_)); | ||
|
|
||
| let testRunners : Map.Map<Text, [PriorityQueueUpdateOperation<Nat>] -> ()> = Map.fromIter( | ||
| [ | ||
| ( | ||
| "A) PriorityQueue", | ||
| func(ops : [PriorityQueueUpdateOperation<Nat>]) { | ||
| let priorityQueue = PriorityQueue.empty<Nat>(); | ||
| for (op in ops.values()) { | ||
| switch (op) { | ||
| case (#Push element) PriorityQueue.push(priorityQueue, Nat.compare, element); | ||
| case (#Pop) ignore PriorityQueue.pop(priorityQueue, Nat.compare); | ||
| case (#Clear) PriorityQueue.clear(priorityQueue) | ||
| } | ||
| } | ||
| } | ||
| ), | ||
| ( | ||
| "B) PriorityQueueSet", | ||
| func(ops : [PriorityQueueUpdateOperation<Nat>]) { | ||
| let priorityQueueSet = PriorityQueueSet.empty<Nat>(); | ||
| for (op in ops.values()) { | ||
| switch (op) { | ||
| case (#Push element) PriorityQueueSet.push(priorityQueueSet, Nat.compare, element); | ||
| case (#Pop) ignore PriorityQueueSet.pop(priorityQueueSet, Nat.compare); | ||
| case (#Clear) PriorityQueueSet.clear(priorityQueueSet) | ||
| } | ||
| } | ||
| } | ||
| ) | ||
| ].values(), | ||
| Text.compare | ||
| ); | ||
| bench.cols(Map.keys<Text, [PriorityQueueUpdateOperation<Nat>] -> ()>(testRunners) |> Array.fromIter(_)); | ||
|
|
||
| bench.runner( | ||
| func(row, col) { | ||
| switch ( | ||
| Map.get(testInstances, Text.compare, row), | ||
| Map.get(testRunners, Text.compare, col) | ||
| ) { | ||
| case (?ops, ?runner) runner(ops); | ||
| case _ Runtime.trap("Missing test instance or runner") | ||
| } | ||
| } | ||
| ); | ||
| bench | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,159 @@ | ||
| /// A mutable priority queue of elements. | ||
| /// !!! In contrast to the implementation in `src/PriorityQueue.mo`, this one | ||
| /// is a wrapper over `Set`. !!! | ||
| /// | ||
| /// Always returns the element with the highest priority first, | ||
| /// as determined by a user-provided comparison function. | ||
| /// | ||
| /// Internally implemented as a wrapper over a core library `Set<(T, Nat)>`. | ||
| /// The `Nat` values serve as unique tags to distinguish elements | ||
| /// with equal priority, since a `Set` cannot store duplicates. | ||
| /// | ||
| /// Performance: | ||
| /// * Runtime: `O(log n)` for `push`, `pop` and `peek`. | ||
| /// * Runtime: `O(1)` for `clear`, `size`, and `isEmpty`. | ||
| /// * Space: `O(n)`, where `n` is the number of stored elements. | ||
| import Set "../../src/Set"; | ||
| import Order "../../src/Order"; | ||
| import Nat "../../src/Nat"; | ||
| import { Tuple2 } "../../src/Tuples"; | ||
|
|
||
| module { | ||
| public type PriorityQueue<T> = { | ||
| set : Set.Set<(T, Nat)>; | ||
| var counter : Nat | ||
| }; | ||
|
|
||
| /// Returns an empty priority queue. | ||
| /// | ||
| /// Example: | ||
| /// ```motoko | ||
| /// import PriorityQueue "mo:core/internal/PriorityQueueSet"; | ||
| /// | ||
| /// let pq = PriorityQueue.empty<Nat>(); | ||
| /// assert PriorityQueue.isEmpty(pq); | ||
| /// ``` | ||
| /// | ||
| /// Runtime: `O(1)`. Space: `O(1)`. | ||
| public func empty<T>() : PriorityQueue<T> = { | ||
| set = Set.empty<(T, Nat)>(); | ||
| var counter = 0 | ||
| }; | ||
|
|
||
| /// Returns a priority queue containing a single element. | ||
| /// | ||
| /// Example: | ||
| /// ```motoko | ||
| /// import PriorityQueue "mo:core/internal/PriorityQueueSet"; | ||
| /// | ||
| /// let pq = PriorityQueue.singleton<Nat>(42); | ||
| /// assert PriorityQueue.peek(pq) == ?42; | ||
| /// ``` | ||
| /// | ||
| /// Runtime: `O(1)`. Space: `O(1)`. | ||
| public func singleton<T>(element : T) : PriorityQueue<T> = { | ||
| set = Set.singleton((element, 0)); | ||
| var counter = 1 | ||
| }; | ||
|
|
||
| /// Returns the number of elements in the priority queue. | ||
| /// | ||
| /// Runtime: `O(1)`. | ||
| public func size<T>(priorityQueue : PriorityQueue<T>) : Nat = Set.size(priorityQueue.set); | ||
|
|
||
| /// Returns `true` iff the priority queue is empty. | ||
| /// | ||
| /// Example: | ||
| /// ```motoko | ||
| /// import PriorityQueue "mo:core/internal/PriorityQueueSet"; | ||
| /// import Nat "mo:core/Nat"; | ||
| /// | ||
| /// let pq = PriorityQueue.empty<Nat>(); | ||
| /// assert PriorityQueue.isEmpty(pq); | ||
| /// PriorityQueue.push(pq, Nat.compare, 5); | ||
| /// assert not PriorityQueue.isEmpty(pq); | ||
| /// ``` | ||
| /// | ||
| /// Runtime: `O(1)`. Space: `O(1)`. | ||
| public func isEmpty<T>(priorityQueue : PriorityQueue<T>) : Bool = Set.isEmpty(priorityQueue.set); | ||
|
|
||
| /// Removes all elements from the priority queue. | ||
| /// | ||
| /// Example: | ||
| /// ```motoko | ||
| /// import PriorityQueue "mo:core/internal/PriorityQueueSet"; | ||
| /// import Nat "mo:core/Nat"; | ||
| /// | ||
| /// let pq = PriorityQueue.empty<Nat>(); | ||
| /// PriorityQueue.push(pq, Nat.compare, 5); | ||
| /// PriorityQueue.push(pq, Nat.compare, 10); | ||
| /// assert not PriorityQueue.isEmpty(pq); | ||
| /// PriorityQueue.clear(pq); | ||
| /// assert PriorityQueue.isEmpty(pq); | ||
| /// ``` | ||
| /// | ||
| /// Runtime: `O(1)`. Space: `O(1)`. | ||
| public func clear<T>(priorityQueue : PriorityQueue<T>) = Set.clear(priorityQueue.set); | ||
|
|
||
| /// Inserts a new element into the priority queue. | ||
| /// | ||
| /// `compare` – comparison function that defines priority ordering. | ||
| /// | ||
| /// Example: | ||
| /// ```motoko | ||
| /// import PriorityQueue "mo:core/internal/PriorityQueueSet"; | ||
| /// import Nat "mo:core/Nat"; | ||
| /// | ||
| /// let pq = PriorityQueue.empty<Nat>(); | ||
| /// PriorityQueue.push(pq, Nat.compare, 5); | ||
| /// PriorityQueue.push(pq, Nat.compare, 10); | ||
| /// assert PriorityQueue.peek(pq) == ?10; | ||
| /// ``` | ||
| /// | ||
| /// Runtime: `O(log n)`. Space: `O(log n)`. | ||
| public func push<T>(priorityQueue : PriorityQueue<T>, compare : (T, T) -> Order.Order, element : T) { | ||
| Set.add(priorityQueue.set, Tuple2.makeCompare(compare, Nat.compare), (element, priorityQueue.counter)); | ||
| priorityQueue.counter += 1 | ||
| }; | ||
|
|
||
| /// Returns the element with the highest priority, without removing it. | ||
| /// Returns `null` if the queue is empty. | ||
| /// | ||
| /// Example: | ||
| /// ```motoko | ||
| /// import PriorityQueue "mo:core/internal/PriorityQueueSet"; | ||
| /// import Nat "mo:core/Nat"; | ||
| /// | ||
| /// let pq = PriorityQueue.singleton<Nat>(42); | ||
| /// assert PriorityQueue.peek(pq) == ?42; | ||
| /// ``` | ||
| /// | ||
| /// Runtime: `O(log n)`. Space: `O(1)`. | ||
| public func peek<T>(priorityQueue : PriorityQueue<T>) : ?T = do ? { | ||
| let (element, _) = Set.max(priorityQueue.set)!; | ||
| element | ||
| }; | ||
|
|
||
| /// Removes and returns the element with the highest priority. | ||
| /// Returns `null` if the queue is empty. | ||
| /// | ||
| /// `compare` – comparison function that defines priority ordering. | ||
| /// | ||
| /// Example: | ||
| /// ```motoko | ||
| /// import PriorityQueue "mo:core/internal/PriorityQueueSet"; | ||
| /// import Nat "mo:core/Nat"; | ||
| /// | ||
| /// let pq = PriorityQueue.empty<Nat>(); | ||
| /// PriorityQueue.push(pq, Nat.compare, 5); | ||
| /// PriorityQueue.push(pq, Nat.compare, 10); | ||
| /// assert PriorityQueue.pop(pq, Nat.compare) == ?10; | ||
| /// ``` | ||
| /// | ||
| /// Runtime: `O(log n)`. Space: `O(log n)`. | ||
| public func pop<T>(priorityQueue : PriorityQueue<T>, compare : (T, T) -> Order.Order) : ?T = do ? { | ||
| let (element, nonce) = Set.max(priorityQueue.set)!; | ||
| Set.remove(priorityQueue.set, Tuple2.makeCompare(compare, Nat.compare), (element, nonce)); | ||
| element | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.