Eren Akkaya
Eren Akkaya

Reputation: 9

How to select items from array no repeat

I'm building swift quiz app I want to show random questions with no repeat.

var sorular: Array = ["soru1","soru2","soru3","soru4","soru5"]

var gorulensoru = [Int]()
var sayac: Int = 0
var sorularcevaplar = ["D","Y","D","Y","D"]
var cevaplar: Array<Any> = []
var dogru: Int = 0
var yanlis: Int = 0

func chooseRandom() -> String {
    if gorulensoru.count == sorular.count { return "" }

    let randomItem = Int(arc4random() % UInt32(sorular.count)) //get

    if (gorulensoru.contains(randomItem)) {
        return chooseRandom()
    }

    let requiredItem = sorular[randomItem]
    gorulensoru.append(randomItem)

    return requiredItem
}

override func viewDidLoad() {
    super.viewDidLoad()

    soruText.text = chooseRandom()
}

What is the problem in my code? I'm tried insert selected random item to inside gorulensoru array but it shows again selected item

if (gorulensoru.contains(randomItem)) {
    return chooseRandom()
}

This statement doesn't run.

Upvotes: 0

Views: 60

Answers (2)

Lynx
Lynx

Reputation: 401

Change this and it may work:

let requiredItem = sorular[randomItem]
gorulensoru.append(requiredItem)

Upvotes: 0

Cyberbeni
Cyberbeni

Reputation: 710

Your code only runs once.

Also, you shouldn't include potential infinite recursive calls because it can easily get to a level where it causes a hang or crash.

Use shuffle() and then iterate over the array.

Upvotes: 1

Related Questions