目前,我的代码从键和值数组中吐出一个随机索引。但是索引保持不变并显示相同的键和值,但我想要它做的是显示一个随机索引迭代数组并显示另一个不等于前一个随机索引的随机索引。我怎么能实现这个呢?
这是我的代码(适用于iOS的swift):
class QuestionDetails {
let QADictionary = ["Who is Thor's brother?" : ["Atum", "Loki", "Red Norvell", "Kevin Masterson"], "What is the name of Thor's hammer?" : ["Mjolinr", "Uru", "Stormbreaker", "Thundara"], "Who is the father of Thor?" : ["Odin", "Sif", "Heimdall", "Balder"]]
}
//get question list
func questionWithAnswers() {
let listQuestions = QuestionDetails()
//array of keys/questions
var questionList = Array(listQuestions.QADictionary.keys)
//random question index
var rand = Int(arc4random_uniform(UInt32(questionList.count)))
var randAnswers = rand
//array of values/answers
var answerList = Array(listQuestions.QADictionary.values)
//button answer choices
var choices = answerList[randAnswers]
//fetch questions from list
let question = questionList[rand]
//function for new question and button titles
questionLabel.text = question
rightAnswerBox = arc4random_uniform(4)+1
//create button
var button:UIButton = UIButton()
var x = 1
for index in 1...4 {
button = view.viewWithTag(index) as! UIButton
if (index == Int(rightAnswerBox)) {
button.setTitle(choices[0], for: .normal)
} else {
button.setTitle(choices[x], for: .normal)
x += 1
}
randomImage()
}
}
答案 0 :(得分:0)
解决此问题的经典方法是,在不重复的情况下从整个数组中随机显示元素,即创建另一个索引数组,为主数组中的每个项目创建一个索引,然后随机地将其重新排列。然后只需逐步执行该混乱的索引数组,并使用now-randomized索引顺序显示主数组中的项目。