Search code examples
iosswiftrandomfirebasearc4random

Using arc4random to generate ten random numbers


I am using arc4random to generate 10 random numbers so I can then query firebase to get the questions that contain the randomly generated numbers. The problem is that I don't want any number to appear more than once so then there are not duplicate questions. Current code below...

import UIKit
import Firebase

class QuestionViewController: UIViewController {

    var amountOfQuestions: UInt32 = 40

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        // Use a for loop to get 10 questions
        for _ in 1...10{
            // generate a random number between 1 and the amount of questions you have
            let randomNumber = Int(arc4random_uniform(amountOfQuestions - 1)) + 1
            print(randomNumber)
            // The reference to your questions in firebase (this is an example from firebase itself)
            let ref = Firebase(url: "https://test.firebaseio.com/questions")
            // Order the questions on their value and get the one that has the random value
            ref.queryOrderedByChild("value").queryEqualToValue(randomNumber)
                .observeEventType(.ChildAdded, withBlock: {
                    snapshot in
                    // Do something with the question
                    print(snapshot.key)
                })
        }
    }

    @IBAction func truepressed(sender: AnyObject) {
    }

    @IBAction func falsePressed(sender: AnyObject) {
    }
}

Solution

  • Given the total number of questions

    let questionsCount = 100
    

    you can generate a sequence of integers

    var naturals = [Int](0..<questionsCount)
    

    Now given the quantity of unique random numbers you need

    let randomsCount = 10
    

    that of course should not exceed the total number of questions

    assert(randomsCount <= questionsCount)
    

    you can build your list of unique integers

    let uniqueRandoms = (1..<randomsCount).map { _ -> Int in
        let index = Int(arc4random_uniform(UInt32(naturals.count)))
        return naturals.removeAtIndex(index)
    }