gpt4 book ai didi

swift - 如何在不重复先前随机数的情况下在Swift中生成随机数?

转载 作者:IT王子 更新时间:2023-10-29 05:28:36 24 4
gpt4 key购买 nike

我对 Swift 和一般的编程逻辑还很陌生,所以请多多包涵

如何在 Swift 中生成 0 到 9 之间的随机数而不重复上次生成的数字?因为同一个数字不会连续出现两次。

最佳答案

我的解决方案,我觉得很容易理解

var nums = [0,1,2,3,4,5,6,7,8,9]

while nums.count > 0 {

// random key from array
let arrayKey = Int(arc4random_uniform(UInt32(nums.count)))

// your random number
let randNum = nums[arrayKey]

// make sure the number isnt repeated
nums.swapAt(arrayKey, nums.count-1)
nums.removeLast()
}

关于swift - 如何在不重复先前随机数的情况下在Swift中生成随机数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27541145/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com