2017-07-22 7 views
1

現在、私のコードは、キーと値の配列からランダムなインデックスを吐き出しています。しかし、インデックスは同じままで同じキーと値を表示しますが、私がしたいのは、配列を反復する1つのランダムなインデックスを表示し、前のランダムインデックスと等しくない別のランダムインデックスを表示することです。私はこれをどのように実装できますか?ランダムなインデックスの進行をアレイ全体にするにはどうすればよいですか?

ここ

は、自分のコード(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

https://github.com/nvzqz/RandomKitを使用して –

答えて

0

、ランダムに繰り返すことなく、全体の配列からの要素を表示し、インデックスの別の配列に対して1つのインデックスを作成することですメインアレイの各アイテムをランダムにシャッフルします。次に、シャッフルされた索引の配列をステップ実行し、現在ランダム化された索引順序を使用して、メイン配列の項目を表示します。

+0

さんのコードを参考にしてもらえますか? –

関連する問題