diff --git a/Guides/MinMax.md b/Guides/MinMax.md new file mode 100644 index 0000000..1745544 --- /dev/null +++ b/Guides/MinMax.md @@ -0,0 +1,58 @@ +# Min/Max with Count + +[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/MinMax.swift) | + [Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/MinMaxTests.swift)] + +Returns the smallest or largest elements of this collection, sorted by a predicate or in the order defined by `Comparable` conformance. + +If you need to sort a collection but only need access to a prefix or suffix of the sorted elements, using these methods can give you a performance boost over sorting the entire collection. The order of equal elements is guaranteed to be preserved. + +```swift +let numbers = [7, 1, 6, 2, 8, 3, 9] +let smallestThree = numbers.min(count: 3, sortedBy: <) +// [1, 2, 3] +``` + +## Detailed Design + +This adds the `Collection` methods shown below: + +```swift +extension Collection { + public func min( + count: Int, + sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool + ) rethrows -> [Element] + + public func max( + count: Int, + sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool + ) rethrows -> [Element] +} +``` + +Additionally, versions of these methods for `Comparable` types are also provided: + +```swift +extension Collection where Element: Comparable { + public func min(count: Int) -> [Element] + + public func max(count: Int) -> [Element] +} +``` + +### Complexity + +The algorithm used is based on [Soroush Khanlou's research on this matter](https://khanlou.com/2018/12/analyzing-complexity/). The total complexity is `O(k log k + nk)`, which will result in a runtime close to `O(n)` if *k* is a small amount. If *k* is a large amount (more than 10% of the collection), we fall back to sorting the entire array. Realistically, this means the worst case is actually `O(n log n)`. + +Here are some benchmarks we made that demonstrates how this implementation (SmallestM) behaves when *k* increases (before implementing the fallback): + +![Benchmark](Resources/SortedPrefix/FewElements.png) +![Benchmark 2](Resources/SortedPrefix/ManyElements.png) + +### Comparison with other languages + +**C++:** The `` library defines a `partial_sort` function where the entire array is returned using a partial heap sort. + +**Python:** Defines a `heapq` priority queue that can be used to manually achieve the same result. + diff --git a/Guides/SortedPrefix.md b/Guides/SortedPrefix.md deleted file mode 100644 index 297da45..0000000 --- a/Guides/SortedPrefix.md +++ /dev/null @@ -1,48 +0,0 @@ -# Sorted Prefix - -[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/PartialSort.swift) | - [Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/SwiftAlgorithmsTests/PartialSortTests.swift)] - -Returns the first k elements of this collection when it's sorted. - -If you need to sort a collection but only need access to a prefix of its elements, using this method can give you a performance boost over sorting the entire collection. The order of equal elements is guaranteed to be preserved. - -```swift -let numbers = [7,1,6,2,8,3,9] -let smallestThree = numbers.sortedPrefix(3, by: <) -// [1, 2, 3] -``` - -## Detailed Design - -This adds the `Collection` method shown below: - -```swift -extension Collection { - public func sortedPrefix(_ count: Int, by areInIncreasingOrder: (Element, Element) throws -> Bool) rethrows -> [Element] -} -``` - -Additionally, a version of this method for `Comparable` types is also provided: - -```swift -extension Collection where Element: Comparable { - public func sortedPrefix(_ count: Int) -> [Element] -} -``` - -### Complexity - -The algorithm used is based on [Soroush Khanlou's research on this matter](https://khanlou.com/2018/12/analyzing-complexity/). The total complexity is `O(k log k + nk)`, which will result in a runtime close to `O(n)` if k is a small amount. If k is a large amount (more than 10% of the collection), we fall back to sorting the entire array. Realistically, this means the worst case is actually `O(n log n)`. - -Here are some benchmarks we made that demonstrates how this implementation (SmallestM) behaves when k increases (before implementing the fallback): - -![Benchmark](Resources/SortedPrefix/FewElements.png) -![Benchmark 2](Resources/SortedPrefix/ManyElements.png) - -### Comparison with other languages - -**C++:** The `` library defines a `partial_sort` function where the entire array is returned using a partial heap sort. - -**Python:** Defines a `heapq` priority queue that can be used to manually achieve the same result. - diff --git a/README.md b/README.md index 422ff2d..2bd5d9b 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ Read more about the package, and the intent behind it, in the [announcement on s #### Partial sorting -- [`sortedPrefix(_:by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/SortedPrefix.md): Returns the first k elements of a sorted collection. +- [`min(count:)`, `max(count:)`, `min(count:sortedBy:)`, `max(count:sortedBy:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/MinMax.md): Returns the smallest or largest elements of a collection, sorted by a predicate. #### Other useful operations diff --git a/Sources/Algorithms/MinMax.swift b/Sources/Algorithms/MinMax.swift new file mode 100644 index 0000000..375a3b8 --- /dev/null +++ b/Sources/Algorithms/MinMax.swift @@ -0,0 +1,385 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Algorithms open source project +// +// Copyright (c) 2020 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +extension Sequence { + /// Implementation for min(count:areInIncreasingOrder:) + @inlinable + internal func _minImplementation( + count: Int, + sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool + ) rethrows -> [Element] { + var iterator = makeIterator() + + var result: [Element] = [] + result.reserveCapacity(count) + while result.count < count, let e = iterator.next() { + result.append(e) + } + try result.sort(by: areInIncreasingOrder) + + while let e = iterator.next() { + // To be part of `result`, `e` must be strictly less than `result.last`. + guard try areInIncreasingOrder(e, result.last!) else { continue } + let insertionIndex = + try result.partitioningIndex { try areInIncreasingOrder(e, $0) } + + assert(insertionIndex != result.endIndex) + result.removeLast() + result.insert(e, at: insertionIndex) + } + + return result + } + + /// Implementation for max(count:areInIncreasingOrder:) + @inlinable + internal func _maxImplementation( + count: Int, + sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool + ) rethrows -> [Element] { + var iterator = makeIterator() + + var result: [Element] = [] + result.reserveCapacity(count) + while result.count < count, let e = iterator.next() { + result.append(e) + } + try result.sort(by: areInIncreasingOrder) + + while let e = iterator.next() { + // To be part of `result`, `e` must be greater/equal to `result.first`. + guard try !areInIncreasingOrder(e, result.first!) else { continue } + let insertionIndex = + try result.partitioningIndex { try areInIncreasingOrder(e, $0) } + + assert(insertionIndex > 0) + // Inserting `e` and then removing the first element (or vice versa) + // would perform a double shift, so we manually shift down the elements + // before dropping `e` in. + var i = 1 + while i < insertionIndex { + result[i - 1] = result[i] + i += 1 + } + result[insertionIndex - 1] = e + } + + return result + } + + /// Returns the smallest elements of this sequence, as sorted by the given + /// predicate. + /// + /// This example partially sorts an array of integers to retrieve its three + /// smallest values: + /// + /// let numbers = [7, 1, 6, 2, 8, 3, 9] + /// let smallestThree = numbers.min(count: 3, sortedBy: <) + /// // [1, 2, 3] + /// + /// If you need to sort a sequence but only need to access its smallest + /// elements, using this method can give you a performance boost over sorting + /// the entire sequence. The order of equal elements is guaranteed to be + /// preserved. + /// + /// - Parameters: + /// - count: The number of elements to return. If `count` is greater than + /// the number of elements in this sequence, all of the sequence's + /// elements are returned. + /// - areInIncreasingOrder: A predicate that returns `true` if its + /// first argument should be ordered before its second argument; + /// otherwise, `false`. + /// - Returns: An array of the smallest `count` elements of this sequence, + /// sorted according to `areInIncreasingOrder`. + /// + /// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the + /// sequence and *k* is `count`. + @inlinable + public func min( + count: Int, + sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool + ) rethrows -> [Element] { + precondition(count >= 0, """ + Cannot find a minimum with a negative count of elements! + """ + ) + + // Do nothing if we're prefixing nothing. + guard count > 0 else { + return [] + } + + return try _minImplementation(count: count, sortedBy: areInIncreasingOrder) + } + + /// Returns the largets elements of this sequence, as sorted by the given + /// predicate. + /// + /// This example partially sorts an array of integers to retrieve its three + /// largest values: + /// + /// let numbers = [7, 1, 6, 2, 8, 3, 9] + /// let smallestThree = numbers.max(count: 3, sortedBy: <) + /// // [7, 8, 9] + /// + /// If you need to sort a sequence but only need to access its largest + /// elements, using this method can give you a performance boost over sorting + /// the entire sequence. The order of equal elements is guaranteed to be + /// preserved. + /// + /// - Parameters: + /// - count: The number of elements to return. If `count` is greater than + /// the number of elements in this sequence, all of the sequence's + /// elements are returned. + /// - areInIncreasingOrder: A predicate that returns `true` if its + /// first argument should be ordered before its second argument; + /// otherwise, `false`. + /// - Returns: An array of the largest `count` elements of this sequence, + /// sorted according to `areInIncreasingOrder`. + /// + /// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the + /// sequence and *k* is `count`. + @inlinable + public func max( + count: Int, + sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool + ) rethrows -> [Element] { + precondition(count >= 0, """ + Cannot find a maximum with a negative count of elements! + """ + ) + + // Do nothing if we're suffixing nothing. + guard count > 0 else { + return [] + } + + return try _maxImplementation(count: count, sortedBy: areInIncreasingOrder) + } +} + +extension Sequence where Element: Comparable { + /// Returns the smallest elements of this sequence. + /// + /// This example partially sorts an array of integers to retrieve its three + /// smallest values: + /// + /// let numbers = [7, 1, 6, 2, 8, 3, 9] + /// let smallestThree = numbers.min(count: 3) + /// // [1, 2, 3] + /// + /// If you need to sort a sequence but only need to access its smallest + /// elements, using this method can give you a performance boost over sorting + /// the entire sequence. The order of equal elements is guaranteed to be + /// preserved. + /// + /// - Parameter count: The number of elements to return. If `count` is greater + /// than the number of elements in this sequence, all of the sequence's + /// elements are returned. + /// - Returns: An array of the smallest `count` elements of this sequence. + /// + /// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the + /// sequence and *k* is `count`. + @inlinable + public func min(count: Int) -> [Element] { + return min(count: count, sortedBy: <) + } + + /// Returns the largest elements of this sequence. + /// + /// This example partially sorts an array of integers to retrieve its three + /// largest values: + /// + /// let numbers = [7, 1, 6, 2, 8, 3, 9] + /// let smallestThree = numbers.max(count: 3) + /// // [7, 8, 9] + /// + /// If you need to sort a sequence but only need to access its largest + /// elements, using this method can give you a performance boost over sorting + /// the entire sequence. The order of equal elements is guaranteed to be + /// preserved. + /// + /// - Parameter count: The number of elements to return. If `count` is greater + /// than the number of elements in this sequence, all of the sequence's + /// elements are returned. + /// - Returns: An array of the largest `count` elements of this sequence. + /// + /// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the + /// sequence and *k* is `count`. + @inlinable + public func max(count: Int) -> [Element] { + return max(count: count, sortedBy: <) + } +} + +extension Collection { + /// Returns the smallest elements of this collection, as sorted by the given + /// predicate. + /// + /// This example partially sorts an array of integers to retrieve its three + /// smallest values: + /// + /// let numbers = [7, 1, 6, 2, 8, 3, 9] + /// let smallestThree = numbers.min(count: 3, sortedBy: <) + /// // [1, 2, 3] + /// + /// If you need to sort a collection but only need to access its smallest + /// elements, using this method can give you a performance boost over sorting + /// the entire collection. The order of equal elements is guaranteed to be + /// preserved. + /// + /// - Parameters: + /// - count: The number of elements to return. If `count` is greater than + /// the number of elements in this collection, all of the collection's + /// elements are returned. + /// - areInIncreasingOrder: A predicate that returns `true` if its + /// first argument should be ordered before its second argument; + /// otherwise, `false`. + /// - Returns: An array of the smallest `count` elements of this collection, + /// sorted according to `areInIncreasingOrder`. + /// + /// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the + /// collection and *k* is `count`. + @inlinable + public func min( + count: Int, + sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool + ) rethrows -> [Element] { + precondition(count >= 0, """ + Cannot find a minimum with a negative count of elements! + """ + ) + + // Do nothing if we're prefixing nothing. + guard count > 0 else { + return [] + } + + // Make sure we are within bounds. + let prefixCount = Swift.min(count, self.count) + + // If we're attempting to prefix more than 10% of the collection, it's + // faster to sort everything. + guard prefixCount < (self.count / 10) else { + return Array(try sorted(by: areInIncreasingOrder).prefix(prefixCount)) + } + + return try _minImplementation(count: count, sortedBy: areInIncreasingOrder) + } + + /// Returns the largets elements of this collection, as sorted by the given + /// predicate. + /// + /// This example partially sorts an array of integers to retrieve its three + /// largest values: + /// + /// let numbers = [7, 1, 6, 2, 8, 3, 9] + /// let smallestThree = numbers.max(count: 3, sortedBy: <) + /// // [7, 8, 9] + /// + /// If you need to sort a collection but only need to access its largest + /// elements, using this method can give you a performance boost over sorting + /// the entire collection. The order of equal elements is guaranteed to be + /// preserved. + /// + /// - Parameters: + /// - count: The number of elements to return. If `count` is greater than + /// the number of elements in this collection, all of the collection's + /// elements are returned. + /// - areInIncreasingOrder: A predicate that returns `true` if its + /// first argument should be ordered before its second argument; + /// otherwise, `false`. + /// - Returns: An array of the largest `count` elements of this collection, + /// sorted according to `areInIncreasingOrder`. + /// + /// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the + /// collection and *k* is `count`. + @inlinable + public func max( + count: Int, + sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool + ) rethrows -> [Element] { + precondition(count >= 0, """ + Cannot find a maximum with a negative count of elements! + """ + ) + + // Do nothing if we're suffixing nothing. + guard count > 0 else { + return [] + } + + // Make sure we are within bounds. + let suffixCount = Swift.min(count, self.count) + + // If we're attempting to prefix more than 10% of the collection, it's + // faster to sort everything. + guard suffixCount < (self.count / 10) else { + return Array(try sorted(by: areInIncreasingOrder).suffix(suffixCount)) + } + + return try _maxImplementation(count: count, sortedBy: areInIncreasingOrder) + } +} + +extension Collection where Element: Comparable { + /// Returns the smallest elements of this collection. + /// + /// This example partially sorts an array of integers to retrieve its three + /// smallest values: + /// + /// let numbers = [7, 1, 6, 2, 8, 3, 9] + /// let smallestThree = numbers.min(count: 3) + /// // [1, 2, 3] + /// + /// If you need to sort a collection but only need to access its smallest + /// elements, using this method can give you a performance boost over sorting + /// the entire collection. The order of equal elements is guaranteed to be + /// preserved. + /// + /// - Parameter count: The number of elements to return. If `count` is greater + /// than the number of elements in this collection, all of the collection's + /// elements are returned. + /// - Returns: An array of the smallest `count` elements of this collection. + /// + /// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the + /// collection and *k* is `count`. + @inlinable + public func min(count: Int) -> [Element] { + return min(count: count, sortedBy: <) + } + + /// Returns the largest elements of this collection. + /// + /// This example partially sorts an array of integers to retrieve its three + /// largest values: + /// + /// let numbers = [7, 1, 6, 2, 8, 3, 9] + /// let smallestThree = numbers.max(count: 3) + /// // [7, 8, 9] + /// + /// If you need to sort a collection but only need to access its largest + /// elements, using this method can give you a performance boost over sorting + /// the entire collection. The order of equal elements is guaranteed to be + /// preserved. + /// + /// - Parameter count: The number of elements to return. If `count` is greater + /// than the number of elements in this collection, all of the collection's + /// elements are returned. + /// - Returns: An array of the largest `count` elements of this collection. + /// + /// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the + /// collection and *k* is `count`. + @inlinable + public func max(count: Int) -> [Element] { + return max(count: count, sortedBy: <) + } +} diff --git a/Sources/Algorithms/SortedPrefix.swift b/Sources/Algorithms/SortedPrefix.swift deleted file mode 100644 index 88b1ed5..0000000 --- a/Sources/Algorithms/SortedPrefix.swift +++ /dev/null @@ -1,99 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift Algorithms open source project -// -// Copyright (c) 2020 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// -//===----------------------------------------------------------------------===// - -extension Collection { - /// Returns the first k elements of this collection when it's sorted using - /// the given predicate as the comparison between elements. - /// - /// This example partially sorts an array of integers to retrieve its three - /// smallest values: - /// - /// let numbers = [7,1,6,2,8,3,9] - /// let smallestThree = numbers.sortedPrefix(3, by: <) - /// // [1, 2, 3] - /// - /// If you need to sort a collection but only need access to a prefix of its - /// elements, using this method can give you a performance boost over sorting - /// the entire collection. The order of equal elements is guaranteed to be - /// preserved. - /// - /// - Parameter count: The k number of elements to prefix. - /// - Parameter areInIncreasingOrder: A predicate that returns true if its - /// first argument should be ordered before its second argument; - /// otherwise, false. - /// - /// - Complexity: O(k log k + nk) - public func sortedPrefix( - _ count: Int, - by areInIncreasingOrder: (Element, Element) throws -> Bool - ) rethrows -> [Self.Element] { - assert(count >= 0, """ - Cannot prefix with a negative amount of elements! - """ - ) - - // Do nothing if we're prefixing nothing. - guard count > 0 else { - return [] - } - - // Make sure we are within bounds. - let prefixCount = Swift.min(count, self.count) - - // If we're attempting to prefix more than 10% of the collection, it's - // faster to sort everything. - guard prefixCount < (self.count / 10) else { - return Array(try sorted(by: areInIncreasingOrder).prefix(prefixCount)) - } - - var result = try self.prefix(prefixCount).sorted(by: areInIncreasingOrder) - for e in self.dropFirst(prefixCount) { - if let last = result.last, try areInIncreasingOrder(last, e) { - continue - } - let insertionIndex = - try result.partitioningIndex { try areInIncreasingOrder(e, $0) } - let isLastElement = insertionIndex == result.endIndex - result.removeLast() - if isLastElement { - result.append(e) - } else { - result.insert(e, at: insertionIndex) - } - } - - return result - } -} - -extension Collection where Element: Comparable { - /// Returns the first k elements of this collection when it's sorted in - /// ascending order. - /// - /// This example partially sorts an array of integers to retrieve its three - /// smallest values: - /// - /// let numbers = [7,1,6,2,8,3,9] - /// let smallestThree = numbers.sortedPrefix(3) - /// // [1, 2, 3] - /// - /// If you need to sort a collection but only need access to a prefix of its - /// elements, using this method can give you a performance boost over sorting - /// the entire collection. The order of equal elements is guaranteed to be - /// preserved. - /// - /// - Parameter count: The k number of elements to prefix. - /// - /// - Complexity: O(k log k + nk) - public func sortedPrefix(_ count: Int) -> [Element] { - return sortedPrefix(count, by: <) - } -} diff --git a/Tests/SwiftAlgorithmsTests/MinMaxTests.swift b/Tests/SwiftAlgorithmsTests/MinMaxTests.swift new file mode 100644 index 0000000..c0dedb3 --- /dev/null +++ b/Tests/SwiftAlgorithmsTests/MinMaxTests.swift @@ -0,0 +1,187 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Algorithms open source project +// +// Copyright (c) 2020 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +import XCTest +import Algorithms + +final class SortedPrefixTests: XCTestCase { + func testMinCount() { + // Replacement at start and end + let input = [10, 11, 12, 1, 13, 2, 14, 3, 4, 5, 6, 0, 7, 8, 9] + let min = input.min(count: 5) + XCTAssertEqualSequences(min, 0..<5) + + // Stability with all equal values + let maxZeroes = Array(repeating: 0, count: 100) + .enumerated() + .max(count: 5, sortedBy: { $0.element < $1.element }) + XCTAssertEqualSequences(maxZeroes.map { $0.offset }, 95..<100) + } + + func testMaxCount() { + // Replacement at start and end + let input = [0, 11, 12, 1, 13, 2, 14, 3, 4, 5, 6, 7, 8, 9, 10] + let max = input.max(count: 5) + XCTAssertEqualSequences(max, 10..<15) + + // Stability with all equal values + let maxZeroes = Array(repeating: 0, count: 100) + .enumerated() + .max(count: 5, sortedBy: { $0.element < $1.element }) + XCTAssertEqualSequences(maxZeroes.map { $0.offset }, 95..<100) + } + + func testEmpty() { + let array = [Int]() + XCTAssertEqual(array.min(count: 0), []) + XCTAssertEqual(array.min(count: 100), []) + + XCTAssertEqual(array.max(count: 0), []) + XCTAssertEqual(array.max(count: 100), []) + } + + func testMinMaxSequences() { + let input = (1...100).shuffled().interspersed(with: 50) + let seq = AnySequence(input) + + XCTAssertEqualSequences(seq.min(count: 0), []) + XCTAssertEqualSequences(seq.min(count: 5), 1...5) + + XCTAssertEqualSequences(seq.max(count: 0), []) + XCTAssertEqualSequences(seq.max(count: 5), 96...100) + } + + func testSortedPrefixComparable() { + let array: [Int] = [20, 1, 4, 70, 100, 2, 3, 7, 90] + + XCTAssertEqual(array.min(count: 0), []) + XCTAssertEqual(array.min(count: 1), [1]) + XCTAssertEqualSequences(array.min(count: 5), array.sorted().prefix(5)) + XCTAssertEqual(array.min(count: 10), array.sorted()) + } + + func testMinMaxWithHugeCount() { + XCTAssertEqual([4, 2, 1, 3].min(count: .max), [1, 2, 3, 4]) + XCTAssertEqual([4, 2, 1, 3].max(count: .max), [1, 2, 3, 4]) + } + + func testMinCountWithHugeInput() { + let range = 1...1000 + let input = range.shuffled() + + XCTAssertEqual(input.min(count: 0, sortedBy: <), []) + XCTAssertEqual(input.min(count: 0, sortedBy: >), []) + + XCTAssertEqual(input.min(count: 1, sortedBy: <), [range.lowerBound]) + XCTAssertEqual(input.min(count: 1, sortedBy: >), [range.upperBound]) + + XCTAssertEqualSequences(input.min(count: 5, sortedBy: <), range.prefix(5)) + XCTAssertEqualSequences( + input.min(count: 5, sortedBy: >), + range.suffix(5).reversed()) + + XCTAssertEqualSequences( + input.min(count: 500, sortedBy: <), + range.prefix(500)) + XCTAssertEqualSequences( + input.min(count: 500, sortedBy: >), + range.suffix(500).reversed()) + + XCTAssertEqualSequences(input.min(count: 1000, sortedBy: <), range) + XCTAssertEqualSequences( + input.min(count: 1000, sortedBy: >), + range.reversed()) + } + + func testMaxCountWithHugeInput() { + let range = 1...1000 + let input = range.shuffled() + + XCTAssertEqual(input.max(count: 0, sortedBy: <), []) + XCTAssertEqual(input.max(count: 0, sortedBy: >), []) + + XCTAssertEqual(input.max(count: 1, sortedBy: <), [range.upperBound]) + XCTAssertEqual(input.max(count: 1, sortedBy: >), [range.lowerBound]) + + XCTAssertEqualSequences(input.max(count: 5, sortedBy: <), range.suffix(5)) + XCTAssertEqualSequences( + input.max(count: 5, sortedBy: >), + range.prefix(5).reversed()) + + XCTAssertEqualSequences( + input.max(count: 500, sortedBy: <), + range.suffix(500)) + XCTAssertEqualSequences( + input.max(count: 500, sortedBy: >), + range.prefix(500).reversed()) + + XCTAssertEqualSequences(input.max(count: 1000, sortedBy: <), range) + XCTAssertEqualSequences( + input.max(count: 1000, sortedBy: >), + range.reversed()) + } + + func testStability() { + assertStability([1,1,1,2,5,7,3,6,2,5,7,3,6], withCount: 3) + assertStability([1,1,1,2,5,7,3,6,2,5,7,3,6], withCount: 6) + assertStability([1,1,1,2,5,7,3,6,2,5,7,3,6], withCount: 20) + assertStability([1,1,1,2,5,7,3,6,2,5,7,3,6], withCount: 1000) + assertStability(Array(repeating: 0, count: 100), withCount: 0) + assertStability(Array(repeating: 0, count: 100), withCount: 1) + assertStability(Array(repeating: 0, count: 100), withCount: 2) + assertStability(Array(repeating: 0, count: 100), withCount: 5) + assertStability(Array(repeating: 0, count: 100), withCount: 20) + assertStability(Array(repeating: 0, count: 100), withCount: 100) + assertStability(Array(repeating: 1, count: 50) + Array(repeating: 0, count: 50), withCount: 2) + assertStability(Array(repeating: 1, count: 50) + Array(repeating: 0, count: 50), withCount: 5) + assertStability(Array(repeating: 1, count: 50) + Array(repeating: 0, count: 50), withCount: 20) + assertStability(Array(repeating: 1, count: 50) + Array(repeating: 0, count: 50), withCount: 50) + assertStability([0,0], withCount: 1) + assertStability([0,0], withCount: 2) + assertStability([0,1,0,1,0,1], withCount: 2) + assertStability([0,1,0,1,0,1], withCount: 6) + assertStability([0,0,0,1,1,1], withCount: 1) + assertStability([0,0,0,1,1,1], withCount: 3) + assertStability([0,0,0,1,1,1], withCount: 4) + assertStability([0,0,0,1,1,1], withCount: 6) + assertStability([1,1,1,0,0,0], withCount: 1) + assertStability([1,1,1,0,0,0], withCount: 3) + assertStability([1,1,1,0,0,0], withCount: 4) + assertStability([1,1,1,0,0,0], withCount: 6) + assertStability([1,1,1,0,0,0], withCount: 5) + } + + func assertStability( + _ actual: [Int], + withCount count: Int + ) { + func stableOrder( + a: (offset: Int, element: Int), + b: (offset: Int, element: Int)) -> Bool + { + a.element == b.element + ? a.offset < b.offset + : a.element < b.element + } + + do { + let sorted = actual.enumerated() + .min(count: count) { $0.element < $1.element } + XCTAssert(sorted.isSorted(by: stableOrder)) + } + + do { + let sorted = actual.enumerated() + .max(count: count) { $0.element < $1.element } + XCTAssert(sorted.isSorted(by: stableOrder)) + } + } +} diff --git a/Tests/SwiftAlgorithmsTests/SortedPrefixTests.swift b/Tests/SwiftAlgorithmsTests/SortedPrefixTests.swift deleted file mode 100644 index 17c2161..0000000 --- a/Tests/SwiftAlgorithmsTests/SortedPrefixTests.swift +++ /dev/null @@ -1,301 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift Algorithms open source project -// -// Copyright (c) 2020 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// -//===----------------------------------------------------------------------===// - -import XCTest -import Algorithms - -final class SortedPrefixTests: XCTestCase { - func testEmpty() { - let array = [Int]() - XCTAssertEqual(array.sortedPrefix(0), []) - } - - func testSortedPrefixWithOrdering() { - let array: [Int] = [20, 1, 4, 70, 100, 2, 3, 7, 90] - - XCTAssertEqual(array.sortedPrefix(0, by: >), []) - XCTAssertEqual( - array.sortedPrefix(1, by: >), - [100] - ) - - XCTAssertEqual( - array.sortedPrefix(5, by: >), - [100, 90, 70, 20, 7] - ) - - XCTAssertEqual( - array.sortedPrefix(9, by: >), - [100, 90, 70, 20, 7, 4, 3, 2, 1] - ) - - XCTAssertEqual([1].sortedPrefix(0, by: <), []) - XCTAssertEqual([1].sortedPrefix(0, by: >), []) - XCTAssertEqual([1].sortedPrefix(1, by: <), [1]) - XCTAssertEqual([1].sortedPrefix(1, by: >), [1]) - XCTAssertEqual([0, 1].sortedPrefix(1, by: <), [0]) - XCTAssertEqual([1, 0].sortedPrefix(1, by: <), [0]) - XCTAssertEqual([1, 0].sortedPrefix(2, by: <), [0, 1]) - XCTAssertEqual([0, 1].sortedPrefix(1, by: >), [1]) - XCTAssertEqual([1, 0].sortedPrefix(1, by: >), [1]) - XCTAssertEqual([1, 0].sortedPrefix(2, by: >), [1, 0]) - - XCTAssertEqual( - [1, 2, 3, 4, 7, 20, 70, 90, 100].sortedPrefix(5, by: <), - [1, 2, 3, 4, 7] - ) - - XCTAssertEqual( - [1, 2, 3, 4, 7, 20, 70, 90, 100].sortedPrefix(5, by: >), - [100, 90, 70, 20, 7] - ) - - XCTAssertEqual( - [1, 2, 3, 4, 7, 20, 70, 90, 100].sortedPrefix(5, by: >), - [100, 90, 70, 20, 7] - ) - - XCTAssertEqual( - [1, 2, 3, 4, 7, 20, 70, 90, 100].sortedPrefix(5, by: <), - [1, 2, 3, 4, 7] - ) - - XCTAssertEqual( - [4, 5, 6, 1, 2, 3].sortedPrefix(3, by: <), - [1, 2, 3] - ) - - XCTAssertEqual( - [4, 5, 9, 8, 7, 6].sortedPrefix(3, by: <), - [4, 5, 6] - ) - - XCTAssertEqual( - [4, 3, 2, 1].sortedPrefix(1, by: <), - [1] - ) - - XCTAssertEqual( - [4, 2, 1, 3].sortedPrefix(3, by: >), - [4, 3, 2] - ) - - XCTAssertEqual( - [4, 2, 1, 3].sortedPrefix(3, by: <), - [1, 2, 3] - ) - } - - func testSortedPrefixComparable() { - let array: [Int] = [20, 1, 4, 70, 100, 2, 3, 7, 90] - - XCTAssertEqual(array.sortedPrefix(0), []) - - XCTAssertEqual( - array.sortedPrefix(1), - [1] - ) - - XCTAssertEqual( - array.sortedPrefix(5), - [1, 2, 3, 4, 7] - ) - - XCTAssertEqual( - array.sortedPrefix(9), - [1, 2, 3, 4, 7, 20, 70, 90, 100] - ) - } - - func testSortedPrefixWithHugePrefix() { - XCTAssertEqual( - [4, 2, 1, 3].sortedPrefix(.max), - [1, 2, 3, 4] - ) - } - - func testSortedPrefixWithHugeInput() { - let input = (1...1000).shuffled() - - XCTAssertEqual( - input.sortedPrefix(0, by: <), - [] - ) - - XCTAssertEqual( - input.sortedPrefix(0, by: >), - [] - ) - - XCTAssertEqual( - input.sortedPrefix(1, by: <), - [1] - ) - - XCTAssertEqual( - input.sortedPrefix(1, by: >), - [1000] - ) - - XCTAssertEqual( - input.sortedPrefix(5, by: <), - [1, 2, 3, 4, 5] - ) - - XCTAssertEqual( - input.sortedPrefix(5, by: >), - [1000, 999, 998, 997, 996] - ) - - XCTAssertEqual( - input.sortedPrefix(10, by: <), - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] - ) - - XCTAssertEqual( - input.sortedPrefix(10, by: >), - [1000, 999, 998, 997, 996, 995, 994, 993, 992, 991] - ) - - XCTAssertEqual( - input.sortedPrefix(50, by: <), - Array((1...50)) - ) - - XCTAssertEqual( - input.sortedPrefix(50, by: >), - Array((1...1000).reversed().prefix(50)) - ) - - XCTAssertEqual( - input.sortedPrefix(250, by: <), - Array((1...250)) - ) - - XCTAssertEqual( - input.sortedPrefix(250, by: >), - Array((1...1000).reversed().prefix(250)) - ) - - XCTAssertEqual( - input.sortedPrefix(500, by: <), - Array((1...500)) - ) - - XCTAssertEqual( - input.sortedPrefix(500, by: >), - Array((1...1000).reversed().prefix(500)) - ) - - XCTAssertEqual( - input.sortedPrefix(750, by: <), - Array((1...750)) - ) - - XCTAssertEqual( - input.sortedPrefix(750, by: >), - Array((1...1000).reversed().prefix(750)) - ) - - XCTAssertEqual( - input.sortedPrefix(1000, by: <), - Array((1...1000)) - ) - - XCTAssertEqual( - input.sortedPrefix(1000, by: >), - (1...1000).reversed() - ) - - XCTAssertEqual( - ([0] + Array(repeating: 1, count: 100)).sortedPrefix(1, by: <), - [0] - ) - - XCTAssertEqual( - ([1] + Array(repeating: 0, count: 100)).sortedPrefix(1, by: <), - [0] - ) - - XCTAssertEqual( - ([0] + Array(repeating: 1, count: 100)).sortedPrefix(2, by: <), - [0, 1] - ) - - XCTAssertEqual( - ([1] + Array(repeating: 0, count: 100)).sortedPrefix(2, by: <), - [0, 0] - ) - - XCTAssertEqual( - ([1] + Array(repeating: 1, count: 100)).sortedPrefix(1, by: >), - [1] - ) - - XCTAssertEqual( - ([0] + Array(repeating: 1, count: 100)).sortedPrefix(1, by: >), - [1] - ) - - XCTAssertEqual( - ([1] + Array(repeating: 0, count: 100)).sortedPrefix(2, by: >), - [1, 0] - ) - - XCTAssertEqual( - ([0] + Array(repeating: 1, count: 100)).sortedPrefix(2, by: >), - [1, 1] - ) - } - - func testStability() { - assertStability([1,1,1,2,5,7,3,6,2,5,7,3,6], withPrefix: 3) - assertStability([1,1,1,2,5,7,3,6,2,5,7,3,6], withPrefix: 6) - assertStability([1,1,1,2,5,7,3,6,2,5,7,3,6], withPrefix: 20) - assertStability([1,1,1,2,5,7,3,6,2,5,7,3,6], withPrefix: 1000) - assertStability(Array(repeating: 0, count: 100), withPrefix: 0) - assertStability(Array(repeating: 0, count: 100), withPrefix: 1) - assertStability(Array(repeating: 0, count: 100), withPrefix: 2) - assertStability(Array(repeating: 0, count: 100), withPrefix: 5) - assertStability(Array(repeating: 0, count: 100), withPrefix: 20) - assertStability(Array(repeating: 0, count: 100), withPrefix: 100) - assertStability(Array(repeating: 1, count: 50) + Array(repeating: 0, count: 50), withPrefix: 2) - assertStability(Array(repeating: 1, count: 50) + Array(repeating: 0, count: 50), withPrefix: 5) - assertStability(Array(repeating: 1, count: 50) + Array(repeating: 0, count: 50), withPrefix: 20) - assertStability(Array(repeating: 1, count: 50) + Array(repeating: 0, count: 50), withPrefix: 50) - assertStability([0,0], withPrefix: 1) - assertStability([0,0], withPrefix: 2) - assertStability([0,1,0,1,0,1], withPrefix: 2) - assertStability([0,1,0,1,0,1], withPrefix: 6) - assertStability([0,0,0,1,1,1], withPrefix: 1) - assertStability([0,0,0,1,1,1], withPrefix: 3) - assertStability([0,0,0,1,1,1], withPrefix: 4) - assertStability([0,0,0,1,1,1], withPrefix: 6) - assertStability([1,1,1,0,0,0], withPrefix: 1) - assertStability([1,1,1,0,0,0], withPrefix: 3) - assertStability([1,1,1,0,0,0], withPrefix: 4) - assertStability([1,1,1,0,0,0], withPrefix: 6) - assertStability([1,1,1,0,0,0], withPrefix: 5) - } - - func assertStability( - _ actual: [Int], - withPrefix prefixCount: Int - ) { - let indexed = actual.enumerated() - let sorted = indexed.map { $0 }.sortedPrefix(prefixCount) { $0.element < $1.element } - - for element in Set(actual) { - let filtered = sorted.filter { $0.element == element }.map(\.offset) - XCTAssertEqual(filtered, filtered.sorted()) - } - } -}