From 027b92153b22d7dcd3856c32280e9fff24aef528 Mon Sep 17 00:00:00 2001 From: Dakshin Devanand Date: Fri, 7 Mar 2025 17:47:16 -0600 Subject: [PATCH] Add Heap.removeAll(where:) --- Sources/HeapModule/Heap.swift | 20 +++++++++++++++++ Tests/HeapTests/HeapTests.swift | 38 +++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/Sources/HeapModule/Heap.swift b/Sources/HeapModule/Heap.swift index d533ead6..fbb6e40e 100644 --- a/Sources/HeapModule/Heap.swift +++ b/Sources/HeapModule/Heap.swift @@ -268,6 +268,26 @@ extension Heap { _checkInvariants() return removed } + + /// Removes all the elements that satisfy the given predicate. + /// + /// - Parameter shouldBeRemoved: A closure that takes an element of the + /// heap as its argument and returns a Boolean value indicating + /// whether the element should be removed from the heap. + /// + /// - Complexity: O(*n*), where *n* is the number of items in the heap. + @inlinable + public mutating func removeAll( + where shouldBeRemoved: (Element) throws -> Bool + ) rethrows { + defer { _checkInvariants() } + try _storage.removeAll(where: shouldBeRemoved) + if _storage.count > 1 { + _update { handle in + handle.heapify() + } + } + } /// Replaces the maximum value in the heap with the given replacement, /// then updates heap contents to reflect the change. diff --git a/Tests/HeapTests/HeapTests.swift b/Tests/HeapTests/HeapTests.swift index 040d5541..293328b0 100644 --- a/Tests/HeapTests/HeapTests.swift +++ b/Tests/HeapTests/HeapTests.swift @@ -641,4 +641,42 @@ final class HeapTests: CollectionTestCase { } } } + + func test_removeAll_noneRemoved() { + withEvery("count", in: 0 ..< 20) { count in + withEvery("seed", in: 0 ..< 100) { seed in + var rng = RepeatableRandomNumberGenerator(seed: seed) + let input = (0 ..< count).shuffled(using: &rng) + var heap = Heap(input) + heap.removeAll { _ in false } + let expected = Array(0 ..< count) + expectEqualElements(heap.itemsInAscendingOrder(), expected) + } + } + } + + func test_removeAll_allRemoved() { + withEvery("count", in: 0 ..< 20) { count in + withEvery("seed", in: 0 ..< 100) { seed in + var rng = RepeatableRandomNumberGenerator(seed: seed) + let input = (0 ..< count).shuffled(using: &rng) + var heap = Heap(input) + heap.removeAll { _ in true } + expectTrue(heap.isEmpty) + } + } + } + + func test_removeAll_removeEvenNumbers() { + withEvery("count", in: 0 ..< 20) { count in + withEvery("seed", in: 0 ..< 100) { seed in + var rng = RepeatableRandomNumberGenerator(seed: seed) + let input = (0 ..< count).shuffled(using: &rng) + var heap = Heap(input) + heap.removeAll { $0 % 2 == 0 } + let expected = Array(stride(from: 1, to: count, by: 2)) + expectEqualElements(heap.itemsInAscendingOrder(), expected) + } + } + } }