simlimsd3
simlimsd3

Reputation: 619

Choose random structs out of array

I have an array of structs that I randomise before a user starts the quiz. I want to get 3 of the questions randomly out of this array and put them into a new array. What is the best way I could do this?

Should I shuffle the array before selecting the random structs or is there a way to choose random structs?

So far the only way I can work out how to do this is to pre shuffle the array and then append the first 3 responses.

var learnersQuizQuestions =

[
    questionInfo(question: "Question 0", questionNumber: 1, answer: true, explanation: "Explanation for Question 0"),
    questionInfo(question: "Question 1", questionNumber: 2, answer: true, explanation: "Explanation for Question 1"),
    questionInfo(question: "Question 2", questionNumber: 3, answer: true, explanation: "Explanation for Question 2"),
    questionInfo(question: "Question 3", questionNumber: 4, answer: true, explanation: "Explanation for Question 3"),
    questionInfo(question: "Question 4", questionNumber: 5, answer: true, explanation: "Explanation for Question 4")
                                                                        ]

Upvotes: 0

Views: 54

Answers (2)

Daniel Krom
Daniel Krom

Reputation: 10058

you can use this function to extract X random elements from array

func randFromArray<T>(arr: Array<T>,numOfElements:Int)->Array<T>{
    var localArr = arr;
    let minIndex = minElement([numOfElements,arr.count])
    var result = Array<T>();

    for i in 0..<minIndex{
        var randIndex =  Int(arc4random()) % localArr.count;
        let element = localArr[randIndex];
        localArr.removeAtIndex(randIndex)
        result.append(element)
    }

    return result;
}

Upvotes: 0

Daniel Hariri
Daniel Hariri

Reputation: 1121

Just mix the array and pick the first three elements.

for var i:Int = 0; i < 10; ++i{
    randIdx1 = Int(arc4random() % learnersQuizQuestions.count)
    randIdx2 = Int(arc4random() % learnersQuizQuestions.count)
    swap(&learnersQuizQuestions[randIdx1], &learnersQuizQuestions[randIdx1])
}

let firstQuestion = learnersQuizQuestions[0]
let secondQuestion = learnersQuizQuestions[1]
let thirdQuestion = learnersQuizQuestions[2]

Upvotes: 1

Related Questions