mirror of
https://github.com/pointfreeco/swift-composable-architecture.git
synced 2025-12-20 09:11:33 +01:00
Add implementation of shuffle on IdentifiedArray (#254)
* add shuffle * Update Tests/ComposableArchitectureTests/IdentifiedArrayTests.swift * Update IdentifiedArrayTests.swift Co-authored-by: Stephen Celis <stephen.celis@gmail.com>
This commit is contained in:
committed by
GitHub
parent
86843a4dcc
commit
fffefb9c22
@@ -190,6 +190,15 @@ where ID: Hashable {
|
||||
try areInIncreasingOrder(self.dictionary[$0]!, self.dictionary[$1]!)
|
||||
}
|
||||
}
|
||||
|
||||
public mutating func shuffle<T>(using generator: inout T) where T : RandomNumberGenerator {
|
||||
ids.shuffle(using: &generator)
|
||||
}
|
||||
|
||||
public mutating func shuffle() {
|
||||
var rng = SystemRandomNumberGenerator()
|
||||
self.shuffle(using: &rng)
|
||||
}
|
||||
}
|
||||
|
||||
extension IdentifiedArray: CustomDebugStringConvertible {
|
||||
|
||||
@@ -195,4 +195,36 @@ final class IdentifiedArrayTests: XCTestCase {
|
||||
], array)
|
||||
|
||||
}
|
||||
|
||||
// Account for randomness API changes in Swift 5.3 (https://twitter.com/mbrandonw/status/1262388756847505410)
|
||||
// TODO: Try swapping out the LCRNG for a Xoshiro generator
|
||||
#if swift(>=5.3)
|
||||
func testShuffle() {
|
||||
struct User: Equatable, Identifiable {
|
||||
let id: Int
|
||||
var name: String
|
||||
}
|
||||
|
||||
var array: IdentifiedArray = [
|
||||
User(id: 1, name: "Blob"),
|
||||
User(id: 2, name: "Blob Jr."),
|
||||
User(id: 3, name: "Blob Sr."),
|
||||
User(id: 4, name: "Foo Jr."),
|
||||
User(id: 5, name: "Bar Jr."),
|
||||
]
|
||||
var lcrng = LCRNG(seed: 0)
|
||||
array.shuffle(using: &lcrng)
|
||||
XCTAssertEqual(
|
||||
[
|
||||
User(id: 1, name: "Blob"),
|
||||
User(id: 3, name: "Blob Sr."),
|
||||
User(id: 5, name: "Bar Jr."),
|
||||
User(id: 4, name: "Foo Jr."),
|
||||
User(id: 2, name: "Blob Jr.")
|
||||
],
|
||||
array.elements
|
||||
)
|
||||
XCTAssertEqual([1, 3, 5, 4, 2], array.ids)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
15
Tests/ComposableArchitectureTests/LCRNG.swift
Normal file
15
Tests/ComposableArchitectureTests/LCRNG.swift
Normal file
@@ -0,0 +1,15 @@
|
||||
/// A linear congruential random number generator.
|
||||
public struct LCRNG: RandomNumberGenerator {
|
||||
public var seed: UInt64
|
||||
|
||||
@inlinable
|
||||
public init(seed: UInt64) {
|
||||
self.seed = seed
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func next() -> UInt64 {
|
||||
seed = 2862933555777941757 &* seed &+ 3037000493
|
||||
return seed
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user