mirror of
https://github.com/apple/swift-algorithms
synced 2026-11-28 04:44:20 +00:00
Fix RandomSample crash when 0 was out from random. (#70)
This commit is contained in:
1 parent
d8a11e0d51
commit
1a3c7061de
2 files changed
+34
-5
No files matched your search
@@ -94,7 +94,8 @@ internal func nextW<G: RandomNumberGenerator>(
|
||||
internal func nextOffset<G: RandomNumberGenerator>(
|
||||
w: Double, using rng: inout G
|
||||
) -> Int {
|
||||
Int(Double.log(.random(in: 0..<1, using: &rng)) / .log(1 - w))
|
||||
let offset = Double.log(.random(in: 0..<1, using: &rng)) / .log(onePlus: -w)
|
||||
return offset < Double(Int.max) ? Int(offset) : Int.max
|
||||
}
|
||||
|
||||
extension Collection {
|
||||
@@ -201,10 +202,10 @@ extension Sequence {
|
||||
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) + 1
|
||||
var offset = nextOffset(w: w, using: &rng)
|
||||
|
||||
// Skip over `offset - 1` elements to find the selected element.
|
||||
while offset > 1, let _ = iterator.next() {
|
||||
// Skip over `offset` elements to find the selected element.
|
||||
while offset > 0, let _ = iterator.next() {
|
||||
offset -= 1
|
||||
}
|
||||
guard let nextElement = iterator.next() else { break }
|
||||
|
||||
Reference in new issue
Block a user