【问题标题】:Using arc4random to generate ten random numbers使用 arc4random 生成十个随机数
【发布时间】:2016-02-22 21:52:07
【问题描述】:

我正在使用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) {
    }
}

【问题讨论】:

  • 你不应该从 amountOfQuestions 中减去 1
  • 如果您不希望它们出现两次,您可以从原始数组中随机删除每个元素

标签: ios swift random firebase arc4random


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    给定问题的总数

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

    【讨论】:

    • 既然你不移除你从数组中挑选的随机对象,是不是可以重复相同的值?在我看来,return naturals[index] 应该改为return naturals.removeAtIndex(index)。这将删除并返回一个对象。
    • @appzYourLife 正如 Duncan C 已经指出的那样,这不会阻止随机数出现多次。只需将问题数量更改为 10,您就会注意到它
    • 你是对的!让我一回家就修好。谢谢!
    • 已通过 iPhone 修复。再次感谢您。
    【解决方案3】:

    作为在客户端生成随机数并请求指定数字的问题的替代方法,您可以下载整个问题数组并随机播放数组。 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
        })
    

    【讨论】:

      【解决方案4】:

      您可以生成随机数并将每个数字存储在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 请求。我希望我能提供帮助:)。

      【讨论】:

        【解决方案5】:

        创建十个随机 Int 0..99 的未排序数组

        var set = Set<Int>()
        while set.count < 10 {
            let num = Int(arc4random_uniform(100))
            set.insert(num)
        }
        let arr = Array(set)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-12-25
          • 2013-06-22
          • 1970-01-01
          • 2023-01-03
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多