gpt4 book ai didi

ios - 使用 arc4random_uniform() 的简单测验

转载 作者:行者123 更新时间:2023-11-28 10:54:56 25 4
gpt4 key购买 nike

我正在创建一个简单的测验应用程序。有四种选择,选择的位置是随机生成的。设置了四个 UILabel 以显示选项。

我写了下面的代码,它通常运行良好,但有时会显示相同的选项。

例)2017 2015 2015 1700

错误应该是 for 循环,但我想不通。

let questions = ["What year is now?"]
let answers = [["2017", "2015", "1000", "1700"]]
var rightAnswerPlacement:UInt32 = 0
var currentQuestion = 0

//Function that displays new question
func newQuestion()
{
lbl.text = questions[currentQuestion]
rightAnswerPlacement = arc4random_uniform(4)+1
// Create a button
var button:UIButton = UIButton()
var x = 1
for i in 1...4
{
//Create a button
button = view.viewWithTag(i) as! UIButton
if (i == Int(rightAnswerPlacement))
{
button.setTitle(answers[currentQuestion][0], for: .normal)
}
else
{
button.setTitle(answers[currentQuestion][x], for: .normal)
x = 2
}
}
button.setTitle(answers[currentQuestion][3], for: .normal)
currentQuestion += 1
}

最佳答案

一个非常的常用方法是“随机”答案。那么你不必做任何ifs:

let questions = [
"What year is now?",
"What is your favorite color?"
]

let answers = [
["2017", "2015", "1000", "1700"],
["Blue", "Red", "Yellow", "Green"]
]

var currentQuestion = 0

//Function that displays new question
func newQuestion()
{
// get the current question text
let thisQuestion = questions[currentQuestion]

// get a "shuffled" array of the current answers
let theseAnswers = answers[currentQuestion].shuffled()

lbl.text = thisQuestion

// loop through the shuffled answers, setting the button titles
for (i, answer) in theseAnswers.enumerated() {
if let button = view.viewWithTag(i) as? UIButton {
button.setTitle(answer, for: .normal)
}
}

}

现在,每次调用 newQuestion() 时,答案都会随机排列。


有很多数组改组的例子 - 这是一个很好的例子(来自“Nate Cook”这里... How do I shuffle an array in Swift?):

extension MutableCollection where Indices.Iterator.Element == Index {
/// Shuffles the contents of this collection.
mutating func shuffle() {
let c = count
guard c > 1 else { return }

for (firstUnshuffled , unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) {
let d: IndexDistance = numericCast(arc4random_uniform(numericCast(unshuffledCount)))
guard d != 0 else { continue }
let i = index(firstUnshuffled, offsetBy: d)
swap(&self[firstUnshuffled], &self[i])
}
}
}

extension Sequence {
/// Returns an array with the contents of this sequence, shuffled.
func shuffled() -> [Iterator.Element] {
var result = Array(self)
result.shuffle()
return result
}
}

关于ios - 使用 arc4random_uniform() 的简单测验,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44206627/

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