Skip to content

Commit c26648b

Browse files
author
Thukor
committed
Added something
2 parents 7926986 + 3a7f20d commit c26648b

File tree

48 files changed

+2728
-37
lines changed

Some content is hidden

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

48 files changed

+2728
-37
lines changed

.Rhistory

Whitespace-only changes.

.travis.yml

+1
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,4 @@ script:
2323
- xcodebuild test -project ./Shell\ Sort/Tests/Tests.xcodeproj -scheme Tests
2424
- xcodebuild test -project ./Stack/Tests/Tests.xcodeproj -scheme Tests
2525
- xcodebuild test -project ./Longest\ Common\ Subsequence/Tests/Tests.xcodeproj -scheme Tests
26+
- xcodebuild test -project ./Bucket\ Sort/Tests/Tests.xcodeproj -scheme Tests

Binary Search Tree/README.markdown

+2-2
Original file line numberDiff line numberDiff line change
@@ -428,7 +428,7 @@ We won't need it for deleting, but for completeness' sake, here is the opposite
428428

429429
It returns the rightmost descendent of the node. We find it by following `right` pointers until we get to the end. In the above example, the rightmost descendent of node `2` is `5`. The maximum value in the entire tree is `11`, because that is the rightmost descendent of the root node `7`.
430430

431-
Finally, we can write the code the remove a node from the tree:
431+
Finally, we can write the code that removes a node from the tree:
432432

433433
```swift
434434
public func remove() -> BinarySearchTree? {
@@ -670,7 +670,7 @@ The enum has three cases:
670670

671671
> **Note:** The nodes in this binary tree don't have a reference to their parent node. It's not a major impediment but it will make certain operations slightly more cumbersome to implement.
672672
673-
A usual, we'll implement most functionality recursively. We'll treat each case of the enum slightly differently. For example, this is how you could calculate the number of nodes in the tree and the height of the tree:
673+
As usual, we'll implement most functionality recursively. We'll treat each case of the enum slightly differently. For example, this is how you could calculate the number of nodes in the tree and the height of the tree:
674674

675675
```swift
676676
public var count: Int {

Binary Tree/BinaryTree.swift

+10
Original file line numberDiff line numberDiff line change
@@ -53,3 +53,13 @@ extension BinaryTree {
5353
}
5454
}
5555
}
56+
57+
extension BinaryTree {
58+
func invert() -> BinaryTree {
59+
if case let .Node(left, value, right) = self {
60+
return .Node(right.invert(), value, left.invert())
61+
} else {
62+
return .Empty
63+
}
64+
}
65+
}

Boyer-Moore/README.markdown

+47
Original file line numberDiff line numberDiff line change
@@ -137,4 +137,51 @@ The closer a character is to the end of the pattern, the smaller the skip amount
137137
138138
Credits: This code is based on the article ["Faster String Searches" by Costas Menico](http://www.drdobbs.com/database/faster-string-searches/184408171) from Dr Dobb's magazine, July 1989 -- Yes, 1989! Sometimes it's useful to keep those old magazines around.
139139

140+
See also: [a detailed analysis](http://www.inf.fh-flensburg.de/lang/algorithmen/pattern/bmen.htm) of the algorithm.
141+
142+
## Boyer-Moore-Horspool algorithm
143+
144+
A variation on the above algorithm is the [Boyer-Moore-Horspool algorithm](https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore%E2%80%93Horspool_algorithm).
145+
146+
Like the regular Boyer-Moore algorithm, it uses the `skipTable` to skip ahead a number of characters. The difference is in how we check partial matches. In the above version, if a partial match is found but it's not a complete match, we skip ahead by just one character. In this revised version, we also use the skip table in that situation.
147+
148+
Here's an implementation of the Boyer-Moore-Horspool algorithm:
149+
150+
```swift
151+
extension String {
152+
public func indexOf(pattern: String) -> String.Index? {
153+
let patternLength = pattern.characters.count
154+
assert(patternLength > 0)
155+
assert(patternLength <= self.characters.count)
156+
157+
var skipTable = [Character: Int]()
158+
for (i, c) in pattern.characters.dropLast().enumerate() {
159+
skipTable[c] = patternLength - i - 1
160+
}
161+
162+
var index = self.startIndex.advancedBy(patternLength - 1)
163+
164+
while index < self.endIndex {
165+
var i = index
166+
var p = pattern.endIndex.predecessor()
167+
168+
while self[i] == pattern[p] {
169+
if p == pattern.startIndex { return i }
170+
i = i.predecessor()
171+
p = p.predecessor()
172+
}
173+
174+
let advance = skipTable[self[index]] ?? patternLength
175+
index = index.advancedBy(advance)
176+
}
177+
178+
return nil
179+
}
180+
}
181+
```
182+
183+
In practice, the Horspool version of the algorithm tends to perform a little better than the original. However, it depends on the tradeoffs you're willing to make.
184+
185+
Credits: This code is based on the paper: [R. N. Horspool (1980). "Practical fast searching in strings". Software - Practice & Experience 10 (6): 501–506.](http://www.cin.br/~paguso/courses/if767/bib/Horspool_1980.pdf)
186+
140187
*Written for Swift Algorithm Club by Matthijs Hollemans*
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
//
2+
// BucketSort.playground
3+
//
4+
// Created by Barbara Rodeker on 4/4/16.
5+
//
6+
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
7+
// associated documentation files (the "Software"), to deal in the Software without restriction, including
8+
// without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
// copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
10+
// following conditions:
11+
//
12+
// The above copyright notice and this permission notice shall be included in all copies or substantial
13+
// portions of the Software.
14+
//
15+
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
16+
// LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
17+
// EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
18+
// AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
19+
// OR OTHER DEALINGS IN THE SOFTWARE.
20+
//
21+
//
22+
23+
24+
25+
26+
//////////////////////////////////////
27+
// MARK: Extensions
28+
//////////////////////////////////////
29+
30+
extension Int: IntConvertible, Sortable {
31+
public func toInt() -> Int {
32+
return self
33+
}
34+
}
35+
36+
//////////////////////////////////////
37+
// MARK: Playing code
38+
//////////////////////////////////////
39+
40+
let input = [1,2,4,6,10]
41+
let buckets = [Bucket<Int>(capacity: 15),Bucket<Int>(capacity: 15),Bucket<Int>(capacity: 15)]
42+
43+
let sortedElements = bucketSort(input, distributor: RangeDistributor(), sorter: InsertionSorter(), buckets: buckets)
44+
45+
print(sortedElements)
46+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
//
2+
// BucketSort.swift
3+
//
4+
// Created by Barbara Rodeker on 4/4/16.
5+
//
6+
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
7+
// associated documentation files (the "Software"), to deal in the Software without restriction, including
8+
// without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
// copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
10+
// following conditions:
11+
//
12+
// The above copyright notice and this permission notice shall be included in all copies or substantial
13+
// portions of the Software.
14+
//
15+
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
16+
// LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
17+
// EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
18+
// AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
19+
// OR OTHER DEALINGS IN THE SOFTWARE.
20+
//
21+
//
22+
23+
import Foundation
24+
25+
//////////////////////////////////////
26+
// MARK: Main algorithm
27+
//////////////////////////////////////
28+
29+
30+
public func bucketSort<T:Sortable>(elements: [T], distributor: Distributor,sorter: Sorter, buckets: [Bucket<T>]) -> [T] {
31+
var bucketsCopy = buckets
32+
for elem in elements {
33+
distributor.distribute(elem, buckets: &bucketsCopy)
34+
}
35+
36+
var results = [T]()
37+
38+
for bucket in buckets {
39+
results += bucket.sort(sorter)
40+
}
41+
42+
return results
43+
}
44+
45+
//////////////////////////////////////
46+
// MARK: Distributor
47+
//////////////////////////////////////
48+
49+
50+
public protocol Distributor {
51+
func distribute<T:Sortable>(element: T, inout buckets: [Bucket<T>])
52+
}
53+
54+
/*
55+
* An example of a simple distribution function that send every elements to
56+
* the bucket representing the range in which it fits.An
57+
*
58+
* If the range of values to sort is 0..<49 i.e, there could be 5 buckets of capacity = 10
59+
* So every element will be classified by the ranges:
60+
*
61+
* - 0 ..< 10
62+
* - 10 ..< 20
63+
* - 20 ..< 30
64+
* - 30 ..< 40
65+
* - 40 ..< 50
66+
*
67+
* By following the formula: element / capacity = #ofBucket
68+
*/
69+
public struct RangeDistributor: Distributor {
70+
71+
public init() {}
72+
73+
public func distribute<T:Sortable>(element: T, inout buckets: [Bucket<T>]) {
74+
let value = element.toInt()
75+
let bucketCapacity = buckets.first!.capacity
76+
77+
let bucketIndex = value / bucketCapacity
78+
buckets[bucketIndex].add(element)
79+
}
80+
}
81+
82+
//////////////////////////////////////
83+
// MARK: Sortable
84+
//////////////////////////////////////
85+
86+
public protocol IntConvertible {
87+
func toInt() -> Int
88+
}
89+
90+
public protocol Sortable: IntConvertible, Comparable {
91+
}
92+
93+
//////////////////////////////////////
94+
// MARK: Sorter
95+
//////////////////////////////////////
96+
97+
public protocol Sorter {
98+
func sort<T:Sortable>(items: [T]) -> [T]
99+
}
100+
101+
public struct InsertionSorter: Sorter {
102+
103+
public init() {}
104+
105+
public func sort<T:Sortable>(items: [T]) -> [T] {
106+
var results = items
107+
for i in 0 ..< results.count {
108+
var j = i
109+
while ( j > 0 && results[j-i] > results[j]) {
110+
111+
let auxiliar = results[i]
112+
results[i] = results[j]
113+
results[j] = auxiliar
114+
115+
j -= 1
116+
}
117+
}
118+
return results
119+
}
120+
}
121+
122+
//////////////////////////////////////
123+
// MARK: Bucket
124+
//////////////////////////////////////
125+
126+
public struct Bucket<T:Sortable> {
127+
var elements: [T]
128+
let capacity: Int
129+
130+
public init(capacity: Int) {
131+
self.capacity = capacity
132+
elements = [T]()
133+
}
134+
135+
public mutating func add(item: T) {
136+
if (elements.count < capacity) {
137+
elements.append(item)
138+
}
139+
}
140+
141+
public func sort(algorithm: Sorter) -> [T] {
142+
return algorithm.sort(elements)
143+
}
144+
}
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>

0 commit comments

Comments
 (0)