Skip to content

Instantly share code, notes, and snippets.

@mredig
Created May 29, 2019 15:43
Show Gist options
  • Save mredig/8beeed9416bce7f1fea6001baffec0be to your computer and use it in GitHub Desktop.
Save mredig/8beeed9416bce7f1fea6001baffec0be to your computer and use it in GitHub Desktop.
import Cocoa
extension Int {
static func anotherRandom(_ range: Range<Int>) -> Int {
let floor = range.lowerBound
guard var ceiling = range.last else { fatalError("No last value in range") }
ceiling += 1
let normalCeiling = ceiling - floor
let rando = Int(arc4random_uniform(UInt32(normalCeiling)))
return rando + floor
}
}
extension Array {
mutating func uniformRandomShuffle() {
for index in 0..<self.count {
let newIndex = Int.anotherRandom(0..<self.count)
(self[index], self[newIndex]) = (self[newIndex], self[index])
}
}
}
func confirmUniformity() {
let iterations = 10000
// this is setting up a map of a count of where each value appears after each shuffle
let individualTracker = (0...9).map { _ in 0 }
var totalTracker = (0...9).map { _ in individualTracker }
for _ in 1...iterations {
var arrayToShuffle = Array(0...9)
arrayToShuffle.uniformRandomShuffle()
for (index, value) in arrayToShuffle.enumerated() {
totalTracker[value][index] += 1
}
}
for (value, counter) in totalTracker.enumerated() {
print(value, counter)
}
}
// every value should be roughly around 1/10 of iterations from the confirmation func
confirmUniformity()
@mredig
Copy link
Author

mredig commented May 29, 2019

I've realized that this isn't actually uniform, so scratch the uniformity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment