From eb93e564d469961a3bcc6a890fab6f4ee95ae24e Mon Sep 17 00:00:00 2001 From: Nate Cook Date: Mon, 7 Mar 2022 18:16:57 -0600 Subject: [PATCH] Add Sequence.randomElement() The stdlib's randomElement() method extends Collection, since it operates by selecting a random index. This adds randomElement() as a Sequence method, specializing the reservoir sampling algorithm from randomSample(count:) for a count of 1. --- Sources/Algorithms/RandomSample.swift | 58 +++++++++++++++++++ .../RandomSampleTests.swift | 33 +++++++++++ 2 files changed, 91 insertions(+) diff --git a/Sources/Algorithms/RandomSample.swift b/Sources/Algorithms/RandomSample.swift index 933269d..0e2c365 100644 --- a/Sources/Algorithms/RandomSample.swift +++ b/Sources/Algorithms/RandomSample.swift @@ -235,3 +235,61 @@ extension Sequence { return randomSample(count: k, using: &g) } } + +//===----------------------------------------------------------------------===// +// randomElement() +//===----------------------------------------------------------------------===// + +// This method is a single-element specialization of `randomSample(count:)`, +// and extends the stdlib's `randomElement()` functionality (which is available +// for collections) down to sequences. + +extension Sequence { + /// Randomly selects an element from this sequence, using the given generator + /// as the source of randomness. + /// + /// - Parameter rng: The random number generator to use for sampling. + /// - Returns: A random element. If the sequence has no elements, this method + /// returns `nil`. + /// + /// - Complexity: O(*n*), where *n* is the length of the sequence. + @inlinable + public func randomElement( + using rng: inout G + ) -> Element? { + var iterator = makeIterator() + guard var result = iterator.next() else { + return nil + } + + var w = 1.0 + while true { + w *= nextW(k: 1, using: &rng) + var offset = nextOffset(w: w, using: &rng) + while offset > 0, let _ = iterator.next() { + offset -= 1 + } + guard let nextElement = iterator.next() + else { break } + + result = nextElement + } + + return result + } + + /// Randomly selects an element from this sequence. + /// + /// This method is equivalent to calling `randomSample(using:)`, passing in + /// the system's default random generator. + /// + /// - Returns: A random element. If the sequence has no elements, this method + /// returns `nil`. + /// + /// - Complexity: O(*n*), where *n* is the length of the sequence. + @inlinable + public func randomElement() -> Element? { + var g = SystemRandomNumberGenerator() + return randomElement(using: &g) + } +} diff --git a/Tests/SwiftAlgorithmsTests/RandomSampleTests.swift b/Tests/SwiftAlgorithmsTests/RandomSampleTests.swift index 5875ac0..04147a7 100644 --- a/Tests/SwiftAlgorithmsTests/RandomSampleTests.swift +++ b/Tests/SwiftAlgorithmsTests/RandomSampleTests.swift @@ -132,4 +132,37 @@ final class RandomSampleTests: XCTestCase { almostAllZero = AlmostAllZeroGenerator(seed: 0) _ = c.randomSample(count: k, using: &almostAllZero) // must not crash } + + func testSequenceRandomElement() { + XCTAssertNil(emptySequence.randomElement()) + + let expectedRange = expectedRange(for: iterations) + let randomElements = (0..<(n*iterations)).map { _ in + s.randomElement()! + }.frequencies + XCTAssertEqual(randomElements.count, n) + XCTAssert(randomElements.values.allSatisfy { expectedRange.contains($0) }) + + let oneElementSequence = sequence(first: 0, next: { _ in nil }) + let randomOneElement = (0..