Swift 笔记(九)

前端之家收集整理的这篇文章主要介绍了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
}
原文链接:https://www.f2er.com/swift/324486.html

猜你在找的Swift相关文章