Randomizing an array
The function below returns a random number between 0 and the given argument:
import Foundation func randomFromZeroTo(number: Int) -> Int { return Int(arc4random_uniform(UInt32(number))) }
Use it to write a function that shuffles the elements of an array in random order. This is the signature of the function:
func randomArray(array: [Int]) -> [Int]
The answer is below:
func randomArray(array: [Int]) -> [Int] { var newArray = array for index in 0..<array.count { let randomIndex = randomFromZeroTo(array.count) let value = newArray[index] newArray[index] = newArray[randomIndex] newArray[randomIndex] = value } return newArray }原文链接:https://www.f2er.com/swift/324486.html