Skip to content

Commit

Permalink
Make Array init(randomCount:) faster
Browse files Browse the repository at this point in the history
  • Loading branch information
nvzqz committed Jan 21, 2017
1 parent 1635d9a commit 8dc67b0
Showing 1 changed file with 3 additions and 15 deletions.
18 changes: 3 additions & 15 deletions Sources/RandomKit/Extensions/Swift/Array+RandomKit.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ extension Array where Element: Random {
///
/// Although safety is not guaranteed, `init(unsafeRandomCount:)` is *significantly* faster than this.
public init<R: RandomGenerator>(randomCount: Int, using randomGenerator: inout R) {
self = (0 ..< randomCount).map { _ in Element.random(using: &randomGenerator) }
self.init(Element.randoms(limitedBy: randomCount, using: &randomGenerator))
}

}
Expand All @@ -53,13 +53,7 @@ extension Array where Element: RandomWithinRange {

/// Construct an Array of random elements from within the range.
public init<R: RandomGenerator>(randomCount: Int, within range: Range<Element>, using randomGenerator: inout R) {
if range.isEmpty || randomCount <= 0 {
self = []
} else {
self = CountableRange(uncheckedBounds: (0, randomCount)).map { _ in
Element.random(within: range, using: &randomGenerator).unsafelyUnwrapped
}
}
self.init(Element.randoms(limitedBy: randomCount, within: range, using: &randomGenerator))
}

}
Expand All @@ -68,13 +62,7 @@ extension Array where Element: RandomWithinClosedRange {

/// Construct an Array of random elements from within the closed range.
public init<R: RandomGenerator>(randomCount: Int, within closedRange: ClosedRange<Element>, using randomGenerator: inout R) {
if randomCount <= 0 {
self = []
} else {
self = CountableRange(uncheckedBounds: (0, randomCount)).map { _ in
Element.random(within: closedRange, using: &randomGenerator)
}
}
self.init(Element.randoms(limitedBy: randomCount, within: closedRange, using: &randomGenerator))
}

}
Expand Down

0 comments on commit 8dc67b0

Please sign in to comment.