Guest User

Untitled

a guest
Feb 21st, 2018
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. fileprivate func gcd(_ a: Int, _ b: Int) -> Int {
  2. return b == 0 ? a : gcd(b, a % b)
  3. }
  4.  
  5. fileprivate func abs(_ n: Int) -> Int {
  6. return n > 0 ? n : -n
  7. }
  8.  
  9. struct Ratio {
  10. let numerator: Int
  11. let denominator: Int
  12.  
  13. init(_ numerator: Int, _ denominator: Int = 1) {
  14. var (numerator, denominator) = (numerator, denominator)
  15.  
  16. let divisor = gcd(numerator, denominator)
  17. numerator /= divisor
  18. denominator /= divisor
  19.  
  20. if denominator < 0 {
  21. (numerator, denominator) = (-numerator, -denominator)
  22. }
  23.  
  24. self.numerator = numerator
  25. self.denominator = denominator
  26. }
  27.  
  28. var asDouble: Double { return Double(numerator) / Double(denominator) }
  29. var asFloat: Float { return Float(numerator) / Float(denominator) }
  30. var abs: Ratio { return self.numerator < 0 ? -self : self }
  31. }
  32.  
  33. extension Ratio: CustomDebugStringConvertible {
  34. var debugDescription: String {
  35. let denom = denominator == 1 ? "" : "/\(String(describing: denominator))"
  36. return "\(numerator)\(denom)"
  37. }
  38. }
  39.  
  40. extension Ratio: ExpressibleByIntegerLiteral {
  41. init(integerLiteral value: IntegerLiteralType) {
  42. self.init(value)
  43. }
  44. }
  45.  
  46. extension Ratio: Equatable {}
  47. func ==(lhs: Ratio, rhs: Ratio) -> Bool {
  48. return lhs.numerator == rhs.numerator && lhs.denominator == rhs.denominator
  49. }
  50.  
  51. extension Ratio: Comparable {}
  52. func <(lhs: Ratio, rhs: Ratio) -> Bool {
  53. return (rhs.abs - lhs.abs).numerator > 0
  54. }
  55.  
  56. func +(lhs: Ratio, rhs: Ratio) -> Ratio {
  57. return Ratio(
  58. lhs.numerator * rhs.denominator + rhs.numerator * lhs.denominator,
  59. lhs.denominator * rhs.denominator
  60. )
  61. }
  62.  
  63. func +=(lhs: inout Ratio, rhs: Ratio) {
  64. lhs = lhs + rhs
  65. }
  66.  
  67. prefix func -(r: Ratio) -> Ratio {
  68. return Ratio(-r.numerator, r.denominator)
  69. }
  70.  
  71. func -(lhs: Ratio, rhs: Ratio) -> Ratio {
  72. return lhs + (-rhs)
  73. }
  74.  
  75. func -=(lhs: inout Ratio, rhs: Ratio) {
  76. lhs = lhs - rhs
  77. }
  78.  
  79. func *(lhs: Ratio, rhs: Ratio) -> Ratio {
  80. return Ratio(lhs.numerator * rhs.numerator,lhs.denominator * rhs.denominator)
  81. }
  82.  
  83. func *=(lhs: inout Ratio, rhs: Ratio) {
  84. lhs = lhs * rhs
  85. }
  86.  
  87. func /(lhs: Ratio, rhs: Ratio) -> Ratio {
  88. return lhs * Ratio(rhs.denominator, rhs.numerator)
  89. }
  90.  
  91. func /=(lhs: inout Ratio, rhs: Ratio) {
  92. lhs = lhs / rhs
  93. }
Add Comment
Please, Sign In to add comment