-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRandom.swift
98 lines (78 loc) · 2.68 KB
/
Random.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
//
// Random.swift
// ios_metal_bezier_renderer
//
// Created by Jacob Martin on 5/31/18.
// Copyright © 2018 Eldad Eilam. All rights reserved.
//
import Foundation
import CoreGraphics
// MARK: Int Extension
public extension Int {
/// Returns a random Int point number between 0 and Int.max.
public static var random: Int {
return Int.random(n: Int.max)
}
/// Random integer between 0 and n-1.
///
/// - Parameter n: Interval max
/// - Returns: Returns a random Int point number between 0 and n max
public static func random(n: Int) -> Int {
return Int(arc4random_uniform(UInt32(n)))
}
/// Random integer between min and max
///
/// - Parameters:
/// - min: Interval minimun
/// - max: Interval max
/// - Returns: Returns a random Int point number between 0 and n max
public static func random(min: Int, max: Int) -> Int {
return Int.random(n: max - min + 1) + min
}
}
// MARK: Double Extension
public extension Double {
/// Returns a random floating point number between 0.0 and 1.0, inclusive.
public static var random: Double {
return Double(arc4random()) / 0xFFFFFFFF
}
/// Random double between 0 and n-1.
///
/// - Parameter n: Interval max
/// - Returns: Returns a random double point number between 0 and n max
public static func random(min: Double, max: Double) -> Double {
return Double.random * (max - min) + min
}
}
// MARK: Float Extension
public extension Float {
/// Returns a random floating point number between 0.0 and 1.0, inclusive.
public static var random: Float {
return Float(arc4random()) / 0xFFFFFFFF
}
/// Random float between 0 and n-1.
///
/// - Parameter n: Interval max
/// - Returns: Returns a random float point number between 0 and n max
public static func random(min: Float, max: Float) -> Float {
return Float.random * (max - min) + min
}
}
// MARK: CGFloat Extension
public extension CGFloat {
/// Randomly returns either 1.0 or -1.0.
public static var randomSign: CGFloat {
return (arc4random_uniform(2) == 0) ? 1.0 : -1.0
}
/// Returns a random floating point number between 0.0 and 1.0, inclusive.
public static var random: CGFloat {
return CGFloat(Float.random)
}
/// Random CGFloat between 0 and n-1.
///
/// - Parameter n: Interval max
/// - Returns: Returns a random CGFloat point number between 0 and n max
public static func random(min: CGFloat, max: CGFloat) -> CGFloat {
return CGFloat.random * (max - min) + min
}
}