Generate random number of certain amount of digits

后端 未结 7 1856
不知归路
不知归路 2021-01-18 10:51

Hy,

I have a very Basic Question which is :

How can i create a random number with 20 digits no floats no negatives (basically an Int) in Swift ?

Than

相关标签:
7条回答
  • 2021-01-18 11:46

    Step 1

    First of all we need an extension of Int to generate a random number in a range.

    extension Int {
        init(_ range: Range<Int> ) {
            let delta = range.startIndex < 0 ? abs(range.startIndex) : 0
            let min = UInt32(range.startIndex + delta)
            let max = UInt32(range.endIndex   + delta)
            self.init(Int(min + arc4random_uniform(max - min)) - delta)
        }
    }
    

    This can be used this way:

    Int(0...9) // 4 or 1 or 1...
    Int(10...99) // 90 or 33 or 11
    Int(100...999) // 200 or 333 or 893
    

    Step 2

    Now we need a function that receive the number of digits requested, calculates the range of the random number and finally does invoke the new initializer of Int.

    func random(digits:Int) -> Int {
        let min = Int(pow(Double(10), Double(digits-1))) - 1
        let max = Int(pow(Double(10), Double(digits))) - 1
        return Int(min...max)
    }
    

    Test

    random(1) // 8
    random(2) // 12
    random(3) // 829
    random(4) // 2374
    
    0 讨论(0)
提交回复
热议问题