Created
May 29, 2019 15:43
-
-
Save mredig/8beeed9416bce7f1fea6001baffec0be to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've realized that this isn't actually uniform, so scratch the uniformity