【问题标题】:Printing function results into an array将函数结果打印到数组中
【发布时间】:2015-08-26 14:29:24
【问题描述】:

看起来很简单,但我想不通。

let getRandom = randomSequenceGenerator(min: 1, max: 20)
for _ in 1...20 {
    println(getRandom())
}

getRandom 在控制台中打印出 20 个不重复的数字...完美。

我想将这 20 个非重复数字放入一个数组中,以便我可以使用它们。 我好像搞不懂。

或者无论如何,我可以在控制台之外访问这 20 个号码。

【问题讨论】:

标签: arrays swift random


【解决方案1】:

你只需要使用一个数组和一个循环变量:

let getRandom = randomSequenceGenerator(min: 1, max: 20)
var array = [Int](20)

for i in 0 ..< 20 {
    array[i] = getRandom()
}

【讨论】:

    【解决方案2】:

    将其放入循环中:

    func randomSequenceGenerator(min: Int, max: Int) -> Int {
        return Int(arc4random_uniform(UInt32(max-min))+UInt32(min))
    }
    
    let getRandom = { randomSequenceGenerator(1, 20) }
    var array = [Int]()
    
    for _ in 1...20 {
        array.append(getRandom())
    }
    

    【讨论】:

      【解决方案3】:

      这是我常用的方法。(如果您想要非重复数字数组,那么您必须检查生成的每个随机数是否之前已存储在数组中)

      检查此代码,它会根据“RANGE”变量值生成不重复的随机数。

          var array = [Int](arrayLiteral: 20)
          var counter = 0
          var repeatedValue = false
          let RANGE : UInt32 = 20
      
          while array.count < 20 {
              let a  = Int(arc4random_uniform(RANGE) + 1)
              repeatedValue = false
      
              for item in array{
                  if item == a{
                      repeatedValue = true
                  }
              }
      
              if repeatedValue == false{
                  array.append(a)
                  counter++
              }
          }
          print("Non repeated 20 random numbers : \(array)")
      

      输出结果:

      Non repeated 20 random numbers : [20, 13, 16, 1, 8, 7, 4, 10, 11, 2, 17, 18, 12, 19, 3, 14, 9, 5, 6, 15]
      

      【讨论】:

        【解决方案4】:

        我认为您只是想随机排列一些数字。我为 Swift 2.0 beta 6 制作了这个:

        func randomUpTo(n: Int) -> Int {
            return Int(arc4random_uniform(UInt32(n)))
        }
        
        extension CollectionType {
            func shuffled() -> [Generator.Element] {
                var ind = Array(indices)
                return (startIndex..<endIndex).map{_ in self[ind.removeAtIndex(randomUpTo(ind.count))] }
            }
        }
        

        你可以这样使用:

        (1...100).shuffled()   // [9, 8, 1, 19, 17, 2, 13, 16, 11, 12, 7, 14, 20, 3, 15, 6, 18, 4, 10, 5]
        
        let alphabet = (1...26).map{ Character(UnicodeScalar($0 + 64)) }    // ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
        alphabet.shuffled()    // ["V", "I", "S", "R", "H", "L", "F", "U", "T", "A", "X", "W", "B", "P", "K", "M", "Y", "E", "N", "Z", "G", "J", "Q", "D", "C", "O"]
        

        编辑:上面的算法不如这个算法快(复杂度 O(n^2))(Fisher-Yikes 算法):

        extension CollectionType {
            func chooseRandom(n : Int = Int.max) -> [Generator.Element] {
                var values = Array(self)
                for index in values.indices.dropFirst().reverse().prefix(n) {
                    swap(&values[randomUpTo(index)], &values[index])
                }
                return Array(values.suffix(n))
            }
        }
        

        你可以这样使用它:

        (0...20).chooseRandom(10)    // [20, 8, 7, 12, 3, 10, 19, 2, 15, 16]
        [1, 3, 5, 7, 9, 11].chooseRandom()    // [11, 9, 3, 1, 7, 5]
        

        它适用于任何CollectionType。复杂度为 O(n)

        【讨论】:

          【解决方案5】:

          谢谢大家!!这是我得出的解决方案,效果很好!这是针对 3 个随机生成的数字。显然,如果您想要更多,只需更改数字....我使用了每个人的建议。感谢您的帮助。

            func randomSequenceGenerator(min min: Int, max: Int) -> () -> Int {
                  var numbers: [Int] = []
                  return {
                      if numbers.count == 0 {
                          numbers = Array(min ... max)
                      }
          
                      let index = Int(arc4random_uniform(UInt32(numbers.count)))
                      return numbers.removeAtIndex(index)
                  }
              }
          
          
           let getRandom = randomSequenceGenerator(min: 1, max: 3)
          
                      for i in 0...2 {
          
                         randomNonRepeat[i] = getRandom()
          
                      }
          
              print (randomNonRepeat)
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-04-26
            • 2017-11-27
            • 2023-01-11
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多