Skip to content

Commit 4fe6999

Browse files
author
Popov Valery
committed
Added lection 2.6
1 parent 54b59df commit 4fe6999

File tree

6 files changed

+88
-0
lines changed

6 files changed

+88
-0
lines changed

Lecture2_6.playground/Contents.swift

+71
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
//: Playground - noun: a place where people can play
2+
3+
import UIKit
4+
5+
struct Rational: CustomStringConvertible {
6+
7+
var numer: Int = 0
8+
var denom: Int = 1
9+
10+
var description: String {
11+
let greatestCommonDivisior = gcd(numer, denom)
12+
return "\(numer / greatestCommonDivisior)/\(denom / greatestCommonDivisior)"
13+
}
14+
15+
init?(numer: Int, denom: Int) {
16+
17+
guard denom != 0 else {
18+
return nil
19+
}
20+
21+
//assert(denom != 0)
22+
23+
self.numer = numer
24+
self.denom = denom
25+
}
26+
27+
init(value: Int) {
28+
numer = value
29+
}
30+
31+
func add(r: Rational) -> Rational {
32+
return Rational(numer: numer * r.denom + r.numer * denom, denom: r.denom * denom)!
33+
}
34+
35+
func sub(r: Rational) -> Rational {
36+
return add(r.neg())
37+
}
38+
39+
func neg() -> Rational {
40+
return Rational(numer: -numer, denom: denom)!
41+
}
42+
43+
func less(that: Rational) -> Bool {
44+
return numer * that.numer < that.numer * denom
45+
}
46+
47+
func max(that: Rational) -> Rational {
48+
return self.less(that) ? that : self
49+
}
50+
51+
52+
53+
private func gcd(a: Int, _ b: Int) -> Int {
54+
return b == 0 ? a : gcd(b, a % b)
55+
}
56+
}
57+
58+
func +(left: Rational, right: Rational) -> Rational {
59+
return Rational(numer: left.numer * right.denom + right.numer * left.denom,
60+
denom: right.denom * left.denom)!
61+
}
62+
63+
func -(left: Rational, right: Rational) -> Rational {
64+
let negativeRight = right.neg()
65+
return left + negativeRight
66+
}
67+
68+
let a = Rational(numer: 24, denom: 6)
69+
70+
let b = Rational(value: 4)
71+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='ios'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>

Lecture2_6.playground/playground.xcworkspace/contents.xcworkspacedata

+7
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<Timeline
3+
version = "3.0">
4+
<TimelineItems>
5+
</TimelineItems>
6+
</Timeline>

0 commit comments

Comments
 (0)