mirror of
https://github.com/apple/swift-collections
synced 2026-11-28 05:04:21 +00:00
Add Heap.removeAll(where:)
This commit is contained in:
1 parent
60746986d8
commit
027b92153b
2 files changed
+58
No files matched your search
@@ -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.
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user