Skip to content

Commit 087daa9

Browse files
authored
Merge pull request #1 from raywenderlich/master
merge from orignal
2 parents e0c0200 + b83ef3b commit 087daa9

File tree

75 files changed

+2831
-913
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

75 files changed

+2831
-913
lines changed

Big-O Notation.markdown

+2-2
Original file line numberDiff line numberDiff line change
@@ -132,9 +132,9 @@ Below are some examples for each category of performance:
132132
The most trivial example of function that takes O(n!) time is given below.
133133

134134
```swift
135-
func nFacFunc(n: Int) {
135+
func nFactFunc(n: Int) {
136136
for i in stride(from: 0, to: n, by: 1) {
137-
nFactFunc(n - 1)
137+
nFactFunc(n: n - 1)
138138
}
139139
}
140140
```

Binary Search Tree/README.markdown

+1-1
Original file line numberDiff line numberDiff line change
@@ -375,7 +375,7 @@ As an exercise, see if you can implement filter and reduce.
375375
We can make the code more readable by defining some helper functions.
376376

377377
```swift
378-
private func reconnectParentToNode(node: BinarySearchTree?) {
378+
private func reconnectParentTo(node: BinarySearchTree?) {
379379
if let parent = parent {
380380
if isLeftChild {
381381
parent.left = node

Binary Search/README.markdown

+3-3
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,15 @@ Goal: Quickly find an element in an array.
44

55
Let's say you have an array of numbers and you want to determine whether a specific number is in that array, and if so, at which index.
66

7-
In most cases, Swift's `indexOf()` function is good enough for that:
7+
In most cases, Swift's `Collection.index(of:)` function is good enough for that:
88

99
```swift
1010
let numbers = [11, 59, 3, 2, 53, 17, 31, 7, 19, 67, 47, 13, 37, 61, 29, 43, 5, 41, 23]
1111

12-
numbers.indexOf(43) // returns 15
12+
numbers.index(of: 43) // returns 15
1313
```
1414

15-
The built-in `indexOf()` function performs a [linear search](../Linear%20Search/). In code that looks something like this:
15+
The built-in `Collection.index(of:)` function performs a [linear search](../Linear%20Search/). In code that looks something like this:
1616

1717
```swift
1818
func linearSearch<T: Equatable>(_ a: [T], _ key: T) -> Int? {

Brute-Force String Search/README.markdown

+1-1
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,6 @@ extension String {
5151

5252
This looks at each character in the source string in turn. If the character equals the first character of the search pattern, then the inner loop checks whether the rest of the pattern matches. If no match is found, the outer loop continues where it left off. This repeats until a complete match is found or the end of the source string is reached.
5353

54-
The brute-force approach works OK, but it's not very efficient (or pretty). It should work fine on small strings, though. For a smarter algorithm that works better with large chunks of text, check out [Boyer-Moore](../Boyer-Moore/) string search.
54+
The brute-force approach works OK, but it's not very efficient (or pretty). It should work fine on small strings, though. For a smarter algorithm that works better with large chunks of text, check out [Boyer-Moore](../Boyer-Moore-Horspool) string search.
5555

5656
*Written for Swift Algorithm Club by Matthijs Hollemans*

Combinatorics/README.markdown

+10-10
Original file line numberDiff line numberDiff line change
@@ -99,17 +99,17 @@ Here's a recursive algorithm by Niklaus Wirth:
9999

100100
```swift
101101
func permuteWirth<T>(_ a: [T], _ n: Int) {
102-
if n == 0 {
103-
print(a) // display the current permutation
104-
} else {
105-
var a = a
106-
permuteWirth(a, n - 1)
107-
for i in 0..<n {
108-
swap(&a[i], &a[n])
109-
permuteWirth(a, n - 1)
110-
swap(&a[i], &a[n])
102+
if n == 0 {
103+
print(a) // display the current permutation
104+
} else {
105+
var a = a
106+
permuteWirth(a, n - 1)
107+
for i in 0..<n {
108+
a.swapAt(i, n)
109+
permuteWirth(a, n - 1)
110+
a.swapAt(i, n)
111+
}
111112
}
112-
}
113113
}
114114
```
115115

Convex Hull/Convex Hull.xcodeproj/project.pbxproj

+3-3
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,7 @@
149149
};
150150
8E6D68B51E59989400161780 = {
151151
CreatedOnToolsVersion = 8.2.1;
152-
DevelopmentTeam = 7C4LVS3ZVC;
152+
DevelopmentTeam = 4SQG5NJNPF;
153153
ProvisioningStyle = Automatic;
154154
};
155155
};
@@ -384,7 +384,7 @@
384384
isa = XCBuildConfiguration;
385385
buildSettings = {
386386
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
387-
DEVELOPMENT_TEAM = 7C4LVS3ZVC;
387+
DEVELOPMENT_TEAM = 4SQG5NJNPF;
388388
INFOPLIST_FILE = "Convex Hull/Info.plist";
389389
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
390390
PRODUCT_BUNDLE_IDENTIFIER = "workmoose.Convex-Hull";
@@ -397,7 +397,7 @@
397397
isa = XCBuildConfiguration;
398398
buildSettings = {
399399
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
400-
DEVELOPMENT_TEAM = 7C4LVS3ZVC;
400+
DEVELOPMENT_TEAM = 4SQG5NJNPF;
401401
INFOPLIST_FILE = "Convex Hull/Info.plist";
402402
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
403403
PRODUCT_BUNDLE_IDENTIFIER = "workmoose.Convex-Hull";
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3+
<plist version="1.0">
4+
<dict>
5+
<key>IDEDidComputeMac32BitWarning</key>
6+
<true/>
7+
</dict>
8+
</plist>

Convex Hull/Convex Hull/View.swift

+2-10
Original file line numberDiff line numberDiff line change
@@ -11,28 +11,20 @@ import UIKit
1111
class View: UIView {
1212

1313
let MAX_POINTS = 100
14-
1514
var points = [CGPoint]()
16-
1715
var convexHull = [CGPoint]()
1816

1917
override init(frame: CGRect) {
2018
super.init(frame: frame)
21-
22-
// last checked with Xcode 9.0b4
23-
#if swift(>=4.0)
24-
print("Hello, Swift 4!")
25-
#endif
26-
27-
generatePoints()
19+
generateRandomPoints()
2820
quickHull(points: points)
2921
}
3022

3123
required init?(coder aDecoder: NSCoder) {
3224
fatalError("init(coder:) has not been implemented")
3325
}
3426

35-
func generatePoints() {
27+
func generateRandomPoints() {
3628
for _ in 0..<MAX_POINTS {
3729
let offset: CGFloat = 50
3830
let xrand = CGFloat(arc4random()) / CGFloat(UINT32_MAX) * (self.frame.width - offset) + 0.5 * offset

Convex Hull/README.md

+14-4
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,23 @@
11
# Convex Hull
22

3-
There are multiple Convex Hull algorithms. This particular implementation uses the Quickhull algorithm.
3+
Given a group of points on a plane. The Convex Hull algorithm calculates the shape (made up from the points itself) containing all these points. It can also be used on a collection of points of different dimensions. This implementation however covers points on a plane. It essentially calculates the lines between points which together contain all points. In comparing different solutions to this problem we can describe each algorithm in terms of it's big-O time complexity.
44

5-
Given a group of points on a plane. The Convex Hull algorithm calculates the shape (made up from the points itself) containing all these points. It can also be used on a collection of points of different dimensions. This implementation however covers points on a plane. It essentially calculates the lines between points which together contain all points.
5+
There are multiple Convex Hull algorithms but this solution is called Quickhull, is comes from the work of both W. Eddy in 1977 and also separately A. Bykat in 1978, this algorithm has an expected time complexity of O(n log n), but it's worst-case time-complexity can be O(n^2) . With average conditions the algorithm has ok efficiency, but it's time-complexity can start to head become more exponential in cases of high symmetry or where there are points lying on the circumference of a circle for example.
66

77
## Quickhull
88

99
The quickhull algorithm works as follows:
10-
The algorithm takes an input of a collection of points. These points should be ordered on their x-coordinate value. We pick the two points A and B with the smallest(A) and the largest(B) x-coordinate. These of course have to be part of the hull. Imagine a line from point A to point B. All points to the right of this line are grouped in an array S1. Imagine now a line from point B to point A. (this is of course the same line as before just with opposite direction) Again all points to the right of this line are grouped in an array, S2 this time.
11-
We now define the following recursive function:
10+
11+
- The algorithm takes an input of a collection of points. These points should be ordered on their x-coordinate value.
12+
- We first find the two points A and B with the minimum(A) and the maximum(B) x-coordinates (as these will obviously be part of the hull).
13+
- Use the line formed by the two points to divide the set in two subsets of points, which will be processed recursively.
14+
- Determine the point, on one side of the line, with the maximum distance from the line. The two points found before along with this one form a triangle.
15+
- The points lying inside of that triangle cannot be part of the convex hull and can therefore be ignored in the next steps.
16+
- Repeat the previous two steps on the two lines formed by the triangle (not the initial line).
17+
- Keep on doing so on until no more points are left, the recursion has come to an end and the points selected constitute the convex hull.
18+
19+
20+
Our functioni will have the following defininition:
1221

1322
`findHull(points: [CGPoint], p1: CGPoint, p2: CGPoint)`
1423

@@ -18,6 +27,7 @@ findHull(S2, B, A)
1827
```
1928

2029
What this function does is the following:
30+
2131
1. If `points` is empty we return as there are no points to the right of our line to add to our hull.
2232
2. Draw a line from `p1` to `p2`.
2333
3. Find the point in `points` that is furthest away from this line. (`maxPoint`)

DiningPhilosophers/README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ Based on the Chandy and Misra's analysis, a system of preference levels is deriv
4444

4545
# Swift implementation
4646

47-
This Swift 3.0 implementation of the Chandy/Misra solution is based on the GCD and Semaphore tecnique that can be built on both macOS and Linux.
47+
This Swift 3.0 implementation of the Chandy/Misra solution is based on the GCD and Semaphore technique that can be built on both macOS and Linux.
4848

4949
The code is based on a ForkPair struct used for holding an array of DispatchSemaphore and a Philosopher struct for associate a couple of forks to each Philosopher.
5050

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
//: Playground - noun: a place where people can play
2+
3+
func printTree(_ root: BinaryNode<String>?) {
4+
guard let root = root else {
5+
return
6+
}
7+
8+
let leftVal = root.left == nil ? "nil" : root.left!.val
9+
let rightVal = root.right == nil ? "nil" : root.right!.val
10+
11+
print("val: \(root.val) left: \(leftVal) right: \(rightVal)")
12+
13+
printTree(root.left)
14+
printTree(root.right)
15+
}
16+
17+
let coder = BinaryNodeCoder<String>()
18+
19+
let node1 = BinaryNode("a")
20+
let node2 = BinaryNode("b")
21+
let node3 = BinaryNode("c")
22+
let node4 = BinaryNode("d")
23+
let node5 = BinaryNode("e")
24+
25+
node1.left = node2
26+
node1.right = node3
27+
node3.left = node4
28+
node3.right = node5
29+
30+
let encodeStr = try coder.encode(node1)
31+
print(encodeStr)
32+
// "a b # # c d # # e # #"
33+
34+
35+
let root: BinaryNode<String> = coder.decode(from: encodeStr)!
36+
print("Tree:")
37+
printTree(root)
38+
/*
39+
Tree:
40+
val: a left: b right: c
41+
val: b left: nil right: nil
42+
val: c left: d right: e
43+
val: d left: nil right: nil
44+
val: e left: nil right: nil
45+
*/
46+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
//
2+
// EncodeAndDecodeTree.swift
3+
//
4+
//
5+
// Created by Kai Chen on 19/07/2017.
6+
//
7+
//
8+
9+
import Foundation
10+
11+
protocol BinaryNodeEncoder {
12+
func encode<T>(_ node: BinaryNode<T>?) throws -> String
13+
}
14+
15+
protocol BinaryNodeDecoder {
16+
func decode<T>(from string: String) -> BinaryNode<T>?
17+
}
18+
19+
public class BinaryNodeCoder<T: Comparable>: BinaryNodeEncoder, BinaryNodeDecoder {
20+
21+
// MARK: Private
22+
23+
private let separator: Character = ","
24+
private let nilNode = "X"
25+
26+
private func decode<T>(from array: inout [String]) -> BinaryNode<T>? {
27+
guard !array.isEmpty else {
28+
return nil
29+
}
30+
31+
let value = array.removeLast()
32+
33+
guard value != nilNode, let val = value as? T else {
34+
return nil
35+
}
36+
37+
let node = BinaryNode<T>(val)
38+
node.left = decode(from: &array)
39+
node.right = decode(from: &array)
40+
41+
return node
42+
}
43+
44+
// MARK: Public
45+
46+
public init() {}
47+
48+
public func encode<T>(_ node: BinaryNode<T>?) throws -> String {
49+
var str = ""
50+
node?.preOrderTraversal { data in
51+
if let data = data {
52+
let string = String(describing: data)
53+
str.append(string)
54+
} else {
55+
str.append(nilNode)
56+
}
57+
str.append(separator)
58+
}
59+
60+
return str
61+
}
62+
63+
public func decode<T>(from string: String) -> BinaryNode<T>? {
64+
var components = string.split(separator: separator).reversed().map(String.init)
65+
return decode(from: &components)
66+
}
67+
}
68+
69+
public class BinaryNode<Element: Comparable> {
70+
public var val: Element
71+
public var left: BinaryNode?
72+
public var right: BinaryNode?
73+
74+
public init(_ val: Element, left: BinaryNode? = nil, right: BinaryNode? = nil) {
75+
self.val = val
76+
self.left = left
77+
self.right = right
78+
}
79+
80+
public func preOrderTraversal(visit: (Element?) throws -> ()) rethrows {
81+
try visit(val)
82+
83+
if let left = left {
84+
try left.preOrderTraversal(visit: visit)
85+
} else {
86+
try visit(nil)
87+
}
88+
89+
if let right = right {
90+
try right.preOrderTraversal(visit: visit)
91+
} else {
92+
try visit(nil)
93+
}
94+
}
95+
}

0 commit comments

Comments
 (0)