从数组中选择随机结构

时间:2015-08-03 12:42:00

标签: ios arrays swift random

我有一个结构数组,我在用户开始测验之前随机化。我想从这个数组中随机抽取3个问题并将它们放入一个新数组中。我能做到这一点的最佳方式是什么?

我应该在选择随机结构之前对数组进行洗牌,还是有办法选择随机结构?

到目前为止,我能解决如何做到这一点的唯一方法是预先对数组进行混洗,然后附加前3个响应。

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")
                                                                        ]

2 个答案:

答案 0 :(得分:1)

只需混合数组并选择前三个元素。

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]

答案 1 :(得分:0)

您可以使用此函数从数组中提取X随机元素

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;
}