【问题标题】:[Swift 2.2]: analog arc4random for range with negative numbers[Swift 2.2]:负数范围的模拟 arc4random
【发布时间】:2016-03-26 20:18:40
【问题描述】:

我写了一个函数来找出数组所有元素之间的最大差异。但我需要限制输入元素数组 [-5..20]。不幸的是它不支持 UInt32。什么类似于从 [-5..20] 范围内随机填充数组的解决方案?谢谢!

func highDifferenceV ( n: Int) ->String{
        var a = [Int]() //array
        var dif = 0     // max difference
        var k = 0


        for _ in 0..<n {
            a.append(Int(arc4random_uniform(UInt32(20)))) // fill array


        }
        while k < a.count {  //search the greatest difference
            for i in 0..<n {
                if a[k] - a[i] > dif {
                    dif = a[k] - a[i]
                }
            }
            k++
        }
        print(a)
        return "Maximum difference =\(dif)"
    }

    highDifferenceV(75)

【问题讨论】:

    标签: arrays swift random swift2


    【解决方案1】:

    要用-5...20 中的值填充数组,请在0...25 范围内生成一个数字,然后减去5

    for _ in 0..<n {
        a.append(Int(arc4random_uniform(UInt32(26)))-5) // fill array
    }
    

    通常,要生成min...max 范围内的值,请使用max - min + 1 调用arc4random_uniform,然后添加min

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-12
      • 2017-05-02
      • 2021-12-04
      • 1970-01-01
      相关资源
      最近更新 更多