使用arc4random生成十个随机数

时间:2016-02-22 21:52:08

标签: ios swift random firebase arc4random

我正在使用arc4random生成10个随机数,以便我可以查询firebase以获取包含随机生成的数字的问题。问题是我不希望任何数字出现多次,因此没有重复的问题。目前的代码如下......

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) {
    }
}

5 个答案:

答案 0 :(得分:5)

你可以有一个数组来存储你想要随机的值,在你的情况下,[1,2,3 .... 10],然后使用arc4random获取内部任意值的随机索引(0 .9),获取值并从数组中删除它。那么你永远不会从数组中获得相同的数字。

答案 1 :(得分:4)

给出问题总数

let questionsCount = 100

你可以生成一个整数序列

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

现在给出您需要的唯一随机数的数量

let randomsCount = 10

当然不应超过问题总数

assert(randomsCount <= questionsCount)

您可以构建唯一整数列表

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

答案 2 :(得分:2)

作为在客户端上生成随机数并以该指定号码请求问题的替代方法,您可以下载整个问题数组并随机播放该数组。 GameKit提供了一个内置的方法来重新排列数组。

import GameKit

// ...

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")
    .observeEventType(.ChildAdded, withBlock: {
        snapshot in
        // Shuffle your array
        let shuffledQuestions = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(snapshot)
        // Store your array somewhere and iterate through it for the duration of your game
    })

答案 3 :(得分:1)

您可以生成随机数并将每个数字存储在NSArray中。但是,当您将其附加到数组时,您可以检查数组是否已包含该数字。

例如:

for _ in 1...10 {
let amountOfQuestions: UInt32 = 40
var intArray: [Int] = []
let randomNumber = Int(arc4random_uniform(amountOfQuestions - 1)) + 1

if intArray.contains(randomNumber) {

    repeat {
        randomNumber = Int(arc4random_uniform(amountOfQuestions - 1)) + 1
    } while intArray.contains(randomNumber)

    if !intArray.contains(randomNumber) {
        intArray.append(randomNumber)
    }


} else {
    intArray.append(randomNumber)
}

    print(intArray)
}

之后,您可以使用唯一生成的整数生成FireBase请求。我希望我能够提供帮助:)。

答案 4 :(得分:0)

创建十个随机Int 0..99

的未排序数组
var set = Set<Int>()
while set.count < 10 {
    let num = Int(arc4random_uniform(100))
    set.insert(num)
}
let arr = Array(set)