Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/lucidfrontier45/heapq
Priority Queue with scoring function
https://github.com/lucidfrontier45/heapq
data-structures queue rust
Last synced: about 4 hours ago
JSON representation
Priority Queue with scoring function
- Host: GitHub
- URL: https://github.com/lucidfrontier45/heapq
- Owner: lucidfrontier45
- License: mit
- Created: 2023-10-23T22:40:56.000Z (about 1 year ago)
- Default Branch: main
- Last Pushed: 2023-10-24T01:45:29.000Z (about 1 year ago)
- Last Synced: 2024-04-24T19:02:22.224Z (7 months ago)
- Topics: data-structures, queue, rust
- Language: Rust
- Homepage: https://crates.io/crates/heapq
- Size: 5.86 KB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Heapq
Priority Queue with scoring function# Usage
```toml
[dependencies]
heapq = "0.1.0"
```In the code you first need to create an instance with `heaqp::PriorityQueue::new`. It takes a closure that converts your item type `&T` into score type `S: Ord`. Then you can use `push/pop/peek` methods in the same way as `std::collections::BinaryHeap`.
# Example
```rust
use std::cmp::Reverse;use heapq::PriorityQueue;
fn main() {
// a score function that returns the length of a string
let score_fn = |s: &String| s.len();
// create a new priority queue with the score function
let mut queue = PriorityQueue::new(score_fn);// the queue is empty at the beginning
assert!(queue.peek().is_none());// push some items into the queue
// the score function is used to calculate the score of each item
queue.push("a".to_string()); // score = 1
queue.push("ccc".to_string()); // score = 3
queue.push("bb".to_string()); // score = 2// you can also push an item with a explicit score
queue.push_with_score("b".to_string(), 10); // score = 10// peek the item with the highest priority
assert_eq!(queue.peek(), Some(&"b".to_string()));// pop the item with the highest priority
assert_eq!(queue.pop(), Some("b".to_string()));
assert_eq!(queue.pop(), Some("ccc".to_string()));
assert_eq!(queue.pop(), Some("bb".to_string()));
assert_eq!(queue.pop(), Some("a".to_string()));// the queue is empty again
assert!(queue.peek().is_none());// you can also use a reverse order
let score_fn = |s: &String| Reverse(s.len());
let mut queue = PriorityQueue::new(score_fn);queue.push("a".to_string()); // score = -1
queue.push("ccc".to_string()); // score = -3
queue.push("bb".to_string()); // score = -2// remember to use Reverse when pushing an item with a explicit score
queue.push_with_score("b".to_string(), Reverse(10)); // score = -10assert_eq!(queue.peek(), Some(&"a".to_string()));
assert_eq!(queue.pop(), Some("a".to_string()));
assert_eq!(queue.pop(), Some("bb".to_string()));
assert_eq!(queue.pop(), Some("ccc".to_string()));
assert_eq!(queue.pop(), Some("b".to_string()));
assert!(queue.peek().is_none());
}
```