Skip to content

Instantly share code, notes, and snippets.

@harlanhaskins
Created January 3, 2017 19:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harlanhaskins/6d37d9adc751e7d03bb2e7c3f06da7de to your computer and use it in GitHub Desktop.
Save harlanhaskins/6d37d9adc751e7d03bb2e7c3f06da7de to your computer and use it in GitHub Desktop.
Shuffle program for Trill in the iOS app
foreign type Array {
foreign init() -> Array
foreign func push(_: Any)
foreign subscript(_: Int) -> Any
foreign var length: Int
}
foreign type Math {
foreign static func random() -> Double
foreign static func floor(_: Double) -> Int
}
extension Array {
/*
* A standard Fischer-Yates shuffle,
* in-place.
*/
mutating func shuffle() {
for var i = 0; i < self.length; i += 1 {
let swap = Math.floor(Math.random() *
(self.length - i) as Double) + i
let tmp = self[swap]
self[swap] = self[i]
self[i] = tmp
}
}
func shuffled() -> Array {
var copy = self.copy()
copy.shuffle()
return copy
}
func copy() -> Array {
var new_ = Array()
for var i = 0; i < self.length; i += 1 {
new_.push(i)
}
return new_
}
}
func main() {
var nums = Array()
for var i = 1; i <= 10; i += 1 {
nums.push(i)
}
print("Numbers: ")
println(nums)
print("Shuffled: ")
nums.shuffle()
let n = nums.shuffled()
println(nums)
println(n)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment