作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在创建一个简单的测验应用程序。有四种选择,选择的位置是随机生成的。设置了四个 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
}
最佳答案
一个非常的常用方法是“随机”答案。那么你不必做任何if
s:
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/
我尝试执行一些深度学习应用程序并得到一个模块 'tensorflow' has no attribute 'random_uniform' 错误。在 CPU 上,代码运行良好,但速度非常慢。为了在 G
下面的代码是我用来测试性能的: import time import numpy as np import tensorflow as tf t = time.time() for i in rang
我是一名优秀的程序员,十分优秀!