数组中的随机数而不连续两次重复相同的数字

数组中的随机数而不连续两次重复相同的数字

本文介绍了数组中的随机数而不连续两次重复相同的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Swift 和 SpriteKit 制作游戏,我根据数组将对象移动到随机位置.

I am making a game using Swift and SpriteKit where i move an object to random locations based on an array.

由CGPoints组成的数组:

The array that is made up of CGPoints:

let easyArray = [CGPointMake(0,0), CGPointMake(126.6,0),   CGPointMake(253.4,0), CGPointMake(0,197.5), CGPointMake(126.7,197.5), CGPointMake(253.4,197.5), CGPointMake(0,395), CGPointMake(126.7,395), CGPointMake(253.4,395)]

我用这个函数来生成一个随机数:

I use this function to generate a random number:

func randomNumber(maximum: UInt32) -> Int {

    var randomNumber = arc4random_uniform(maximum)
    while previousNumber == randomNumber {
    randomNumber = arc4random_uniform(maximum)
}
    previousNumber = randomNumber
    return Int(randomNumber)
}

我使用它根据生成的随机数移动对象:

I used this to move the object based on the random number generated:

let greenEasy = randomNumberNew(9)
let moveSelector = SKAction.moveTo(easyArray[greenEasy], duration: 0)
selector.runAction(moveSelector)

我在网上做了一些阅读,发现While"条件应该使它不会连续生成两次相同的随机数.但它仍然会发生.

I have done some reading online and found that the "While" condition should make it so that the same random number isn't generate twice in a row. But it still happens.

谁能帮我弄一下,这样我就不会连续两次得到相同的数字了?

Can anyone please help me on how to make it so i don't get the same number twice in a row?

推荐答案

下面的代码不会随机取同一个数字.

The code below doesn't random the same number.

   var currentNo: UInt32 = 0

    func randomNumber(maximum: UInt32) -> Int {

        var randomNumber: UInt32

        do {
            randomNumber = (arc4random_uniform(maximum))
        }while currentNo == randomNumber

        currentNo = randomNumber

        return Int(randomNumber)
    }

这篇关于数组中的随机数而不连续两次重复相同的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 08:36