2017-07-22 30 views
1

目前我的代码从一个键和值的数组中抽出一个随机索引。然而,索引保持不变,并显示相同的键和值,但我想要它做的是显示一个随机索引迭代通过数组,并显示另一个不等于以前的随机索引的随机索引。我怎么能实现这个?如何通过整个数组来使我的随机索引进度?

这是我的代码(SWIFT为iOS):

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

使用此https://github.com/nvzqz/RandomKit也许可以帮助你 –

回答

0

解决这个问题,并随机显示从整个阵列元件,而不重复所述的经典方法是创建索引的另一个数组,为一个索引你的主阵列中的每个项目,并随机洗牌。然后,只需遍历该混合的索引数组,然后使用now-randomized索引顺序显示主数组中的项目。

+0

你能给我一个例子与我的代码? –

相关问题