不会重复自身的随机数生成器功能 [英] Random number generator function that doesn't repeat itself

查看:212
本文介绍了不会重复自身的随机数生成器功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

默认情况下,swift的随机数生成器仅返回一次相同的数字吗?

Does swift by default has a random number generator that returns the same number only once?

例如,它选择1,2,3,4,5范围内的数字.返回该随机数(假设为3).在下一个循环中,它仅从1,2,4,5中选择,依此类推.

For example it picks a number in range 1,2,3,4,5. Return that random number (lets say 3). In the next loop, it picks only from 1,2,4,5 and so on.

这就是我最终使用的.它返回一个从0-5的整数数组,并在操场上进行了测试.请注意,这是在从大量整数(而不只是6个)中进行选择时使用的.

This is what I ended up using. It returns an array of integers from 0-5 and was tested in playground. Note that this is meant to be used when you are picking from a large set of Integers and not just 6.

func generateRandomArray() -> [Int]{
    var randomImages: [Int] = [Int]()

    var newRandomNumber = Int(arc4random_uniform(UInt32(6)))

    while (randomImages.count < 6) {
        if (randomImages.contains(newRandomNumber) == false){
            randomImages.append(newRandomNumber)
        }
        newRandomNumber = Int(arc4random_uniform(UInt32(6)))
    }

    return randomImages

}

推荐答案

只需将最后一个随机数存储在变量中,然后在while循环中针对它检查下一个随机数.新的随机数与上一个随机数相同时,生成一个新的随机数.一旦生成的新随机数与最后一个随机数不同,则while循环结束,我们将更新最后一个随机数.

Just store the last random number in a variable and check the next random number against it in a while loop. While the new random number is the same as the last random number, generate a new random number. Once the new random number generated is not the same as the last random number the while loop ends and we update the last random number.

var lastRandomNumber = 0
var newRandomNumber = 0

func gernerateRandomNumber() {
    newRandomNumber = Int(arc4random_uniform(5)+1)

    while newRandomNumber == lastRandomNumber {
        newRandomNumber = Int(arc4random_uniform(5)+1)
    }

    lastRandomNumber = newRandomNumber
}

这篇关于不会重复自身的随机数生成器功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆