搜索
您的当前位置:首页正文

Random Generator, Random Array G

来源:二三娱乐

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
    }
}
Top