tree-experiments 0.1.0

Experiments with tree-like data structures
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
// SPDX-FileCopyrightText: 2023 Markus Mayer
// SPDX-License-Identifier: EUPL-1.2

use std::fmt::{Debug, Formatter};
use std::marker::PhantomData;
use std::mem::swap;

/// A binary max-heap.
///
/// Uses a list representation internally.
pub type BinaryMaxHeap<T> = BinaryHeap<T, Max<T>>;

/// A binary max-heap.
///
/// Uses a list representation internally.
pub type BinaryMinHeap<T> = BinaryHeap<T, Min<T>>;

/// A binary tree with an arbitrary heap property.
pub struct BinaryHeap<T, H> {
    /// The heap in list representation.
    ///
    /// ## List representation
    ///
    /// An element at index `N` has its left child at index `2×N+1` and its right child at `2×N+2`.
    /// The parent of a non-root element at `N>0` can be found at index `(N-1)/2`.
    ///
    /// ## Complete Binary Tree
    ///
    /// The heap is implemented as a complete binary tree, i.e. all levels are completely filled,
    /// except for possibly the last level, i.e. all children are as far left as possible, and a
    /// node has either both a left and right child, just a left child or no children at all.
    data: Vec<T>,
    _heap_property: PhantomData<H>,
}

/// Implements the max-heap property.
pub struct Max<T>(PhantomData<T>);

/// Implements the min-heap property.
pub struct Min<T>(PhantomData<T>);

/// Heap property.
pub trait HeapProperty<T> {
    const NAME: &'static str;

    /// Determines whether the heap property is upheld between the first and the
    /// second value, where the first value takes priority:
    ///
    /// * `property_upheld(parent, child)`
    /// * `property_upheld(left, right)`
    fn property_upheld(lhs: &T, rhs: &T) -> bool;
}

impl<T, H> BinaryHeap<T, H> {
    /// Constructs a new, empty `BinaryHeap`.
    pub const fn new() -> Self {
        Self {
            data: Vec::new(),
            _heap_property: PhantomData,
        }
    }

    /// Constructs a new, empty `BinaryHeap` with at least the specified capacity.
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            data: Vec::with_capacity(capacity),
            _heap_property: PhantomData,
        }
    }

    /// Pushes an element onto the heap.
    ///
    /// ## Arguments
    ///
    /// * `value` - The value to push onto the heap.
    pub fn push(&mut self, value: T)
    where
        T: PartialOrd,
        H: HeapProperty<T>,
    {
        let index = self.data.len();
        self.data.push(value);
        self.upheap(index);
    }

    /// Gets a reference to the top element on the heap.
    ///
    /// ## Returns
    ///
    /// A value if the tree is nonempty; or `None` otherwise.
    pub fn peek(&self) -> Option<&T> {
        self.data.get(0)
    }

    /// Extracts an element from the heap.
    ///
    /// ## Returns
    ///
    /// A value if the tree is nonempty; or `None` otherwise.
    pub fn pop(&mut self) -> Option<T>
    where
        T: PartialOrd,
        H: HeapProperty<T>,
    {
        if self.data.is_empty() {
            return None;
        }

        // Replace the root of the heap with the last element on the last level.
        let last_index = self.data.len() - 1;
        self.data.swap(0, last_index);

        // We extract the last element first so it doesn't interfere with the downheap operation.
        let extracted_value = self.data.pop();

        if !self.data.is_empty() {
            self.downheap(0);
        }

        extracted_value
    }

    /// Pushes an element onto the heap and extracts the top value in one operation.
    ///
    /// ## Arguments
    ///
    /// * `value` - The value to push onto the heap.
    ///
    /// ## Returns
    ///
    /// The value. If the tree is empty, the value itself is returned.
    pub fn push_pop(&mut self, mut value: T) -> T
    where
        T: PartialOrd,
        H: HeapProperty<T>,
    {
        if self.data.is_empty() {
            return value;
        }

        if H::property_upheld(&value, &self.data[0]) {
            return value;
        }

        swap(&mut self.data[0], &mut value);
        self.downheap(0);

        value
    }

    /// Determines whether the heap contains the specified item.
    ///
    /// ## Arguments
    ///
    /// * `value` - The value to test for.
    ///
    /// ## Returns
    ///
    /// Returns `true` if the heap contains the specified item or `false` if not.
    pub fn contains(&self, value: &T) -> bool
    where
        T: PartialEq,
    {
        self.data.contains(value)
    }

    /// Deletes a value from the heap.
    ///
    /// ## Arguments
    ///
    /// * `value` - The value to delete.
    ///
    /// ## Returns
    ///
    /// Returns `true` if the value was deleted or `false` if not.
    pub fn remove(&mut self, value: &T) -> bool
    where
        T: PartialEq + PartialOrd,
        H: HeapProperty<T>,
    {
        self.remove_where(|x| x == value).is_some()
    }

    /// Deletes a value from the heap.
    ///
    /// ## Arguments
    ///
    /// * `predicate` - The predicate used to test for the value. If the predicate matches,
    ///                 the value is removed and the function returns.
    ///
    /// ## Returns
    ///
    /// Returns `Some(value)` if the value was deleted or `None` if not.
    pub fn remove_where<F>(&mut self, predicate: F) -> Option<T>
    where
        T: PartialEq + PartialOrd,
        H: HeapProperty<T>,
        F: FnMut(&T) -> bool,
    {
        if self.data.is_empty() {
            return None;
        }

        let last_index = self.data.len() - 1;

        // Find the index of the element we want to delete.
        if let Some(index) = self.data.iter().position(predicate) {
            // Swap this element with the last element.
            self.data.swap(index, last_index);

            // Remove the element.
            let previous_value = self.data.pop().expect("the value exists");

            // If we deleted the last element, exit.
            if index == last_index {
                return Some(previous_value);
            }

            // Down-heapify or up-heapify to restore the heap property.
            let up_heapify = H::property_upheld(&self.data[index], &previous_value);
            if up_heapify {
                self.upheap(index);
            } else {
                self.downheap(index);
            }

            Some(previous_value)
        } else {
            None
        }
    }

    /// Replaces a value on the heap.
    ///
    /// This function can be used if the replacement value already exists. If the element needs
    /// to be mutated in place, use [`BinaryHeap::replace_where_with`] instead.
    ///
    /// ## Arguments
    ///
    /// * `value` - The value to replace.
    /// * `replacement` - The replacement value.
    ///
    /// ## Returns
    ///
    /// Returns `Some(previous value)` if the value was replaced or `None` if not.
    pub fn replace(&mut self, value: &T, replacement: T) -> Option<T>
    where
        T: PartialEq + PartialOrd,
        H: HeapProperty<T>,
    {
        self.replace_where(|x| x == value, replacement)
    }

    /// Replaces a value on the heap.
    ///
    /// This function can be used if the replacement value already exists. If the element needs
    /// to be mutated in place, use [`BinaryHeap::replace_where_with`] instead.
    ///
    /// ## Arguments
    ///
    /// * `predicate` - The predicate used to test for the value. If the predicate matches,
    ///                 the value is removed and the function returns.
    /// * `replacement` - The replacement value.
    ///
    /// ## Returns
    ///
    /// Returns `Some(previous value)` if the value was replaced or `None` if not.
    pub fn replace_where<F>(&mut self, predicate: F, mut replacement: T) -> Option<T>
    where
        T: PartialEq + PartialOrd,
        H: HeapProperty<T>,
        F: FnMut(&T) -> bool,
    {
        if self.data.is_empty() {
            return None;
        }

        // Find the index of the element we want to delete.
        if let Some(index) = self.data.iter().position(predicate) {
            let downheap = H::property_upheld(&self.data[index], &replacement);

            swap(&mut self.data[index], &mut replacement);

            if downheap {
                self.downheap(index);
            } else {
                self.upheap(index);
            }

            Some(replacement)
        } else {
            None
        }
    }

    /// Replaces a value on the heap.
    ///
    /// This function allows to mutate the value in-place but at the cost of a bit of performance.
    /// If the replacement value exists beforehand, use [`BinaryHeap::replace_where`] instead.
    ///
    /// ## Arguments
    ///
    /// * `value` - The value to replace.
    /// * `replacement` - The function creating the replacement value.
    ///
    /// ## Returns
    ///
    /// Returns `true` if the value was replaced or `false` if not.
    pub fn replace_with<R>(&mut self, value: &T, replacement: R) -> bool
    where
        T: PartialEq + PartialOrd,
        H: HeapProperty<T>,
        R: FnMut(&mut T),
    {
        self.replace_where_with(|x| x == value, replacement)
    }

    /// Replaces a value on the heap.
    ///
    /// This function allows to mutate the value in-place but at the cost of a bit of performance.
    /// If the replacement value exists beforehand, use [`BinaryHeap::replace_where`] instead.
    ///
    /// ## Arguments
    ///
    /// * `predicate` - The predicate used to test for the value. If the predicate matches,
    ///                 the value is removed and the function returns.
    /// * `replacement` - The function creating the replacement value.
    ///
    /// ## Returns
    ///
    /// Returns `true` if the value was replaced or `false` if not.
    pub fn replace_where_with<F, R>(&mut self, predicate: F, mut replacement: R) -> bool
    where
        T: PartialEq + PartialOrd,
        H: HeapProperty<T>,
        F: FnMut(&T) -> bool,
        R: FnMut(&mut T),
    {
        if self.data.is_empty() {
            return false;
        }

        // Find the index of the element we want to delete.
        if let Some(index) = self.data.iter().position(predicate) {
            // Mutate the element.
            replacement(&mut self.data[index]);

            // TODO: Optimize these calls? We don't know if the value increased or decreased here.
            let _ = self.upheap(index) || self.downheap(index);

            true
        } else {
            false
        }
    }

    /// Returns the number of elements on the heap.
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// Returns `true` if the heap is empty.
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    /// Ensures that elements are in the correct order, starting from a given child node,
    /// working its way up the heap.
    ///
    /// ## Returns
    ///
    /// Returns `true` if the tree was changed or `false` if no change was performed.
    fn upheap(&mut self, mut index: usize) -> bool
    where
        T: PartialOrd,
        H: HeapProperty<T>,
    {
        debug_assert!(index < self.data.len());
        let mut changed = false;

        // Compare the added element with its parent; if they are in the correct order, stop.
        while index > 0 {
            let parent_idx = self
                .get_parent_idx(index)
                .expect("since the tree was not empty before the insert, the parent must exist");

            let parent = self
                .data
                .get(parent_idx)
                .expect("since the tree was not empty before the insert, the parent must exist");

            if H::property_upheld(&parent, &self.data[index]) {
                break;
            }

            // If not, swap the element with its parent and return to the previous step.
            self.data.swap(parent_idx, index);
            index = parent_idx;

            changed = true;
        }

        changed
    }

    /// Ensures that elements are in the correct order, starting from a given parent node,
    /// working its way down the heap.
    ///
    /// ## Returns
    ///
    /// Returns `true` if the tree was changed or `false` if no change was performed.
    fn downheap(&mut self, mut index: usize) -> bool
    where
        T: PartialOrd,
        H: HeapProperty<T>,
    {
        debug_assert!(index < self.data.len());
        let mut changed = false;

        // Compare the new root with its children; if they are in the correct order, stop.
        // If not, swap the element with one of its children and return to the previous step.
        // (Swap with its smaller child in a min-heap and its larger child in a max-heap.)
        loop {
            let left_child_idx = self.get_left_child_idx(index);
            let right_child_idx = self.get_right_child_idx(index);

            let current = &self.data[index];

            match (left_child_idx, right_child_idx) {
                (Some(left), Some(right)) => {
                    let left_child = &self.data[left];
                    let right_child = &self.data[right];

                    if H::property_upheld(&current, left_child)
                        && H::property_upheld(current, right_child)
                    {
                        break;
                    }

                    if H::property_upheld(left_child, right_child) {
                        self.data.swap(index, left);
                        index = left;
                    } else {
                        self.data.swap(index, right);
                        index = right;
                    }

                    changed = true;
                }
                (Some(child), None) => {
                    let left_child = &self.data[child];

                    if H::property_upheld(current, left_child) {
                        break;
                    }

                    self.data.swap(index, child);

                    // Since there is no right child and the tree is balanced, the left child can also not have any children.
                    debug_assert!(self.get_left_child_idx(child).is_none());

                    changed = true;
                }
                (None, Some(_)) => unreachable!("the tree cannot have only a right child"),
                (None, None) => break,
            }
        }

        changed
    }

    /// Gets the index of the left child of the item at the specified `index`.
    const fn get_left_child_idx_unchecked(index: usize) -> usize {
        2 * index + 1
    }

    /// Gets the index of the left child of the item at the specified `index`.
    ///
    /// ## Returns
    ///
    /// * `Some(index)` if the element exists in the tree.
    /// * `None` if the child does not exist.
    fn get_left_child_idx(&self, index: usize) -> Option<usize> {
        let idx = Self::get_left_child_idx_unchecked(index);
        if idx < self.data.len() {
            Some(idx)
        } else {
            None
        }
    }

    /// Gets the index of the right child of the item at the specified `index`.
    const fn get_right_child_idx_unchecked(index: usize) -> usize {
        2 * index + 2
    }

    /// Gets the index of the right child of the item at the specified `index`.
    ///
    /// ## Returns
    ///
    /// * `Some(index)` if the element exists in the tree.
    /// * `None` if the child does not exist.
    fn get_right_child_idx(&self, index: usize) -> Option<usize> {
        let idx = Self::get_right_child_idx_unchecked(index);
        if idx < self.data.len() {
            Some(idx)
        } else {
            None
        }
    }

    /// Gets the index of the parent of the item at the specified `index`.
    ///
    /// ## Returns
    ///
    /// * `Some(index)` if the element exists in the tree.
    /// * `None` if the parent does not exist.
    fn get_parent_idx(&self, index: usize) -> Option<usize> {
        if index == 0 || index >= self.data.len() {
            return None;
        }

        Some((index - 1) / 2)
    }
}

impl<T, H> FromIterator<T> for BinaryHeap<T, H>
where
    T: PartialOrd,
    H: HeapProperty<T>,
{
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        <Self as From<Vec<T>>>::from(iter.into_iter().collect())
    }
}

impl<T, H> From<Vec<T>> for BinaryHeap<T, H>
where
    T: PartialOrd,
    H: HeapProperty<T>,
{
    fn from(value: Vec<T>) -> Self {
        let mut tree = Self {
            data: value,
            _heap_property: PhantomData,
        };

        // Floyd's method.
        let length = tree.data.len();
        for i in (0..=(length / 2)).rev() {
            tree.downheap(i);
        }

        tree
    }
}

impl<T, H> Debug for BinaryHeap<T, H>
where
    T: Debug,
    H: HeapProperty<T>,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct(&format!("Binary{}Heap", H::NAME))
            .field("data", &self.data)
            .finish()
    }
}

impl<T, H> Default for BinaryHeap<T, H> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T, H> Clone for BinaryHeap<T, H>
where
    T: Clone,
{
    fn clone(&self) -> Self {
        Self {
            data: self.data.clone(),
            _heap_property: PhantomData,
        }
    }
}

impl<T, H> AsRef<[T]> for BinaryHeap<T, H> {
    fn as_ref(&self) -> &[T] {
        &self.data
    }
}

impl<T> HeapProperty<T> for Max<T>
where
    T: PartialOrd,
{
    const NAME: &'static str = "Max";

    fn property_upheld(lhs: &T, rhs: &T) -> bool {
        lhs >= rhs
    }
}

impl<T> HeapProperty<T> for Min<T>
where
    T: PartialOrd,
{
    const NAME: &'static str = "Min";

    fn property_upheld(lhs: &T, rhs: &T) -> bool {
        lhs <= rhs
    }
}