创建一个随机数数组,不让一个数字在一行中重复两次



我对这一切都是新手,所以我希望这一切都有意义。我想在按下按钮时显示随机图像,而不让同一图像连续出现两次。我在这个网站上发现了类似的问题,答案也有所帮助,但我的代码中仍然存在我不理解的错误。

这是我在类顶部的图像数组的代码:

var imageArray:[String] = ["yes", "no", "indeed", "nope", "ofCourse", "noWay"]

以下是我在按钮IBAction下用于随机数的代码:(可能有我不知道的错误,就像我之前说的,我是一个noob)

 var currentNo: UInt32 = 0
    func randomNumber(maximum: UInt32) -> Int {
        var randomNumber: UInt32
        do {
            randomNumber = (arc4random_uniform(6))
        }while currentNo == randomNumber
        currentNo = randomNumber
        return Int(randomNumber)
    }
    var imageString:String = self.imageArray [randomNumber]
    self.iPhoneImage.image = UIImage(named: imageString)

我得到一个错误在这行:

var imageString:String = self.imageArray [randomNumber]

上面写着

"无法订阅具有类型索引的'[String]'类型的值'(UInt32)->Int'

如果你不想重复随机项目,你可以删除它,并在下一次抽奖后将其追加,如下所示:

var imageArray: [String] = ["yes", "no", "indeed", "nope", "ofCourse", "noWay"]
var random: Int {
    return Int(arc4random_uniform(UInt32(imageArray.count)))
}
var lastImage = ""
var imageName: String {
    let newImage = imageArray.removeAtIndex(random)
    if lastImage != "" {
        imageArray.append(lastImage)
    }
    lastImage = newImage
    return newImage
}

测试

println(imageName)  // "ofCourse"
println(imageName)  // "no"
println(imageName)  // "yes"
println(imageName)  // "nope"
println(imageName)  // "indeed"
println(imageName)  // "noWay" 
println(imageName)  // "ofCourse"
println(imageName)  // "noWay
println(imageName)  // "nope"
println(imageName)  // "ofCourse"
println(imageName)  // "noWay"
println(imageName)  // "yes"
println(imageName)  // "ofCourse"
println(imageName)  // "indeed"
println(imageName)  // "yes"
println(imageName)  // "nope"
println(imageName)  // "noWay"
println(imageName)  // "no"
println(imageName)  // "noWay"

这将正常工作:

var imageString:String = self.imageArray[randomNumber(6)]

正如您在函数声明func randomNumber(maximum: UInt32) -> Int中看到的,这意味着您的函数接受类型为UInt32的参数maximum并返回Int

但是您使用的函数类似于self.imageArray[randomNumber],您希望使用randomNumber函数访问imageArray中的元素。

但是你的函数接受你没有指定的参数,所以你可以这样使用函数randomNumber(6),其中6是一个最大值。

您可以根据需要更改您的最大值。

对于GameKit,实际上有一个内置的随机分布,它可以为您做到这一点,同时仍然是均匀和非常随机的:

import GameplayKit
let imageArray = ["yes", "no", "indeed", "nope", "ofCourse", "noWay"]
let randomDistribution = GKShuffledDistribution(lowestValue: 0, highestValue: imageArray.count - 1)
func randomItem() -> String {
    return imageArray[randomDistribution.nextInt()]
}

我建议将其封装到自己的类型中:

struct RandomNonRepeating<Element> {
    let values : [Element]
    let distribution : GKRandomDistribution
    init(values : [Element]) {
        self.values = values
        distribution = GKShuffledDistribution(
            lowestValue: 0, highestValue: values.count - 1)
    }
    func next() -> Element {
        return values[distribution.nextInt()]
    }
}

可以这样使用:

let x = RandomNonRepeating(values: [1, 2, 3, 4, 5])
for _ in 0...30 {
    x.next()
}

给出

4
3
2
1
5
2
4
3
1
5
4
3
2
1
5
3
1
2
4
5
4
1
3
2
5
4
3
1
2
5
3

相关内容

最新更新