Generate random number of certain amount of digits

后端 未结 7 1925
不知归路
不知归路 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:45

    Swift 4 version of Unome's validate response plus :

    • Guard it against overflow and 0 digit number

    • Adding support for Linux's device because "arc4random*" functions don't exit

    With linux device don't forgot to do

    #if os(Linux)
        srandom(UInt32(time(nil)))
    #endif
    

    only once before calling random.

    /// This function generate a random number of type Int with the given digits number
    ///
    /// - Parameter digit: the number of digit
    /// - Returns: the ramdom generate number or nil if wrong parameter
    func randomNumber(with digit: Int) -> Int? {
    
        guard 0 < digit, digit < 20 else { // 0 digit number don't exist and 20 digit Int are to big
            return nil
        }
    
        /// The final ramdom generate Int
        var finalNumber : Int = 0;
    
        for i in 1...digit {
    
            /// The new generated number which will be add to the final number
            var randomOperator : Int = 0
    
            repeat {
                #if os(Linux)
                    randomOperator = Int(random() % 9) * Int(powf(10, Float(i - 1)))
                #else
                    randomOperator = Int(arc4random_uniform(9)) * Int(powf(10, Float(i - 1)))
                #endif
    
            } while Double(randomOperator + finalNumber) > Double(Int.max) // Verification to be sure to don't overflow Int max size
    
            finalNumber += randomOperator
        }
    
        return finalNumber
    } 
    

提交回复
热议问题