//

//  RandomNumbers.swift

//  RandomNumbers

//

//  Created by bruegel on 22.04.17.

//  Copyright © 2017 Coti's Crazy Coding. All rights reserved.

//

//  25. 4. 2017

//  Added randomElement() -> Element? and randomItem() -> Element

//

import Foundation


public class RandomNumbers {


  /// Random Int € [0, n)

  public class func randomInt(_ n: Int) -> Int {

    return Int(arc4random_uniform(UInt32(n)))

  }

  


  // Random numbers (Int, Float, Double, CGFloat) € [min, max)

  

  /// Random Int € [min, max)

  public class func randomInt(min: Int, max: Int) -> Int {

    return min + Int(arc4random_uniform(UInt32(max - min)))

  }

  

  /// Random Double € [min, max)

  public class func randomDouble(min: Double, max: Double) -> Double {

    return (Double(arc4random()) / 0xFFFFFFFF) * (max - min) + min

  }

  

  /// Random Float € [min, max)

  public class func randomFloat(min: Float, max: Float) -> Float {

    return (Float(arc4random()) / 0xFFFFFFFF) * (max - min) + min

  }

  

  /// Random CGFloat € [min, max)

  public class func randomCGFloat(min: CGFloat, max: CGFloat) -> CGFloat {

    return CGFloat(Float(arc4random()) / Float(UINT32_MAX)) * (max - min) + min

  }


  // Random numbers (Int, Float, Double, CGFloat) € [0,1)


  /// Random Double € [0,1)

  public class func randomDouble() -> Double {

    return (Double(arc4random()) / 0xFFFFFFFF)

  }

  

  /// Random Float € [0, 1)

  public class func randomFloat() -> Float {

    return (Float(arc4random()) / 0xFFFFFFFF)

  }

  

  /// Random CGFloat € [0,1)

  public class func randomCGFloat() -> CGFloat {

    return CGFloat(Float(arc4random()) / Float(UINT32_MAX))

  }

} // End of RandomNumbers


//MARK: randomElement() for Collection

/// Returns a random item from the collecion or nil if empty

extension Collection where Index == Int {

  

  /**

   Picks a random element of the collection.

   

   - returns: A random element of the collection.

   */

  func randomElement() -> Iterator.Element? {

    return isEmpty ? nil : self[Int(arc4random_uniform(UInt32(endIndex)))]

  }

  

}

//MARK: randomItem() for Array

/// Non-optional, no check for empty Array

extension Array {

  func randomItem() -> Element {

    let index = Int(arc4random_uniform(UInt32(self.count)))

    return self[index]

  }

}