1

How can i set my random function to only get me 2 results. I only want to get 2 questions per array not the 4 questions. random() or arc4random()? Not really sure which is better or what are the differences between this two methods! This is a different situation because Im using an struct for my array of Question.

struct Question {
var question: String!
var answers: [String]
var answer: Int!
var img: UIImage!
var info: String!

}
//Here is my viewDidLoad
override func viewDidLoad() {
    super.viewDidLoad()
questions = [

        Question(
            question: "How old it was Steve Jobs in 2009?",
            answers: ["10","30","19","20    "],
            answer: 3,
            img: UIImage.self(named: "steve"),
            info: "Steve"
                ),]//....Here is more code with other questions
}

var questions = [Question]()//my array with the questions
var questionNumber = Int()

private func pickingRandomQuestion() {
    let numberQuestion = questions.count

if numberQuestion > 0{
    questionNumber = random() % questions.count//I only want to get  2 questions not the entire array of questions.
else {
NSLog("Done!")
}
  • 1
    Make an array `[0..length-1]`. Shuffle that. Pick the first two entries. Use those as indexes into your questions. – Thilo Sep 12 '16 at 04:14
  • my array contains `Strings` and `Int` thats one of the problems that I have with `arc4random()`. – Roberto Viramontes Sep 12 '16 at 04:28
  • Your array contains `Question` structs, no? – Thilo Sep 12 '16 at 04:38
  • yes but I want to get only 2 questions not the 4 that i have!!! – Roberto Viramontes Sep 12 '16 at 04:53
  • Yes, so you want to refer to the linked question and pick two random questions from your array. `let twoQuestions = [questions[randomIndex], questions[anotherRandomIndex]]`. – Thilo Sep 12 '16 at 04:54
  • This is so hard to understand, I already try to implement your code but I don't know how use the correct syntax in my code !!! little bit more help my man – Roberto Viramontes Sep 12 '16 at 07:39
  • With two from four questions there are only six possible pairs: 12, 13, 14, 23, 24, 34. If order is important then there are twelve pairs: 12, 21, 13, 31, 14, 41, 23, 32, 24, 42, 34, 43. Pick a random number in [1..6] or in [1..12] and take the two questions the number indicates. – rossum Sep 12 '16 at 11:36

0 Answers0