-
Notifications
You must be signed in to change notification settings - Fork 446
/
Copy pathMinMax.swift
482 lines (447 loc) · 18 KB
/
MinMax.swift
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
//===----------------------------------------------------------------------===//
//
// 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 }
result.removeLast()
let insertionIndex =
try result.partitioningIndex { try areInIncreasingOrder(e, $0) }
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 largest 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 largestThree = 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] {
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 largestThree = 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] {
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!
"""
)
// Make sure we are within bounds.
let prefixCount = Swift.min(count, self.count)
// Do nothing if we're prefixing nothing.
guard prefixCount > 0 else {
return []
}
// 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 largest 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 largestThree = 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!
"""
)
// Make sure we are within bounds.
let suffixCount = Swift.min(count, self.count)
// Do nothing if we're suffixing nothing.
guard suffixCount > 0 else {
return []
}
// 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] {
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] {
max(count: count, sortedBy: <)
}
}
//===----------------------------------------------------------------------===//
// Simultaneous minimum and maximum evaluation
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns both the minimum and maximum elements in the sequence, using the
/// given predicate as the comparison between elements.
///
/// The predicate must be a *strict weak ordering* over the elements. That is,
/// for any elements `a`, `b`, and `c`, the following conditions must hold:
///
/// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity)
/// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are
/// both `true`, then `areInIncreasingOrder(a, c)` is also
/// `true`. (Transitive comparability)
/// - Two elements are *incomparable* if neither is ordered before the other
/// according to the predicate. If `a` and `b` are incomparable, and `b`
/// and `c` are incomparable, then `a` and `c` are also incomparable.
/// (Transitive incomparability)
///
/// This example shows how to use the `minAndMax(by:)` method on a dictionary
/// to find the key-value pair with the lowest value and the pair with the
/// highest value.
///
/// let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
/// if let extremeHues = hues.minAndMax(by: {$0.value < $1.value}) {
/// print(extremeHues.min, extremeHues.max)
/// } else {
/// print("There are no hues")
/// }
/// // Prints: "(key: "Coral", value: 16) (key: "Heliotrope", value: 296)"
///
/// - Precondition: The sequence is finite.
///
/// - Parameter areInIncreasingOrder: A predicate that returns `true` if its
/// first argument should be ordered before its second argument; otherwise,
/// `false`.
/// - Returns: A tuple with the sequence's minimum element, followed by its
/// maximum element. If the sequence provides multiple qualifying minimum
/// elements, the first equivalent element is returned; of multiple maximum
/// elements, the last is returned. If the sequence has no elements, the
/// method returns `nil`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func minAndMax(
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> (min: Element, max: Element)? {
// Check short sequences.
var iterator = makeIterator()
guard var lowest = iterator.next() else { return nil }
guard var highest = iterator.next() else { return (lowest, lowest) }
// Confirm the initial bounds.
if try areInIncreasingOrder(highest, lowest) { swap(&lowest, &highest) }
// Read the elements in pairwise. Structuring the comparisons around this
// is actually faster than loops based on extracting and testing elements
// one-at-a-time.
while var low = iterator.next() {
var high = iterator.next() ?? low
if try areInIncreasingOrder(high, low) { swap(&low, &high) }
if try areInIncreasingOrder(low, lowest) { lowest = low }
if try !areInIncreasingOrder(high, highest) { highest = high }
}
return (lowest, highest)
}
}
extension Sequence where Element: Comparable {
/// Returns both the minimum and maximum elements in the sequence.
///
/// This example finds the smallest and largest values in an array of height
/// measurements.
///
/// let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9]
/// if let (lowestHeight, greatestHeight) = heights.minAndMax() {
/// print(lowestHeight, greatestHeight)
/// } else {
/// print("The list of heights is empty")
/// }
/// // Prints: "58.5 67.5"
///
/// - Precondition: The sequence is finite.
///
/// - Returns: A tuple with the sequence's minimum element, followed by its
/// maximum element. If the sequence provides multiple qualifying minimum
/// elements, the first equivalent element is returned; of multiple maximum
/// elements, the last is returned. If the sequence has no elements, the
/// method returns `nil`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func minAndMax() -> (min: Element, max: Element)? {
minAndMax(by: <)
}
}