2024-08-23 16:55:59 +10:00
|
|
|
public extension MutableCollection {
|
|
|
|
mutating func shuffle<T: RandomProvider>(using provider: inout T) {
|
2024-09-05 21:46:49 +10:00
|
|
|
let count = self.count
|
|
|
|
guard count > 1 else {
|
2024-08-23 16:55:59 +10:00
|
|
|
return
|
|
|
|
}
|
2024-09-05 21:46:49 +10:00
|
|
|
for (first, remaining) in zip(self.indices, stride(from: count, to: 1, by: -1)) {
|
2024-08-23 16:55:59 +10:00
|
|
|
let i = self.index(first, offsetBy: provider.next(in: remaining))
|
|
|
|
self.swapAt(first, i)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public extension Sequence {
|
|
|
|
func shuffled<T: RandomProvider>(using provider: inout T) -> [Self.Element] {
|
|
|
|
var copy = Array(self)
|
|
|
|
copy.shuffle(using: &provider)
|
|
|
|
return copy
|
|
|
|
}
|
|
|
|
}
|