Created
January 3, 2017 19:50
-
-
Save harlanhaskins/6d37d9adc751e7d03bb2e7c3f06da7de to your computer and use it in GitHub Desktop.
Shuffle program for Trill in the iOS app
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
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