Swift 筆記(九)

我的主力博客:半畝方塘


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
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章