美文网首页
Random Generator, Random Array G

Random Generator, Random Array G

作者: R0b1n_L33 | 来源:发表于2017-09-19 10:15 被阅读8次

    Build some infrastructures, like random generator, random array generator, etc.

    enum TestError : Error {
        case argumentFault
        case resultFault
    }
    
    extension Int {
        ///Generate a random int with an upper & lower bound
        static func random(above low:Int = 0, under high:Int = 9) throws -> Int {
            guard high >= low else { throw TestError.argumentFault }
            let range = high - low + 1;
            return Int(arc4random_uniform(UInt32(range)))+low;
        }
        
        ///Generate an integer array
        static func randomArray(above low:Int = 0, under high:Int = 9) throws -> [Int] {
            guard high >= low else { throw TestError.argumentFault }
            //Got a sequence
            var s = Array(low...high)
            
            //Randomize the order of elements. 
            //O(n) without taking the random algorithm into account
            for i in (0..<s.count).reversed() {
                let currentHigh = i+1
                let random = try Int.random(under: currentHigh)
                (s[i], s[random]) = (s[random], s[i])
            }
            return s
        }
    }
    

    相关文章

      网友评论

          本文标题:Random Generator, Random Array G

          本文链接:https://www.haomeiwen.com/subject/ldaisxtx.html