jon wilson
jon wilson

Reputation: 54

how to keep track of what items in an array have already been?

I have a quiz app that generates a random question. at the moment because of the randomization, you can sometimes answer the same question multiple times. I have an an array of questions and I use the arc4Random method to generate a random question on the screen.

how do I make it so that swift recognises that a question is already been on and to skip it? would I have to make an if statement? and if so how would I code that?

var currentQuestion = Int(arc4random_uniform(31) + 1)
var rightAnswerPlacement:UInt32 = 0
var seconds = 30
var timer = Timer()
var score = 0
if (sender.tag == Int(rightAnswerPlacement)) {
    score += 1
    scoreLabel.text = "\(score)"
    seconds = 100
    currentQuestion = Int(arc4random_uniform(32) + 1)
} else {
    timer.invalidate()
    end()
}

Upvotes: 0

Views: 69

Answers (2)

Shehata Gamal
Shehata Gamal

Reputation: 100503

var currentQuestion = Int(arc4random_uniform(36) + 1)
var rightAnswerPlacement:UInt32 = 0
var seconds = 30
var timer = Timer()
var score = 0
var asked = [Int]()

var recordData:String!

@IBOutlet weak var questionLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var scoreLabel: UILabel!

@IBOutlet weak var buttonOne: UIButton!
@IBOutlet weak var buttonTwo: UIButton!
@IBOutlet weak var buttonThree: UIButton!

@IBAction func answerButtons(_ sender: AnyObject) {

    if (sender.tag == Int(rightAnswerPlacement)) {

        score += 1
        scoreLabel.text = "\(score)"
        seconds = 100
        currentQuestion = Int(arc4random_uniform(36) + 1)

       while asked.contains(currentQuestion) {

            currentQuestion = Int(arc4random_uniform(36) + 1)
        }
        asked.append(currentQuestion)
        print(asked)

        if asked.count == questions.count {
            currentQuestion = 0
          return
        }

Upvotes: 3

Cristik
Cristik

Reputation: 32805

You could simply shuffle the question indices, and process that array:

let questionCount = 32
let questionIndices = (0..<questionCount).shuffled()
for index in questionIndices {
    let question = questions[index]
    let answer = answers[index]
    // process the question
}

You can trust the shuffled() implementation to be really random.

Upvotes: 1

Related Questions