Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,19 @@
extension BidirectionalCollection where Self: MutableCollection
{
mutating func shuffleInPlace()
{
var index = self.index(before: self.endIndex)
while index != self.startIndex
{
// Note the use of ... below. This makes the current element eligible for being selected
let randomInt = Int.random(in: 0 ... self.distance(from: startIndex, to: index))
let randomIndex = self.index(startIndex, offsetBy: randomInt)
self.swapAt(index, randomIndex)
index = self.index(before: index)
}
}
}
var a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
a.shuffleInPlace()
print(a)

View file

@ -0,0 +1,20 @@
import func Darwin.arc4random_uniform
extension Array {
func shuffle() -> Array {
var result = self; result.shuffleInPlace(); return result
}
mutating func shuffleInPlace() {
for i in 1 ..< count { swap(&self[i], &self[Int(arc4random_uniform(UInt32(i+1)))]) }
}
}
// Swift 2.0:
print([1, 2, 3, 4, 5, 6, 7, 8, 9, 10].shuffle())
// Swift 1.x:
//println([1, 2, 3, 4, 5, 6, 7, 8, 9, 10].shuffle())

View file

@ -0,0 +1,31 @@
import func Darwin.arc4random_uniform
func shuffleInPlace<T: MutableCollectionType where T.Index: RandomAccessIndexType>(inout collection: T) {
let i0 = collection.startIndex
for i in i0.successor() ..< collection.endIndex {
let j = i0.advancedBy(numericCast(
arc4random_uniform(numericCast(
i0.distanceTo()
)+1)
))
swap(&collection[i], &collection[j])
}
}
func shuffle<T: MutableCollectionType where T.Index: RandomAccessIndexType>(collection: T) -> T {
var result = collection
shuffleInPlace(&result)
return result
}
// Swift 2.0:
print(shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
// Swift 1.x:
//println(shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))

View file

@ -0,0 +1,50 @@
import func Darwin.arc4random_uniform
// Define a protocol for shuffling:
protocol Shufflable {
@warn_unused_result (mutable_variant="shuffleInPlace")
func shuffle() -> Self
mutating func shuffleInPlace()
}
// Provide a generalized implementation of the shuffling protocol for any mutable collection with random-access index:
extension Shufflable where Self: MutableCollectionType, Self.Index: RandomAccessIndexType {
func shuffle() -> Self {
var result = self
result.shuffleInPlace()
return result
}
mutating func shuffleInPlace() {
let i0 = startIndex
for i in i0+1 ..< endIndex {
let j = i0.advancedBy(numericCast(
arc4random_uniform(numericCast(
i0.distanceTo(i)
)+1)
))
swap(&self[i], &self[j])
}
}
}
// Declare Array's conformance to Shufflable:
extension Array: Shufflable
{ /* Implementation provided by Shufflable protocol extension */ }
print([1, 2, 3, 4, 5, 6, 7, 8, 9, 10].shuffle())