Skip to content

Instantly share code, notes, and snippets.

@erica
Created September 20, 2016 16:01
Show Gist options
  • Save erica/aa0b1164fd82d98d73c58919d3155984 to your computer and use it in GitHub Desktop.
Save erica/aa0b1164fd82d98d73c58919d3155984 to your computer and use it in GitHub Desktop.
import Foundation
#if os(Linux)
import Glibc
#endif
struct Random {
#if os(Linux)
static var initialized = false
#endif
static func roll(max: Int) -> Int {
#if os(Linux)
if !Random.initialized {
srandom(UInt32(time(nil)))
Random.initialized = true
}
return Int(random() % max)
#else
return Int(arc4random_uniform(UInt32(max)))
#endif
}
}
extension Collection {
func permutedIndices() -> [Indices.Iterator.Element] {
typealias Index = Indices.Iterator.Element
var remainingIndices: [Index] = Array(indices)
var count = remainingIndices.count
var results: [Index] = []
(0 ..< count).forEach { _ in
defer { count -= 1 }
let index = Random.roll(max: count)
results.append(remainingIndices.remove(at: index))
}
return results
}
}
let test = ["a", "b", "c", "d"]
for idx in test.permutedIndices() {
print(test[idx])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment