0

I am making a quiz app in Swift and my question is how can I pick 3 random questions from my array which has 6 questions, because im planning on adding like 900 questions and i don't want every single one to be displayed i will need only 30 random from those.

Here is an image how it looks: code

class QuestionBank {

var list = [Questions]()

init() {
    list.append(Questions(questionImage: "Parking", questionText: "Дополнителната табла поставена под сообраќајниот знак означува:", choice1: "Положба при паркирање на возилото на коловоз", choice2: "Место на кое паркирањето не е дозволено", choice3: "Место на кое паркирањето е временски ограничено", correctanswer: 1))
    list.append(Questions(questionImage: "Policaec", questionText: "Положбата на телото и рацете на униформираниот полициски службеник (како на сликата), означува забрането минување:", choice1: "на возилата кои доаѓаат од насока на бочните страни", choice2: "на возилата кои доаѓаат од насока на грбот и градите", choice3: "на сите возила", correctanswer: 2))
    list.append(Questions(questionImage: "policaec2", questionText: "Според положбата на телото и рацете на униформираниот полициски службеник како на сликата , забрането е минување на:", choice1: "сите возила", choice2: "возилата кои доаѓаат од насока на бочните страни", choice3: "возилата кои доаѓаат од насока на грбот и градите", correctanswer: 3))
    list.append(Questions(questionImage: "semafor", questionText: "Според светлосниот знак на уредот за давање на светлосни сообраќајни знаци (прикажан на сликата):", choice1: "не може да свртите десно, бидејќи нема дополнителна зелена светлечка стрелка", choice2: "имате дозволен премин во сите правци", choice3: "имате дозволен премин само во насока право", correctanswer: 2))
    list.append(Questions(questionImage: "Stop", questionText: "Според начинот на кој е регулиран сообраќајот на крстосницата како на сликата, возачот е должен:", choice1: "да го запре возилото", choice2: "да запре со возилото само доколку има стоп линија", choice3: "да продолжи со движењето", correctanswer: 1))
    list.append(Questions(questionImage: "Dolzina", questionText: "Дополнителната табла поставена под сообраќајниот знак означува:", choice1: "Место каде сообраќајот се одвива во насока на прикажаните стрелки", choice2: "Оддалеченост од место каде започнуваат работите на патот", choice3: "Должина на дел од патот на кој што се изведувааат работи на патот", correctanswer: 3))
}

This is QuestionBank class

class Questions {
let image: String
let prasanje: String
let odgovor1: String
let odgovor2: String
let odgovor3: String
let tocenodgovor: Int

init(questionImage: String, questionText: String, choice1: String, choice2: String, choice3: String, correctanswer: Int){
    image = questionImage
    prasanje = questionText
    odgovor1 = choice1
    odgovor2 = choice2
    odgovor3 = choice3
    tocenodgovor = correctanswer
}

This is the questions class

And if you know how can i randomize the given choices that will be helpfull too!

2
  • 1
    Please post your actual code (not an image) and your Questions class. You should really have an id property on it so that you have something to compare to. Commented May 3, 2020 at 22:08
  • 1
    I think they just need to use the randomElement() or shuffle() properties Commented May 3, 2020 at 22:11

3 Answers 3

2

UPDATED ANSWER WITH OP'S NEWLY POSTED CODE:

You'll need to implement Equatable in your Questions class so iOS can compare items. This is commonly done using an id property. I've updated your class here:

class Questions: Equatable {
    static func == (lhs: Questions, rhs: Questions) -> Bool {
        return lhs.id == rhs.id
    }

    let id: Int
    let image: String
    let prasanje: String
    let odgovor1: String
    let odgovor2: String
    let odgovor3: String
    let tocenodgovor: Int

    init(questionId: Int, questionImage: String, questionText: String, choice1: String, choice2: String, choice3: String, correctanswer: Int){
        id = questionId
        image = questionImage
        prasanje = questionText
        odgovor1 = choice1
        odgovor2 = choice2
        odgovor3 = choice3
        tocenodgovor = correctanswer
    }
}

I've updated your QuestionBank class to have a shared singleton so you can access it from anywhere.

class QuestionBank {

    var list = [Questions]()
    static var shared = QuestionBank()

    init() {
        list.append(Questions(questionId: 1, questionImage: "Parking", questionText: "Дополнителната табла поставена под сообраќајниот знак означува:", choice1: "Положба при паркирање на возилото на коловоз", choice2: "Место на кое паркирањето не е дозволено", choice3: "Место на кое паркирањето е временски ограничено", correctanswer: 1))
            list.append(Questions(questionId: 2, questionImage: "Policaec", questionText: "Положбата на телото и рацете на униформираниот полициски службеник (како на сликата), означува забрането минување:", choice1: "на возилата кои доаѓаат од насока на бочните страни", choice2: "на возилата кои доаѓаат од насока на грбот и градите", choice3: "на сите возила", correctanswer: 2))
            list.append(Questions(questionId: 3, questionImage: "policaec2", questionText: "Според положбата на телото и рацете на униформираниот полициски службеник како на сликата , забрането е минување на:", choice1: "сите возила", choice2: "возилата кои доаѓаат од насока на бочните страни", choice3: "возилата кои доаѓаат од насока на грбот и градите", correctanswer: 3))
            list.append(Questions(questionId: 4, questionImage: "semafor", questionText: "Според светлосниот знак на уредот за давање на светлосни сообраќајни знаци (прикажан на сликата):", choice1: "не може да свртите десно, бидејќи нема дополнителна зелена светлечка стрелка", choice2: "имате дозволен премин во сите правци", choice3: "имате дозволен премин само во насока право", correctanswer: 2))
            list.append(Questions(questionId: 5, questionImage: "Stop", questionText: "Според начинот на кој е регулиран сообраќајот на крстосницата како на сликата, возачот е должен:", choice1: "да го запре возилото", choice2: "да запре со возилото само доколку има стоп линија", choice3: "да продолжи со движењето", correctanswer: 1))
            list.append(Questions(questionId: 6, questionImage: "Dolzina", questionText: "Дополнителната табла поставена под сообраќајниот знак означува:", choice1: "Место каде сообраќајот се одвива во насока на прикажаните стрелки", choice2: "Оддалеченост од место каде започнуваат работите на патот", choice3: "Должина на дел од патот на кој што се изведувааат работи на патот", correctanswer: 3))
    }

    func getRandomQuestions(_ amount: Int) -> [Questions] {
        var randomQuestions = [Questions]()
        while randomQuestions.count < amount {
            let randomIndex = Int.random(in: 0 ... list.count - 1)
            if randomQuestions.contains(list[randomIndex]) == false {
                randomQuestions.append(list[randomIndex])
            } else {
                print("randomQuestions already contains this question.")
            }
        }
        return randomQuestions
    }
}

Now in your ViewController (or anywhere in the app) you can get any number of your random questions with one line of code:

    let randomQuestions = QuestionBank.shared.getRandomQuestions(3)

    // this is some simple test code or you to print your random questions id and text
    for question in randomQuestions {
        print(question.id)
        print(question.prasanje)
    }
Sign up to request clarification or add additional context in comments.

4 Comments

Thnaks for your respond sorry about that. I have uploaded my questions class code. I will try this and let you know if it worked.
@KlayJ, Thanks. I updated my answer based on your actual code. If this works, please accept this answer.
All done and working, thank you very much for your time! If its not too much to ask, how can i make the given options to be randomized aswell? If not thats okay, feel free to leave me your paypal i can send u for ur time helping me!
Hey @KlayJ, You're welcome! What do you mean "the options randomized as well"? If you mean the randomizing the order, you could use "let randomQuestions = QuestionBank.shared.getRandomQuestions(3).shuffled()" instead. I'm not on StackOverflow for payments, but you can always follow me on GitHub: github.com/elliott-io
1

Chooses 3 (non repeated) Questions Stores them into an array

var setOfQuestions: Set<String> = ["Question 1..", "Question 2..", "Question 3.."]
let howMany = 3
var pickedQuestions = [String]()

for i in 1...3 {
   let picked = setOfQuestions.randomElement()!
   pickedQuestions.append(picked)
   setOfQuestions.remove(picked)
}

If you want an array to be shuffled, you can do this (By the way, sets are always shuffled)

[1, 2, 3, 4].shuffled()

3 Comments

Cool, @jonathan. This is functional, though assumes that OP will only pull the random questions once, since this code changes the original array that holds the questions. This is better than my answer if OP wants questions to only ever be displayed once in the app session. If there are repeated rounds where questions can be re-asked, this won't work (which was my assumption in my answer).
yes i want my questions to be repeated every time the quiz starts
Because the OP stated they have the intent to have 900 questions using shuffle or shuffled would be very inefficient. Picking 30 unique random numbers would be better approach in this case.
0

This solution uses a set as every element needs to be unique

func randomQuestions(totalRequired: Int, maxQuestions: Int) -> [Int] {
    var questions = Set<Int>()
    repeat {
        let question = Int.random(in: 0..<maxQuestions)
        questions.insert(question)
    } while questions.count < 3
   return questions.shuffled()
}

print(randomQuestions(totalRequired: 3, maxQuestions: 90))
// [32, 6, 86]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.