-
Notifications
You must be signed in to change notification settings - Fork 446
/
Copy pathRandomSample.swift
264 lines (231 loc) · 8.72 KB
/
RandomSample.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
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// For log(_:) and root(_:_:)
#if ALGORITHMS_DARWIN_ONLY
internal import Darwin
extension Double {
@_transparent
internal static func root(_ x: Double, _ n: Int) -> Double {
guard x >= 0 || n % 2 != 0 else { return .nan }
if n == 3 { return cbrt(x) }
return Double(signOf: x, magnitudeOf: pow(x.magnitude, 1/Double(n)))
}
@_transparent
internal static func log(_ x: Double) -> Double {
Darwin.log(x)
}
@_transparent
internal static func log(onePlus x: Double) -> Double {
Darwin.log1p(x)
}
}
#elseif swift(>=5.11)
internal import RealModule
#elseif swift(>=5.10)
import RealModule
#else
@_implementationOnly
import RealModule
#endif
//===----------------------------------------------------------------------===//
// randomStableSample(count:)
//===----------------------------------------------------------------------===//
extension Collection {
/// Randomly selects the specified number of elements from this collection,
/// maintaining their relative order.
///
/// - Parameters:
/// - k: The number of elements to randomly select.
/// - rng: The random number generator to use for the sampling.
/// - Returns: An array of `k` random elements. If `k` is greater than this
/// collection's count, then this method returns the full collection.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public func randomStableSample<G: RandomNumberGenerator>(
count k: Int, using rng: inout G
) -> [Element] {
guard k > 0 else { return [] }
var remainingCount = count
guard k < remainingCount else { return Array(self) }
var result: [Element] = []
result.reserveCapacity(k)
var i = startIndex
var countToSelect = k
while countToSelect > 0 {
let r = Int.random(in: 0..<remainingCount, using: &rng)
if r < countToSelect {
result.append(self[i])
countToSelect -= 1
}
formIndex(after: &i)
remainingCount -= 1
}
return result
}
/// Randomly selects the specified number of elements from this collection,
/// maintaining their relative order.
///
/// This method is equivalent to calling `randomStableSample(k:using:)`,
/// passing in the system's default random generator.
///
/// - Parameter k: The number of elements to randomly select.
/// - Returns: An array of `k` random elements. If `k` is greater than this
/// collection's count, then this method returns the full collection.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public func randomStableSample(count k: Int) -> [Element] {
var g = SystemRandomNumberGenerator()
return randomStableSample(count: k, using: &g)
}
}
//===----------------------------------------------------------------------===//
// randomSample(count:)
//===----------------------------------------------------------------------===//
// These methods use Algorithm L, described in "Reservoir-Sampling
// Algorithms of Time Complexity O(n(1 + log(N/n)))":
// https://dl.acm.org/doi/pdf/10.1145/198429.198435
@usableFromInline
internal func nextW<G: RandomNumberGenerator>(
k: Int, using rng: inout G
) -> Double {
Double.root(.random(in: 0..<1, using: &rng), k)
}
@usableFromInline
internal func nextOffset<G: RandomNumberGenerator>(
w: Double, using rng: inout G
) -> Int {
let offset = Double.log(.random(in: 0..<1, using: &rng)) / .log(onePlus: -w)
return offset < Double(Int.max) ? Int(offset) : Int.max
}
extension Collection {
/// Randomly selects the specified number of elements from this collection.
///
/// - Parameters:
/// - k: The number of elements to randomly select.
/// - rng: The random number generator to use for the sampling.
/// - Returns: An array of `k` random elements. The returned elements may be
/// in any order. If `k` is greater than this collection's count, then this
/// method returns the full collection.
///
/// - Complexity: O(*k*), where *k* is the number of elements to select, if
/// the collection conforms to `RandomAccessCollection`. Otherwise, O(*n*),
/// where *n* is the length of the collection.
@inlinable
public func randomSample<G: RandomNumberGenerator>(
count k: Int, using rng: inout G
) -> [Element] {
guard k > 0 else { return [] }
var w = 1.0
var result: [Element] = []
result.reserveCapacity(k)
// Fill the reservoir with the first `k` elements.
var i = startIndex
while i != endIndex, result.count < k {
result.append(self[i])
formIndex(after: &i)
}
while i != endIndex {
// Calculate the next value of w.
w *= nextW(k: k, using: &rng)
// Find index of the next element to swap into the reservoir.
let offset = nextOffset(w: w, using: &rng)
i = index(i, offsetBy: offset, limitedBy: endIndex) ?? endIndex
if i != endIndex {
// Swap selected element with a randomly chosen one in the reservoir.
let j = Int.random(in: 0..<result.count, using: &rng)
result[j] = self[i]
formIndex(after: &i)
}
}
// FIXME: necessary?
result.shuffle(using: &rng)
return result
}
/// Randomly selects the specified number of elements from this collection.
///
/// This method is equivalent to calling `randomSample(k:using:)`, passing in
/// the system's default random generator.
///
/// - Parameter k: The number of elements to randomly select.
/// - Returns: An array of `k` random elements. The returned elements may be
/// in any order. If `k` is greater than this collection's count, then this
/// method returns the full collection.
///
/// - Complexity: O(*k*), where *k* is the number of elements to select, if
/// the collection conforms to `RandomAccessCollection`. Otherwise, O(*n*),
/// where *n* is the length of the collection.
@inlinable
public func randomSample(count k: Int) -> [Element] {
var g = SystemRandomNumberGenerator()
return randomSample(count: k, using: &g)
}
}
extension Sequence {
/// Randomly selects the specified number of elements from this sequence.
///
/// - Parameters:
/// - k: The number of elements to randomly select.
/// - rng: The random number generator to use for the sampling.
/// - Returns: An array of `k` random elements. The returned elements may be
/// in any order. If `k` is greater than this sequence's count, then this
/// method returns the full sequence.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func randomSample<G: RandomNumberGenerator>(
count k: Int, using rng: inout G
) -> [Element] {
guard k > 0 else { return [] }
var w = 1.0
var result: [Element] = []
result.reserveCapacity(k)
// Fill the reservoir with the first `k` elements.
var iterator = makeIterator()
while result.count < k, let el = iterator.next() {
result.append(el)
}
while true {
// Calculate the next value of w.
w *= nextW(k: k, using: &rng)
// Find the offset of the next element to swap into the reservoir.
var offset = nextOffset(w: w, using: &rng)
// Skip over `offset` elements to find the selected element.
while offset > 0, let _ = iterator.next() {
offset -= 1
}
guard let nextElement = iterator.next() else { break }
// Swap selected element with a randomly chosen one in the reservoir.
let j = Int.random(in: 0..<result.count, using: &rng)
result[j] = nextElement
}
// FIXME: necessary?
result.shuffle(using: &rng)
return result
}
/// Randomly selects the specified number of elements from this sequence.
///
/// This method is equivalent to calling `randomSample(k:using:)`, passing in
/// the system's default random generator.
///
/// - Parameter k: The number of elements to randomly select.
/// - Returns: An array of `k` random elements. The returned elements may be
/// in any order. If `k` is greater than this sequence's count, then this
/// method returns the full sequence.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func randomSample(count k: Int) -> [Element] {
var g = SystemRandomNumberGenerator()
return randomSample(count: k, using: &g)
}
}