Skip to content

Commit 77adaa9

Browse files
committed
more maneatingape code
1 parent 36f9406 commit 77adaa9

File tree

2 files changed

+66
-1
lines changed

2 files changed

+66
-1
lines changed

src/maneatingape/heap.rs

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
// source: // source: https://github.com/maneatingape/advent-of-code-rust/blob/2f5d0220ea44f33545f741e307d4481b50d632c7/src/util/heap.rs
2+
3+
//! [Min heap] more suitable for algorithms such as [Dijkstra] and [A*] than Rust's default
4+
//! max heap. Splits the sorting key and value, so that you can order items without having
5+
//! to implement [`Ord`] on the value type.
6+
//!
7+
//! [Min heap]: https://en.wikipedia.org/wiki/Heap_(data_structure)
8+
//! [Dijkstra]: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
9+
//! [A*]: https://en.wikipedia.org/wiki/A*_search_algorithm
10+
use std::cmp::Ordering;
11+
use std::collections::BinaryHeap;
12+
13+
struct Wrapper<K: Ord, V> {
14+
key: K,
15+
value: V,
16+
}
17+
18+
impl<K: Ord, V> PartialEq for Wrapper<K, V> {
19+
#[inline]
20+
fn eq(&self, other: &Self) -> bool {
21+
self.key == other.key
22+
}
23+
}
24+
25+
impl<K: Ord, V> Eq for Wrapper<K, V> {}
26+
27+
impl<K: Ord, V> PartialOrd for Wrapper<K, V> {
28+
#[inline]
29+
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
30+
Some(self.cmp(other))
31+
}
32+
}
33+
34+
impl<K: Ord, V> Ord for Wrapper<K, V> {
35+
#[inline]
36+
fn cmp(&self, other: &Self) -> Ordering {
37+
other.key.cmp(&self.key)
38+
}
39+
}
40+
41+
#[derive(Default)]
42+
pub struct MinHeap<K: Ord, V> {
43+
heap: BinaryHeap<Wrapper<K, V>>,
44+
}
45+
46+
impl<K: Ord, V> MinHeap<K, V> {
47+
pub fn new() -> Self {
48+
MinHeap { heap: BinaryHeap::new() }
49+
}
50+
51+
pub fn with_capacity(capacity: usize) -> Self {
52+
MinHeap { heap: BinaryHeap::with_capacity(capacity) }
53+
}
54+
55+
#[inline]
56+
pub fn push(&mut self, key: K, value: V) {
57+
self.heap.push(Wrapper { key, value });
58+
}
59+
60+
#[inline]
61+
pub fn pop(&mut self) -> Option<(K, V)> {
62+
self.heap.pop().map(|w| (w.key, w.value))
63+
}
64+
}

src/maneatingape/mod.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
pub mod hash;
2+
pub mod heap;
23
pub mod integer;
34
pub mod iter;
45
pub mod math;
5-
pub mod parse;
6+
pub mod parse;

0 commit comments

Comments
 (0)