diff --git a/Array2D/Array2D.playground/Contents.swift b/Array2D/Array2D.playground/Contents.swift index d088c99af..1a6a439bd 100644 --- a/Array2D/Array2D.playground/Contents.swift +++ b/Array2D/Array2D.playground/Contents.swift @@ -7,13 +7,13 @@ public struct Array2D { public let columns: Int public let rows: Int fileprivate var array: [T] - + public init(columns: Int, rows: Int, initialValue: T) { self.columns = columns self.rows = rows array = .init(repeating: initialValue, count: rows*columns) } - + public subscript(column: Int, row: Int) -> T { get { precondition(column < columns, "Column \(column) Index is out of range. Array(columns: \(columns), rows:\(rows))") diff --git a/Array2D/Array2D.swift b/Array2D/Array2D.swift index df4822916..caff8373c 100644 --- a/Array2D/Array2D.swift +++ b/Array2D/Array2D.swift @@ -7,13 +7,13 @@ public struct Array2D { public let columns: Int public let rows: Int fileprivate var array: [T] - + public init(columns: Int, rows: Int, initialValue: T) { self.columns = columns self.rows = rows array = .init(repeating: initialValue, count: rows*columns) } - + public subscript(column: Int, row: Int) -> T { get { precondition(column < columns, "Column \(column) Index is out of range. Array(columns: \(columns), rows:\(rows))") diff --git a/B-Tree/BTree.playground/Sources/BTree.swift b/B-Tree/BTree.playground/Sources/BTree.swift index 52cda4e43..2693eb308 100644 --- a/B-Tree/BTree.playground/Sources/BTree.swift +++ b/B-Tree/BTree.playground/Sources/BTree.swift @@ -33,23 +33,23 @@ class BTreeNode { * The tree that owns the node. */ unowned var owner: BTree - + fileprivate var keys = [Key]() fileprivate var values = [Value]() var children: [BTreeNode]? - + var isLeaf: Bool { return children == nil } - + var numberOfKeys: Int { return keys.count } - + init(owner: BTree) { self.owner = owner } - + convenience init(owner: BTree, keys: [Key], values: [Value], children: [BTreeNode]? = nil) { self.init(owner: owner) @@ -62,7 +62,7 @@ class BTreeNode { // MARK: BTreeNode extesnion: Searching extension BTreeNode { - + /** * Returns the value for a given `key`, returns nil if the `key` is not found. * @@ -71,11 +71,11 @@ extension BTreeNode { */ func value(for key: Key) -> Value? { var index = keys.startIndex - + while (index + 1) < keys.endIndex && keys[index] < key { index = (index + 1) } - + if key == keys[index] { return values[index] } else if key < keys[index] { @@ -89,7 +89,7 @@ extension BTreeNode { // MARK: BTreeNode extension: Travelsals extension BTreeNode { - + /** * Traverses the keys in order, executes `process` for every key. * @@ -101,7 +101,7 @@ extension BTreeNode { children?[i].traverseKeysInOrder(process) process(keys[i]) } - + children?.last?.traverseKeysInOrder(process) } } @@ -109,7 +109,7 @@ extension BTreeNode { // MARK: BTreeNode extension: Insertion extension BTreeNode { - + /** * Inserts `value` for `key` to the node, or to one if its descendants. * @@ -119,16 +119,16 @@ extension BTreeNode { */ func insert(_ value: Value, for key: Key) { var index = keys.startIndex - + while index < keys.endIndex && keys[index] < key { index = (index + 1) } - + if index < keys.endIndex && keys[index] == key { values[index] = value return } - + if isLeaf { keys.insert(key, at: index) values.insert(value, at: index) @@ -140,7 +140,7 @@ extension BTreeNode { } } } - + /** * Splits `child` at `index`. * The key-value pair at `index` gets moved up to the parent node, @@ -156,7 +156,7 @@ extension BTreeNode { values.insert(child.values[middleIndex], at: index) child.keys.remove(at: middleIndex) child.values.remove(at: middleIndex) - + let rightSibling = BTreeNode( owner: owner, keys: Array(child.keys[child.keys.indices.suffix(from: middleIndex)]), @@ -164,9 +164,9 @@ extension BTreeNode { ) child.keys.removeSubrange(child.keys.indices.suffix(from: middleIndex)) child.values.removeSubrange(child.values.indices.suffix(from: middleIndex)) - + children!.insert(rightSibling, at: (index + 1)) - + if child.children != nil { rightSibling.children = Array( child.children![child.children!.indices.suffix(from: (middleIndex + 1))] @@ -198,7 +198,7 @@ extension BTreeNode { return children!.last!.inorderPredecessor } } - + /** * Removes `key` and the value associated with it from the node * or one of its descendants. @@ -208,11 +208,11 @@ extension BTreeNode { */ func remove(_ key: Key) { var index = keys.startIndex - + while (index + 1) < keys.endIndex && keys[index] < key { index = (index + 1) } - + if keys[index] == key { if isLeaf { keys.remove(at: index) @@ -229,7 +229,7 @@ extension BTreeNode { } } else if key < keys[index] { // We should go to left child... - + if let leftChild = children?[index] { leftChild.remove(key) if leftChild.numberOfKeys < owner.order { @@ -240,7 +240,7 @@ extension BTreeNode { } } else { // We should go to right child... - + if let rightChild = children?[(index + 1)] { rightChild.remove(key) if rightChild.numberOfKeys < owner.order { @@ -251,7 +251,7 @@ extension BTreeNode { } } } - + /** * Fixes `childWithTooFewKeys` by either moving a key to it from * one of its neighbouring nodes, or by merging. @@ -264,7 +264,7 @@ extension BTreeNode { * - index: the index of the child to be fixed in the current node */ private func fix(childWithTooFewKeys child: BTreeNode, atIndex index: Int) { - + if (index - 1) >= 0 && children![(index - 1)].numberOfKeys > owner.order { move(keyAtIndex: (index - 1), to: child, from: children![(index - 1)], at: .left) } else if (index + 1) < children!.count && children![(index + 1)].numberOfKeys > owner.order { @@ -275,7 +275,7 @@ extension BTreeNode { merge(child: child, atIndex: index, to: .right) } } - + /** * Moves the key at the specified `index` from `node` to * the `targetNode` at `position` @@ -301,7 +301,7 @@ extension BTreeNode { at: targetNode.children!.startIndex) node.children!.removeLast() } - + case .right: targetNode.keys.insert(keys[index], at: targetNode.keys.endIndex) targetNode.values.insert(values[index], at: targetNode.values.endIndex) @@ -316,7 +316,7 @@ extension BTreeNode { } } } - + /** * Merges `child` at `position` to the node at the `position`. * @@ -329,33 +329,33 @@ extension BTreeNode { switch position { case .left: // We can merge to the left sibling - + children![(index - 1)].keys = children![(index - 1)].keys + [keys[(index - 1)]] + child.keys - + children![(index - 1)].values = children![(index - 1)].values + [values[(index - 1)]] + child.values - + keys.remove(at: (index - 1)) values.remove(at: (index - 1)) - + if !child.isLeaf { children![(index - 1)].children = children![(index - 1)].children! + child.children! } - + case .right: // We should merge to the right sibling - + children![(index + 1)].keys = child.keys + [keys[index]] + children![(index + 1)].keys - + children![(index + 1)].values = child.values + [values[index]] + children![(index + 1)].values - + keys.remove(at: index) values.remove(at: index) - + if !child.isLeaf { children![(index + 1)].children = child.children! + children![(index + 1)].children! @@ -374,18 +374,18 @@ extension BTreeNode { */ var inorderArrayFromKeys: [Key] { var array = [Key] () - + for i in 0.. { * except the root node which is allowed to contain less keys than the value of order. */ public let order: Int - + /** * The root node of the tree */ var rootNode: BTreeNode! - + fileprivate(set) public var numberOfKeys = 0 - + /** * Designated initializer for the tree * @@ -484,7 +484,7 @@ extension BTree { guard rootNode.numberOfKeys > 0 else { return nil } - + return rootNode.value(for: key) } } @@ -501,12 +501,12 @@ extension BTree { */ public func insert(_ value: Value, for key: Key) { rootNode.insert(value, for: key) - + if rootNode.numberOfKeys > order * 2 { splitRoot() } } - + /** * Splits the root node of the tree. * @@ -515,7 +515,7 @@ extension BTree { */ private func splitRoot() { let middleIndexOfOldRoot = rootNode.numberOfKeys / 2 - + let newRoot = BTreeNode( owner: self, keys: [rootNode.keys[middleIndexOfOldRoot]], @@ -524,7 +524,7 @@ extension BTree { ) rootNode.keys.remove(at: middleIndexOfOldRoot) rootNode.values.remove(at: middleIndexOfOldRoot) - + let newRightChild = BTreeNode( owner: self, keys: Array(rootNode.keys[rootNode.keys.indices.suffix(from: middleIndexOfOldRoot)]), @@ -532,7 +532,7 @@ extension BTree { ) rootNode.keys.removeSubrange(rootNode.keys.indices.suffix(from: middleIndexOfOldRoot)) rootNode.values.removeSubrange(rootNode.values.indices.suffix(from: middleIndexOfOldRoot)) - + if rootNode.children != nil { newRightChild.children = Array( rootNode.children![rootNode.children!.indices.suffix(from: (middleIndexOfOldRoot + 1))] @@ -541,7 +541,7 @@ extension BTree { rootNode.children!.indices.suffix(from: (middleIndexOfOldRoot + 1)) ) } - + newRoot.children!.append(newRightChild) rootNode = newRoot } @@ -560,9 +560,9 @@ extension BTree { guard rootNode.numberOfKeys > 0 else { return } - + rootNode.remove(key) - + if rootNode.numberOfKeys == 0 && !rootNode.isLeaf { rootNode = rootNode.children!.first! } diff --git a/B-Tree/BTree.swift b/B-Tree/BTree.swift index 52cda4e43..2693eb308 100644 --- a/B-Tree/BTree.swift +++ b/B-Tree/BTree.swift @@ -33,23 +33,23 @@ class BTreeNode { * The tree that owns the node. */ unowned var owner: BTree - + fileprivate var keys = [Key]() fileprivate var values = [Value]() var children: [BTreeNode]? - + var isLeaf: Bool { return children == nil } - + var numberOfKeys: Int { return keys.count } - + init(owner: BTree) { self.owner = owner } - + convenience init(owner: BTree, keys: [Key], values: [Value], children: [BTreeNode]? = nil) { self.init(owner: owner) @@ -62,7 +62,7 @@ class BTreeNode { // MARK: BTreeNode extesnion: Searching extension BTreeNode { - + /** * Returns the value for a given `key`, returns nil if the `key` is not found. * @@ -71,11 +71,11 @@ extension BTreeNode { */ func value(for key: Key) -> Value? { var index = keys.startIndex - + while (index + 1) < keys.endIndex && keys[index] < key { index = (index + 1) } - + if key == keys[index] { return values[index] } else if key < keys[index] { @@ -89,7 +89,7 @@ extension BTreeNode { // MARK: BTreeNode extension: Travelsals extension BTreeNode { - + /** * Traverses the keys in order, executes `process` for every key. * @@ -101,7 +101,7 @@ extension BTreeNode { children?[i].traverseKeysInOrder(process) process(keys[i]) } - + children?.last?.traverseKeysInOrder(process) } } @@ -109,7 +109,7 @@ extension BTreeNode { // MARK: BTreeNode extension: Insertion extension BTreeNode { - + /** * Inserts `value` for `key` to the node, or to one if its descendants. * @@ -119,16 +119,16 @@ extension BTreeNode { */ func insert(_ value: Value, for key: Key) { var index = keys.startIndex - + while index < keys.endIndex && keys[index] < key { index = (index + 1) } - + if index < keys.endIndex && keys[index] == key { values[index] = value return } - + if isLeaf { keys.insert(key, at: index) values.insert(value, at: index) @@ -140,7 +140,7 @@ extension BTreeNode { } } } - + /** * Splits `child` at `index`. * The key-value pair at `index` gets moved up to the parent node, @@ -156,7 +156,7 @@ extension BTreeNode { values.insert(child.values[middleIndex], at: index) child.keys.remove(at: middleIndex) child.values.remove(at: middleIndex) - + let rightSibling = BTreeNode( owner: owner, keys: Array(child.keys[child.keys.indices.suffix(from: middleIndex)]), @@ -164,9 +164,9 @@ extension BTreeNode { ) child.keys.removeSubrange(child.keys.indices.suffix(from: middleIndex)) child.values.removeSubrange(child.values.indices.suffix(from: middleIndex)) - + children!.insert(rightSibling, at: (index + 1)) - + if child.children != nil { rightSibling.children = Array( child.children![child.children!.indices.suffix(from: (middleIndex + 1))] @@ -198,7 +198,7 @@ extension BTreeNode { return children!.last!.inorderPredecessor } } - + /** * Removes `key` and the value associated with it from the node * or one of its descendants. @@ -208,11 +208,11 @@ extension BTreeNode { */ func remove(_ key: Key) { var index = keys.startIndex - + while (index + 1) < keys.endIndex && keys[index] < key { index = (index + 1) } - + if keys[index] == key { if isLeaf { keys.remove(at: index) @@ -229,7 +229,7 @@ extension BTreeNode { } } else if key < keys[index] { // We should go to left child... - + if let leftChild = children?[index] { leftChild.remove(key) if leftChild.numberOfKeys < owner.order { @@ -240,7 +240,7 @@ extension BTreeNode { } } else { // We should go to right child... - + if let rightChild = children?[(index + 1)] { rightChild.remove(key) if rightChild.numberOfKeys < owner.order { @@ -251,7 +251,7 @@ extension BTreeNode { } } } - + /** * Fixes `childWithTooFewKeys` by either moving a key to it from * one of its neighbouring nodes, or by merging. @@ -264,7 +264,7 @@ extension BTreeNode { * - index: the index of the child to be fixed in the current node */ private func fix(childWithTooFewKeys child: BTreeNode, atIndex index: Int) { - + if (index - 1) >= 0 && children![(index - 1)].numberOfKeys > owner.order { move(keyAtIndex: (index - 1), to: child, from: children![(index - 1)], at: .left) } else if (index + 1) < children!.count && children![(index + 1)].numberOfKeys > owner.order { @@ -275,7 +275,7 @@ extension BTreeNode { merge(child: child, atIndex: index, to: .right) } } - + /** * Moves the key at the specified `index` from `node` to * the `targetNode` at `position` @@ -301,7 +301,7 @@ extension BTreeNode { at: targetNode.children!.startIndex) node.children!.removeLast() } - + case .right: targetNode.keys.insert(keys[index], at: targetNode.keys.endIndex) targetNode.values.insert(values[index], at: targetNode.values.endIndex) @@ -316,7 +316,7 @@ extension BTreeNode { } } } - + /** * Merges `child` at `position` to the node at the `position`. * @@ -329,33 +329,33 @@ extension BTreeNode { switch position { case .left: // We can merge to the left sibling - + children![(index - 1)].keys = children![(index - 1)].keys + [keys[(index - 1)]] + child.keys - + children![(index - 1)].values = children![(index - 1)].values + [values[(index - 1)]] + child.values - + keys.remove(at: (index - 1)) values.remove(at: (index - 1)) - + if !child.isLeaf { children![(index - 1)].children = children![(index - 1)].children! + child.children! } - + case .right: // We should merge to the right sibling - + children![(index + 1)].keys = child.keys + [keys[index]] + children![(index + 1)].keys - + children![(index + 1)].values = child.values + [values[index]] + children![(index + 1)].values - + keys.remove(at: index) values.remove(at: index) - + if !child.isLeaf { children![(index + 1)].children = child.children! + children![(index + 1)].children! @@ -374,18 +374,18 @@ extension BTreeNode { */ var inorderArrayFromKeys: [Key] { var array = [Key] () - + for i in 0.. { * except the root node which is allowed to contain less keys than the value of order. */ public let order: Int - + /** * The root node of the tree */ var rootNode: BTreeNode! - + fileprivate(set) public var numberOfKeys = 0 - + /** * Designated initializer for the tree * @@ -484,7 +484,7 @@ extension BTree { guard rootNode.numberOfKeys > 0 else { return nil } - + return rootNode.value(for: key) } } @@ -501,12 +501,12 @@ extension BTree { */ public func insert(_ value: Value, for key: Key) { rootNode.insert(value, for: key) - + if rootNode.numberOfKeys > order * 2 { splitRoot() } } - + /** * Splits the root node of the tree. * @@ -515,7 +515,7 @@ extension BTree { */ private func splitRoot() { let middleIndexOfOldRoot = rootNode.numberOfKeys / 2 - + let newRoot = BTreeNode( owner: self, keys: [rootNode.keys[middleIndexOfOldRoot]], @@ -524,7 +524,7 @@ extension BTree { ) rootNode.keys.remove(at: middleIndexOfOldRoot) rootNode.values.remove(at: middleIndexOfOldRoot) - + let newRightChild = BTreeNode( owner: self, keys: Array(rootNode.keys[rootNode.keys.indices.suffix(from: middleIndexOfOldRoot)]), @@ -532,7 +532,7 @@ extension BTree { ) rootNode.keys.removeSubrange(rootNode.keys.indices.suffix(from: middleIndexOfOldRoot)) rootNode.values.removeSubrange(rootNode.values.indices.suffix(from: middleIndexOfOldRoot)) - + if rootNode.children != nil { newRightChild.children = Array( rootNode.children![rootNode.children!.indices.suffix(from: (middleIndexOfOldRoot + 1))] @@ -541,7 +541,7 @@ extension BTree { rootNode.children!.indices.suffix(from: (middleIndexOfOldRoot + 1)) ) } - + newRoot.children!.append(newRightChild) rootNode = newRoot } @@ -560,9 +560,9 @@ extension BTree { guard rootNode.numberOfKeys > 0 else { return } - + rootNode.remove(key) - + if rootNode.numberOfKeys == 0 && !rootNode.isLeaf { rootNode = rootNode.children!.first! } diff --git a/B-Tree/Tests/Tests/BTreeNodeTests.swift b/B-Tree/Tests/Tests/BTreeNodeTests.swift index fd3ba10e8..8eff926b5 100644 --- a/B-Tree/Tests/Tests/BTreeNodeTests.swift +++ b/B-Tree/Tests/Tests/BTreeNodeTests.swift @@ -9,44 +9,44 @@ import XCTest class BTreeNodeTests: XCTestCase { - + let owner = BTree(order: 2)! var root: BTreeNode! var leftChild: BTreeNode! var rightChild: BTreeNode! - + override func setUp() { super.setUp() - + root = BTreeNode(owner: owner) leftChild = BTreeNode(owner: owner) rightChild = BTreeNode(owner: owner) - + root.insert(1, for: 1) root.children = [leftChild, rightChild] } - + func testIsLeafRoot() { XCTAssertFalse(root.isLeaf) } - + func testIsLeafLeaf() { XCTAssertTrue(leftChild.isLeaf) XCTAssertTrue(rightChild.isLeaf) } - + func testOwner() { XCTAssert(root.owner === owner) XCTAssert(leftChild.owner === owner) XCTAssert(rightChild.owner === owner) } - + func testNumberOfKeys() { XCTAssertEqual(root.numberOfKeys, 1) XCTAssertEqual(leftChild.numberOfKeys, 0) XCTAssertEqual(rightChild.numberOfKeys, 0) } - + func testChildren() { XCTAssertEqual(root.children!.count, 2) } diff --git a/B-Tree/Tests/Tests/BTreeTests.swift b/B-Tree/Tests/Tests/BTreeTests.swift index f2dac7511..1e94bfd7d 100644 --- a/B-Tree/Tests/Tests/BTreeTests.swift +++ b/B-Tree/Tests/Tests/BTreeTests.swift @@ -10,201 +10,201 @@ import XCTest class BTreeTests: XCTestCase { var bTree: BTree! - + override func setUp() { super.setUp() bTree = BTree(order: 3)! } - + // MARK: - Tests on empty tree - + func testOrder() { XCTAssertEqual(bTree.order, 3) } - + func testRootNode() { XCTAssertNotNil(bTree.rootNode) } - + func testNumberOfNodesOnEmptyTree() { XCTAssertEqual(bTree.numberOfKeys, 0) } - + func testInorderTraversalOfEmptyTree() { bTree.traverseKeysInOrder { _ in XCTFail("Inorder travelsal fail.") } } - + func testSubscriptOnEmptyTree() { XCTAssertEqual(bTree[1], nil) } - + func testSearchEmptyTree() { XCTAssertEqual(bTree.value(for: 1), nil) } - + func testInsertToEmptyTree() { bTree.insert(1, for: 1) - + XCTAssertEqual(bTree[1]!, 1) } - + func testRemoveFromEmptyTree() { bTree.remove(1) XCTAssertEqual(bTree.description, "[]") } - + func testInorderArrayFromEmptyTree() { XCTAssertEqual(bTree.inorderArrayFromKeys, [Int]()) } - + func testDescriptionOfEmptyTree() { XCTAssertEqual(bTree.description, "[]") } - + // MARK: - Travelsal - + func testInorderTravelsal() { for i in 1...20 { bTree.insert(i, for: i) } - + var j = 1 - + bTree.traverseKeysInOrder { i in XCTAssertEqual(i, j) j += 1 } } - + // MARK: - Searching - + func testSearchForMaximum() { for i in 1...20 { bTree.insert(i, for: i) } - + XCTAssertEqual(bTree.value(for: 20)!, 20) } - + func testSearchForMinimum() { for i in 1...20 { bTree.insert(i, for: i) } - + XCTAssertEqual(bTree.value(for: 1)!, 1) } - + // MARK: - Insertion - + func testInsertion() { bTree.insertKeysUpTo(20) - + XCTAssertEqual(bTree.numberOfKeys, 20) - + for i in 1...20 { XCTAssertNotNil(bTree[i]) } - + do { try bTree.checkBalance() } catch { XCTFail("BTree is not balanced") } } - + // MARK: - Removal - + func testRemoveMaximum() { for i in 1...20 { bTree.insert(i, for: i) } - + bTree.remove(20) - + XCTAssertNil(bTree[20]) - + do { try bTree.checkBalance() } catch { XCTFail("BTree is not balanced") } } - + func testRemoveMinimum() { bTree.insertKeysUpTo(20) - + bTree.remove(1) - + XCTAssertNil(bTree[1]) - + do { try bTree.checkBalance() } catch { XCTFail("BTree is not balanced") } } - + func testRemoveSome() { bTree.insertKeysUpTo(20) - + bTree.remove(6) bTree.remove(9) - + XCTAssertNil(bTree[6]) XCTAssertNil(bTree[9]) - + do { try bTree.checkBalance() } catch { XCTFail("BTree is not balanced") } } - + func testRemoveSomeFrom2ndOrder() { bTree = BTree(order: 2)! bTree.insertKeysUpTo(20) - + bTree.remove(6) bTree.remove(9) - + XCTAssertNil(bTree[6]) XCTAssertNil(bTree[9]) - + do { try bTree.checkBalance() } catch { XCTFail("BTree is not balanced") } } - + func testRemoveAll() { bTree.insertKeysUpTo(20) - + XCTAssertEqual(bTree.numberOfKeys, 20) - + for i in (1...20).reversed() { bTree.remove(i) } - + do { try bTree.checkBalance() } catch { XCTFail("BTree is not balanced") } - + XCTAssertEqual(bTree.numberOfKeys, 0) } - + // MARK: - InorderArray - + func testInorderArray() { bTree.insertKeysUpTo(20) - + let returnedArray = bTree.inorderArrayFromKeys let targetArray = Array(1...20) - + XCTAssertEqual(returnedArray, targetArray) } } @@ -221,7 +221,7 @@ extension BTreeNode { } else if !root && numberOfKeys < owner.order { throw BTreeError.tooFewNodes } - + if !isLeaf { for child in children! { try child.checkBalance(isRoot: false) @@ -234,14 +234,14 @@ extension BTree where Key: SignedInteger, Value: SignedInteger { func insertKeysUpTo(_ to: Int) { var k: Key = 1 var v: Value = 1 - + for _ in 1...to { insert(v, for: k) k = k + 1 v = v + 1 } } - + func checkBalance() throws { try rootNode.checkBalance(isRoot: true) } diff --git a/Brute-Force String Search/BruteForceStringSearch.playground/Contents.swift b/Brute-Force String Search/BruteForceStringSearch.playground/Contents.swift index 00ac6da97..b9f2b1432 100644 --- a/Brute-Force String Search/BruteForceStringSearch.playground/Contents.swift +++ b/Brute-Force String Search/BruteForceStringSearch.playground/Contents.swift @@ -2,7 +2,7 @@ extension String { func indexOf(_ pattern: String) -> String.Index? { - + for i in self.characters.indices { var j = i var found = true diff --git a/Comb Sort/Comb Sort.playground/Sources/Comb Sort.swift b/Comb Sort/Comb Sort.playground/Sources/Comb Sort.swift index b6e85fa2b..f7c4eec61 100644 --- a/Comb Sort/Comb Sort.playground/Sources/Comb Sort.swift +++ b/Comb Sort/Comb Sort.playground/Sources/Comb Sort.swift @@ -11,13 +11,13 @@ public func combSort(_ input: [T]) -> [T] { var copy: [T] = input var gap = copy.count let shrink = 1.3 - + while gap > 1 { gap = (Int)(Double(gap) / shrink) if gap < 1 { gap = 1 } - + var index = 0 while !(index + gap >= copy.count) { if copy[index] > copy[index + gap] { diff --git a/Comb Sort/Comb Sort.swift b/Comb Sort/Comb Sort.swift index b6e85fa2b..f7c4eec61 100644 --- a/Comb Sort/Comb Sort.swift +++ b/Comb Sort/Comb Sort.swift @@ -11,13 +11,13 @@ public func combSort(_ input: [T]) -> [T] { var copy: [T] = input var gap = copy.count let shrink = 1.3 - + while gap > 1 { gap = (Int)(Double(gap) / shrink) if gap < 1 { gap = 1 } - + var index = 0 while !(index + gap >= copy.count) { if copy[index] > copy[index + gap] { diff --git a/Comb Sort/Tests/CombSortTests.swift b/Comb Sort/Tests/CombSortTests.swift index 1bcc67fd0..b9287f84a 100644 --- a/Comb Sort/Tests/CombSortTests.swift +++ b/Comb Sort/Tests/CombSortTests.swift @@ -16,7 +16,7 @@ class CombSortTests: XCTestCase { super.setUp() sequence = [2, 32, 9, -1, 89, 101, 55, -10, -12, 67] } - + override func tearDown() { super.tearDown() } diff --git a/Convex Hull/Convex Hull/AppDelegate.swift b/Convex Hull/Convex Hull/AppDelegate.swift index 4f8496cd5..bfe15e1a7 100644 --- a/Convex Hull/Convex Hull/AppDelegate.swift +++ b/Convex Hull/Convex Hull/AppDelegate.swift @@ -17,16 +17,16 @@ class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let screenBounds = UIScreen.main.bounds - + window = UIWindow(frame: screenBounds) - + let viewController = UIViewController() viewController.view = View(frame: (window?.frame)!) viewController.view.backgroundColor = .white - + window?.rootViewController = viewController window?.makeKeyAndVisible() - + return true } diff --git a/Convex Hull/Convex Hull/View.swift b/Convex Hull/Convex Hull/View.swift index f9f9f6ef4..2f2c3e046 100644 --- a/Convex Hull/Convex Hull/View.swift +++ b/Convex Hull/Convex Hull/View.swift @@ -9,24 +9,24 @@ import UIKit class View: UIView { - + let MAX_POINTS = 100 - + var points = [CGPoint]() - + var convexHull = [CGPoint]() - + override init(frame: CGRect) { super.init(frame: frame) - + generatePoints() quickHull(points: points) } - + required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } - + func generatePoints() { for _ in 0.. Bool in return a.x < b.x } } - + func quickHull(points: [CGPoint]) { var pts = points - + // Assume points has at least 2 points // Assume list is ordered on x - + // left most point let p1 = pts.removeFirst() // right most point let p2 = pts.removeLast() - + // p1 and p2 are outer most points and thus are part of the hull convexHull.append(p1) convexHull.append(p2) - + // points to the right of oriented line from p1 to p2 var s1 = [CGPoint]() - + // points to the right of oriented line from p2 to p1 var s2 = [CGPoint]() - + // p1 to p2 line let lineVec1 = CGPoint(x: p2.x - p1.x, y: p2.y - p1.y) - + for p in pts { // per point check if point is to right or left of p1 to p2 line let pVec1 = CGPoint(x: p.x - p1.x, y: p.y - p1.y) let sign1 = lineVec1.x * pVec1.y - pVec1.x * lineVec1.y // cross product to check on which side of the line point p is. - + if sign1 > 0 { // right of p1 p2 line (in a normal xy coordinate system this would be < 0 but due to the weird iPhone screen coordinates this is > 0 s1.append(p) } else { // right of p2 p1 line s2.append(p) } } - + // find new hull points findHull(s1, p1, p2) findHull(s2, p2, p1) } - + func findHull(_ points: [CGPoint], _ p1: CGPoint, _ p2: CGPoint) { // if set of points is empty there are no points to the right of this line so this line is part of the hull. if points.isEmpty { return } - + var pts = points - + // calculate parameters of general line equation y = a * x + b let a = (p1.y - p2.y) / (p1.x - p2.x) let b = p1.y - a * p1.x - + // calculate normal line's growth factor let a1 = -1 / a - + var maxDist: CGFloat = -1 var maxPoint: CGPoint = pts.first! - + for p in pts { // for every point check the distance from our line let b1 = p.y - a1 * p.x // calculate offset to line equation for given point p let x = -(b - b1)/(a - a1) // calculate x where the two lines intersect let y = a * x + b // calculate y value of this intersect point - + let dist = pow(x - p.x, 2) + pow(y - p.y, 2) // calculate distance squared between intersection point and point p if dist > maxDist { // if distance is larger than current maxDist remember new point p maxDist = dist maxPoint = p } } - + convexHull.insert(maxPoint, at: convexHull.index(of: p1)! + 1) // insert point with max distance from line in the convexHull after p1 - + pts.remove(at: pts.index(of: maxPoint)!) // remove maxPoint from points array as we are going to split this array in points left and right of the line - + // points to the right of oriented line from p1 to maxPoint var s1 = [CGPoint]() - + // points to the right of oriented line from maxPoint to p2 var s2 = [CGPoint]() - + // p1 to maxPoint line let lineVec1 = CGPoint(x: maxPoint.x - p1.x, y: maxPoint.y - p1.y) // maxPoint to p2 line let lineVec2 = CGPoint(x: p2.x - maxPoint.x, y: p2.y - maxPoint.y) - + for p in pts { let pVec1 = CGPoint(x: p.x - p1.x, y: p.y - p1.y) // vector from p1 to p let sign1 = lineVec1.x * pVec1.y - pVec1.x * lineVec1.y // sign to check is p is to the right or left of lineVec1 - + let pVec2 = CGPoint(x: p.x - maxPoint.x, y: p.y - maxPoint.y) // vector from p2 to p let sign2 = lineVec2.x * pVec2.y - pVec2.x * lineVec2.y // sign to check is p is to the right or left of lineVec2 @@ -139,34 +139,34 @@ class View: UIView { s2.append(p) } } - + // find new hull points findHull(s1, p1, maxPoint) findHull(s2, maxPoint, p2) } override func draw(_ rect: CGRect) { - + let context = UIGraphicsGetCurrentContext() - + // Draw hull let lineWidth: CGFloat = 2.0 - + context!.setFillColor(UIColor.black.cgColor) context!.setLineWidth(lineWidth) context!.setStrokeColor(UIColor.red.cgColor) context!.setFillColor(UIColor.black.cgColor) - + let firstPoint = convexHull.first! context!.move(to: firstPoint) - + for p in convexHull.dropFirst() { context!.addLine(to: p) } context!.addLine(to: firstPoint) - + context!.strokePath() - + // Draw points for p in points { let radius: CGFloat = 5 diff --git a/Fixed Size Array/FixedSizeArray.playground/Contents.swift b/Fixed Size Array/FixedSizeArray.playground/Contents.swift index 4bc5d66df..8ef545e45 100644 --- a/Fixed Size Array/FixedSizeArray.playground/Contents.swift +++ b/Fixed Size Array/FixedSizeArray.playground/Contents.swift @@ -10,25 +10,25 @@ struct FixedSizeArray { private var defaultValue: T private var array: [T] private (set) var count = 0 - + init(maxSize: Int, defaultValue: T) { self.maxSize = maxSize self.defaultValue = defaultValue self.array = [T](repeating: defaultValue, count: maxSize) } - + subscript(index: Int) -> T { assert(index >= 0) assert(index < count) return array[index] } - + mutating func append(_ newElement: T) { assert(count < maxSize) array[count] = newElement count += 1 } - + mutating func removeAt(index: Int) -> T { assert(index >= 0) assert(index < count) @@ -38,7 +38,7 @@ struct FixedSizeArray { array[count] = defaultValue return result } - + mutating func removeAll() { for i in 0..(), AdjacencyListGraph()] { - + let v1 = graph.createVertex(1) let v2 = graph.createVertex(2) let v3 = graph.createVertex(3) diff --git a/Hash Set/HashSet.playground/Sources/HashSet.swift b/Hash Set/HashSet.playground/Sources/HashSet.swift index c3365110b..3ccaa94ea 100644 --- a/Hash Set/HashSet.playground/Sources/HashSet.swift +++ b/Hash Set/HashSet.playground/Sources/HashSet.swift @@ -2,31 +2,31 @@ public struct HashSet { fileprivate var dictionary = Dictionary() - + public init() { - + } - + public mutating func insert(_ element: T) { dictionary[element] = true } - + public mutating func remove(_ element: T) { dictionary[element] = nil } - + public func contains(_ element: T) -> Bool { return dictionary[element] != nil } - + public func allElements() -> [T] { return Array(dictionary.keys) } - + public var count: Int { return dictionary.count } - + public var isEmpty: Bool { return dictionary.isEmpty } diff --git a/Hash Table/HashTable.playground/Sources/HashTable.swift b/Hash Table/HashTable.playground/Sources/HashTable.swift index 947737c32..2383b8192 100644 --- a/Hash Table/HashTable.playground/Sources/HashTable.swift +++ b/Hash Table/HashTable.playground/Sources/HashTable.swift @@ -34,19 +34,19 @@ public struct HashTable: CustomStringConvertible { private typealias Element = (key: Key, value: Value) private typealias Bucket = [Element] private var buckets: [Bucket] - + /// The number of key-value pairs in the hash table. private(set) public var count = 0 - + /// A Boolean value that indicates whether the hash table is empty. public var isEmpty: Bool { return count == 0 } - + /// A string that represents the contents of the hash table. public var description: String { let pairs = buckets.flatMap { b in b.map { e in "\(e.key) = \(e.value)" } } return pairs.joined(separator: ", ") } - + /// A string that represents the contents of /// the hash table, suitable for debugging. public var debugDescription: String { @@ -57,7 +57,7 @@ public struct HashTable: CustomStringConvertible { } return str } - + /** Create a hash table with the given capacity. */ @@ -65,7 +65,7 @@ public struct HashTable: CustomStringConvertible { assert(capacity > 0) buckets = Array(repeatElement([], count: capacity)) } - + /** Accesses the value associated with the given key for reading and writing. @@ -82,7 +82,7 @@ public struct HashTable: CustomStringConvertible { } } } - + /** Returns the value for the given key. */ @@ -95,14 +95,14 @@ public struct HashTable: CustomStringConvertible { } return nil // key not in hash table } - + /** Updates the value stored in the hash table for the given key, or adds a new key-value pair if the key does not exist. */ @discardableResult public mutating func updateValue(_ value: Value, forKey key: Key) -> Value? { let index = self.index(forKey: key) - + // Do we already have this key in the bucket? for (i, element) in buckets[index].enumerated() { if element.key == key { @@ -111,20 +111,20 @@ public struct HashTable: CustomStringConvertible { return oldValue } } - + // This key isn't in the bucket yet; add it to the chain. buckets[index].append((key: key, value: value)) count += 1 return nil } - + /** Removes the given key and its associated value from the hash table. */ @discardableResult public mutating func removeValue(forKey key: Key) -> Value? { let index = self.index(forKey: key) - + // Find the element in the bucket's chain and remove it. for (i, element) in buckets[index].enumerated() { if element.key == key { @@ -135,7 +135,7 @@ public struct HashTable: CustomStringConvertible { } return nil // key not in hash table } - + /** Removes all key-value pairs from the hash table. */ @@ -143,7 +143,7 @@ public struct HashTable: CustomStringConvertible { buckets = Array(repeatElement([], count: buckets.count)) count = 0 } - + /** Returns the given key's array index. */ diff --git a/HaversineDistance/HaversineDistance.playground/Contents.swift b/HaversineDistance/HaversineDistance.playground/Contents.swift index a6effb7b0..449fa366d 100644 --- a/HaversineDistance/HaversineDistance.playground/Contents.swift +++ b/HaversineDistance/HaversineDistance.playground/Contents.swift @@ -1,25 +1,25 @@ import UIKit func haversineDinstance(la1: Double, lo1: Double, la2: Double, lo2: Double, radius: Double = 6367444.7) -> Double { - + let haversin = { (angle: Double) -> Double in return (1 - cos(angle))/2 } - + let ahaversin = { (angle: Double) -> Double in return 2*asin(sqrt(angle)) } - + // Converts from degrees to radians let dToR = { (angle: Double) -> Double in return (angle / 360) * 2 * M_PI } - + let lat1 = dToR(la1) let lon1 = dToR(lo1) let lat2 = dToR(la2) let lon2 = dToR(lo2) - + return radius * ahaversin(haversin(lat2 - lat1) + cos(lat1) * cos(lat2) * haversin(lon2 - lon1)) } diff --git a/Heap/Heap.swift b/Heap/Heap.swift index fa30df362..80b40c65f 100644 --- a/Heap/Heap.swift +++ b/Heap/Heap.swift @@ -113,7 +113,7 @@ public struct Heap { */ public mutating func replace(index i: Int, value: T) { guard i < elements.count else { return } - + assert(isOrderedBefore(value, elements[i])) elements[i] = value shiftUp(i) @@ -144,7 +144,7 @@ public struct Heap { */ public mutating func removeAt(_ index: Int) -> T? { guard index < elements.count else { return nil } - + let size = elements.count - 1 if index != size { swap(&elements[index], &elements[size]) diff --git a/Heap/Tests/HeapTests.swift b/Heap/Tests/HeapTests.swift index 0e6c504f3..cac934406 100644 --- a/Heap/Tests/HeapTests.swift +++ b/Heap/Tests/HeapTests.swift @@ -201,7 +201,7 @@ class HeapTests: XCTestCase { XCTAssertEqual(v, nil) XCTAssertTrue(verifyMaxHeap(h)) XCTAssertEqual(h.elements, [100, 50, 70, 10, 20, 60, 65]) - + let v1 = h.removeAt(5) XCTAssertEqual(v1, 60) XCTAssertTrue(verifyMaxHeap(h)) @@ -314,7 +314,7 @@ class HeapTests: XCTestCase { h.replace(index: 5, value: 13) XCTAssertTrue(verifyMaxHeap(h)) XCTAssertEqual(h.elements, [16, 14, 13, 8, 7, 10, 3, 2, 4, 1]) - + //test index out of bounds h.replace(index: 20, value: 2) XCTAssertTrue(verifyMaxHeap(h)) diff --git a/Huffman Coding/Huffman.swift b/Huffman Coding/Huffman.swift index 7e2961a2f..cad80327d 100644 --- a/Huffman Coding/Huffman.swift +++ b/Huffman Coding/Huffman.swift @@ -13,7 +13,7 @@ public class Huffman { /* Tree nodes don't use pointers to refer to each other, but simple integer indices. That allows us to use structs for the nodes. */ typealias NodeIndex = Int - + /* A node in the compression tree. Leaf nodes represent the actual bytes that are present in the input data. The count of an intermediary node is the sum of the counts of all nodes below it. The root node's count is the number of @@ -25,15 +25,15 @@ public class Huffman { var left: NodeIndex = -1 var right: NodeIndex = -1 } - + /* The tree structure. The first 256 entries are for the leaf nodes (not all of those may be used, depending on the input). We add additional nodes as we build the tree. */ var tree = [Node](repeating: Node(), count: 256) - + /* This is the last node we add to the tree. */ var root: NodeIndex = -1 - + /* The frequency table describes how often a byte occurs in the input data. You need it to decompress the Huffman-encoded data. The frequency table should be serialized along with the compressed data. */ @@ -41,7 +41,7 @@ public class Huffman { var byte: UInt8 = 0 var count = 0 } - + public init() { } } @@ -59,7 +59,7 @@ extension Huffman { ptr = ptr.successor() } } - + /* Takes a frequency table and rebuilds the tree. This is the first step of decompression. */ fileprivate func restoreTree(fromTable frequencyTable: [Freq]) { @@ -70,7 +70,7 @@ extension Huffman { } buildTree() } - + /* Returns the frequency table. This is the first 256 nodes from the tree but only those that are actually used, without the parent/left/right pointers. You would serialize this along with the compressed file. */ @@ -91,13 +91,13 @@ extension Huffman { for node in tree where node.count > 0 { queue.enqueue(node) } - + while queue.count > 1 { // Find the two nodes with the smallest frequencies that do not have // a parent node yet. let node1 = queue.dequeue()! let node2 = queue.dequeue()! - + // Create a new intermediate node. var parentNode = Node() parentNode.count = node1.count + node2.count @@ -105,15 +105,15 @@ extension Huffman { parentNode.right = node2.index parentNode.index = tree.count tree.append(parentNode) - + // Link the two nodes into their new parent node. tree[node1.index].parent = parentNode.index tree[node2.index].parent = parentNode.index - + // Put the intermediate node back into the queue. queue.enqueue(parentNode) } - + // The final remaining node in the queue becomes the root of the tree. let rootNode = queue.dequeue()! root = rootNode.index @@ -125,7 +125,7 @@ extension Huffman { public func compressData(data: NSData) -> NSData { countByteFrequency(inData: data) buildTree() - + let writer = BitWriter() var ptr = data.bytes.assumingMemoryBound(to: UInt8.self) for _ in 0.. NSData { restoreTree(fromTable: frequencyTable) - + let reader = BitReader(data: data) let outData = NSMutableData() let byteCount = tree[root].count - + var i = 0 while i < byteCount { var b = findLeafNode(reader: reader, nodeIndex: root) @@ -172,7 +172,7 @@ extension Huffman { } return outData } - + /* Walks the tree from the root down to the leaf node. At every node, read the next bit and use that to determine whether to step to the left or right. When we get to the leaf node, we simply return its index, which is equal to diff --git a/Huffman Coding/NSData+Bits.swift b/Huffman Coding/NSData+Bits.swift index 4ae3c5c6d..1f5333296 100644 --- a/Huffman Coding/NSData+Bits.swift +++ b/Huffman Coding/NSData+Bits.swift @@ -5,7 +5,7 @@ public class BitWriter { public var data = NSMutableData() var outByte: UInt8 = 0 var outCount = 0 - + public func writeBit(bit: Bool) { if outCount == 8 { data.append(&outByte, length: 1) @@ -14,7 +14,7 @@ public class BitWriter { outByte = (outByte << 1) | (bit ? 1 : 0) outCount += 1 } - + public func flush() { if outCount > 0 { if outCount < 8 { @@ -31,11 +31,11 @@ public class BitReader { var ptr: UnsafePointer var inByte: UInt8 = 0 var inCount = 8 - + public init(data: NSData) { ptr = data.bytes.assumingMemoryBound(to: UInt8.self) } - + public func readBit() -> Bool { if inCount == 8 { inByte = ptr.pointee // load the next byte diff --git a/Karatsuba Multiplication/KaratsubaMultiplication.playground/Contents.swift b/Karatsuba Multiplication/KaratsubaMultiplication.playground/Contents.swift index 3ac29301a..2d327fbac 100644 --- a/Karatsuba Multiplication/KaratsubaMultiplication.playground/Contents.swift +++ b/Karatsuba Multiplication/KaratsubaMultiplication.playground/Contents.swift @@ -17,7 +17,7 @@ func ^^ (radix: Int, power: Int) -> Int { func multiply(_ num1: Int, by num2: Int, base: Int = 10) -> Int { let num1Array = String(num1).characters.reversed().map { Int(String($0))! } let num2Array = String(num2).characters.reversed().map { Int(String($0))! } - + var product = Array(repeating: 0, count: num1Array.count + num2Array.count) for i in num1Array.indices { @@ -29,7 +29,7 @@ func multiply(_ num1: Int, by num2: Int, base: Int = 10) -> Int { } product[i + num2Array.count] += carry } - + return Int(product.reversed().map { String($0) }.reduce("", +))! } @@ -37,24 +37,24 @@ func multiply(_ num1: Int, by num2: Int, base: Int = 10) -> Int { func karatsuba(_ num1: Int, by num2: Int) -> Int { let num1Array = String(num1).characters let num2Array = String(num2).characters - + guard num1Array.count > 1 && num2Array.count > 1 else { return multiply(num1, by: num2) } - + let n = max(num1Array.count, num2Array.count) let nBy2 = n / 2 - + let a = num1 / 10^^nBy2 let b = num1 % 10^^nBy2 let c = num2 / 10^^nBy2 let d = num2 % 10^^nBy2 - + let ac = karatsuba(a, by: c) let bd = karatsuba(b, by: d) let adPlusbc = karatsuba(a+b, by: c+d) - ac - bd - + let product = ac * 10^^(2 * nBy2) + adPlusbc * 10^^nBy2 + bd - + return product } diff --git a/Karatsuba Multiplication/KaratsubaMultiplication.swift b/Karatsuba Multiplication/KaratsubaMultiplication.swift index fb20a667d..0f0e8ed12 100644 --- a/Karatsuba Multiplication/KaratsubaMultiplication.swift +++ b/Karatsuba Multiplication/KaratsubaMultiplication.swift @@ -22,24 +22,24 @@ func ^^ (radix: Int, power: Int) -> Int { func karatsuba(_ num1: Int, by num2: Int) -> Int { let num1Array = String(num1).characters let num2Array = String(num2).characters - + guard num1Array.count > 1 && num2Array.count > 1 else { return num1 * num2 } - + let n = max(num1Array.count, num2Array.count) let nBy2 = n / 2 - + let a = num1 / 10^^nBy2 let b = num1 % 10^^nBy2 let c = num2 / 10^^nBy2 let d = num2 % 10^^nBy2 - + let ac = karatsuba(a, by: c) let bd = karatsuba(b, by: d) let adPlusbc = karatsuba(a+b, by: c+d) - ac - bd - + let product = ac * 10^^(2 * nBy2) + adPlusbc * 10^^nBy2 + bd - + return product } diff --git a/Knuth-Morris-Pratt/KnuthMorrisPratt.swift b/Knuth-Morris-Pratt/KnuthMorrisPratt.swift index 46a88c134..45d9812b7 100644 --- a/Knuth-Morris-Pratt/KnuthMorrisPratt.swift +++ b/Knuth-Morris-Pratt/KnuthMorrisPratt.swift @@ -9,54 +9,54 @@ import Foundation extension String { - + func indexesOf(ptnr: String) -> [Int]? { - + let text = Array(self.characters) let pattern = Array(ptnr.characters) - + let textLength: Int = text.count let patternLength: Int = pattern.count - + guard patternLength > 0 else { return nil } - + var suffixPrefix: [Int] = [Int](repeating: 0, count: patternLength) var textIndex: Int = 0 var patternIndex: Int = 0 var indexes: [Int] = [Int]() - + /* Pre-processing stage: computing the table for the shifts (through Z-Algorithm) */ let zeta = ZetaAlgorithm(ptnr: ptnr) - + for patternIndex in (1 ..< patternLength).reversed() { textIndex = patternIndex + zeta![patternIndex] - 1 suffixPrefix[textIndex] = zeta![patternIndex] } - + /* Search stage: scanning the text for pattern matching */ textIndex = 0 patternIndex = 0 - + while textIndex + (patternLength - patternIndex - 1) < textLength { - + while patternIndex < patternLength && text[textIndex] == pattern[patternIndex] { textIndex = textIndex + 1 patternIndex = patternIndex + 1 } - + if patternIndex == patternLength { indexes.append(textIndex - patternIndex) } - + if patternIndex == 0 { textIndex = textIndex + 1 } else { patternIndex = suffixPrefix[patternIndex - 1] } } - + guard !indexes.isEmpty else { return nil } diff --git a/Linked List/LinkedList.playground/Contents.swift b/Linked List/LinkedList.playground/Contents.swift index 08e14ef70..9ee4cc4c4 100644 --- a/Linked List/LinkedList.playground/Contents.swift +++ b/Linked List/LinkedList.playground/Contents.swift @@ -4,37 +4,37 @@ //: Linked List Class Declaration: public final class LinkedList { - + /// Linked List's Node Class Declaration public class LinkedListNode { var value: T var next: LinkedListNode? weak var previous: LinkedListNode? - + public init(value: T) { self.value = value } } - + /// Typealiasing the node class to increase readability of code public typealias Node = LinkedListNode - + /// The head of the Linked List fileprivate var head: Node? - + /// Default initializer public init() {} - + /// Computed property to check if the linked list is empty public var isEmpty: Bool { return head == nil } - + /// Computed property to get the first node in the linked list (if any) public var first: Node? { return head } - + /// Computed property to iterate through the linked list and return the last node in the list (if any) public var last: Node? { if var node = head { @@ -46,7 +46,7 @@ public final class LinkedList { return nil } } - + /// Computed property to iterate through the linked list and return the total number of nodes public var count: Int { if var node = head { @@ -60,7 +60,7 @@ public final class LinkedList { return 0 } } - + /// Function to return the node at a specific index. Crashes if index is out of bounds (0...self.count) /// /// - Parameter index: Integer value of the node's index to be returned @@ -77,7 +77,7 @@ public final class LinkedList { } return nil } - + /// Subscript function to return the node at a specific index /// /// - Parameter index: Integer value of the requested value's index @@ -86,7 +86,7 @@ public final class LinkedList { assert(node != nil) return node!.value } - + /// Append a value to the end of the list /// /// - Parameter value: The data value to be appended @@ -94,7 +94,7 @@ public final class LinkedList { let newNode = Node(value: value) self.append(newNode) } - + /// Append a copy of a LinkedListNode to the end of the list. /// /// - Parameter node: The node containing the value to be appended @@ -107,7 +107,7 @@ public final class LinkedList { head = newNode } } - + /// Append a copy of a LinkedList to the end of the list. /// /// - Parameter list: The list to be copied and appended. @@ -118,28 +118,28 @@ public final class LinkedList { nodeToCopy = node.next } } - + /// A private helper funciton to find the nodes before and after a specified index. Crashes if index is out of bounds (0...self.count) /// /// - Parameter index: Integer value of the index between the nodes. /// - Returns: A tuple of 2 nodes before & after the specified index respectively. private func nodesBeforeAndAfter(index: Int) -> (Node?, Node?) { assert(index >= 0) - + var i = index var next = head var prev: Node? - + while next != nil && i > 0 { i -= 1 prev = next next = next!.next } assert(i == 0) // if > 0, then specified index was too large - + return (prev, next) } - + /// Insert a value at a specific index. Crashes if index is out of bounds (0...self.count) /// /// - Parameters: @@ -149,7 +149,7 @@ public final class LinkedList { let newNode = Node(value: value) self.insert(newNode, atIndex: index) } - + /// Insert a copy of a node at a specific index. Crashes if index is out of bounds (0...self.count) /// /// - Parameters: @@ -162,12 +162,12 @@ public final class LinkedList { newNode.next = next prev?.next = newNode next?.previous = newNode - + if prev == nil { head = newNode } } - + /// Insert a copy of a LinkedList at a specific index. Crashes if index is out of bounds (0...self.count) /// /// - Parameters: @@ -192,12 +192,12 @@ public final class LinkedList { prev?.next = next next?.previous = prev } - + /// Function to remove all nodes/value from the list public func removeAll() { head = nil } - + /// Function to remove a specific node. /// /// - Parameter node: The node to be deleted @@ -205,19 +205,19 @@ public final class LinkedList { @discardableResult public func remove(node: Node) -> T { let prev = node.previous let next = node.next - + if let prev = prev { prev.next = next } else { head = next } next?.previous = prev - + node.previous = nil node.next = nil return node.value } - + /// Function to remove the last node/value in the list. Crashes if the list is empty /// /// - Returns: The data value contained in the deleted node. @@ -225,7 +225,7 @@ public final class LinkedList { assert(!isEmpty) return remove(node: last!) } - + /// Function to remove a node/value at a specific index. Crashes if index is out of bounds (0...self.count) /// /// - Parameter index: Integer value of the index of the node to be removed @@ -276,7 +276,7 @@ extension LinkedList { } return result } - + public func filter(predicate: (T) -> Bool) -> LinkedList { let result = LinkedList() var node = head @@ -294,7 +294,7 @@ extension LinkedList { extension LinkedList { convenience init(array: Array) { self.init() - + for element in array { self.append(element) } @@ -305,7 +305,7 @@ extension LinkedList { extension LinkedList: ExpressibleByArrayLiteral { public convenience init(arrayLiteral elements: T...) { self.init() - + for element in elements { self.append(element) } diff --git a/Linked List/LinkedList.swift b/Linked List/LinkedList.swift index 783e650e8..94e978c07 100755 --- a/Linked List/LinkedList.swift +++ b/Linked List/LinkedList.swift @@ -1,29 +1,29 @@ public final class LinkedList { - + public class LinkedListNode { var value: T var next: LinkedListNode? weak var previous: LinkedListNode? - + public init(value: T) { self.value = value } } - + public typealias Node = LinkedListNode - + fileprivate var head: Node? - + public init() {} - + public var isEmpty: Bool { return head == nil } - + public var first: Node? { return head } - + public var last: Node? { if var node = head { while case let next? = node.next { @@ -34,7 +34,7 @@ public final class LinkedList { return nil } } - + public var count: Int { if var node = head { var c = 1 @@ -47,7 +47,7 @@ public final class LinkedList { return 0 } } - + public func node(atIndex index: Int) -> Node? { if index >= 0 { var node = head @@ -60,18 +60,18 @@ public final class LinkedList { } return nil } - + public subscript(index: Int) -> T { let node = self.node(atIndex: index) assert(node != nil) return node!.value } - + public func append(_ value: T) { let newNode = Node(value: value) self.append(newNode) } - + public func append(_ node: Node) { let newNode = LinkedListNode(value: node.value) if let lastNode = last { @@ -81,7 +81,7 @@ public final class LinkedList { head = newNode } } - + public func append(_ list: LinkedList) { var nodeToCopy = list.head while let node = nodeToCopy { @@ -89,29 +89,29 @@ public final class LinkedList { nodeToCopy = node.next } } - + private func nodesBeforeAndAfter(index: Int) -> (Node?, Node?) { assert(index >= 0) - + var i = index var next = head var prev: Node? - + while next != nil && i > 0 { i -= 1 prev = next next = next!.next } assert(i == 0) // if > 0, then specified index was too large - + return (prev, next) } - + public func insert(_ value: T, atIndex index: Int) { let newNode = Node(value: value) self.insert(newNode, atIndex: index) } - + public func insert(_ node: Node, atIndex index: Int) { let (prev, next) = nodesBeforeAndAfter(index: index) let newNode = LinkedListNode(value: node.value) @@ -119,12 +119,12 @@ public final class LinkedList { newNode.next = next prev?.next = newNode next?.previous = newNode - + if prev == nil { head = newNode } } - + public func insert(_ list: LinkedList, atIndex index: Int) { if list.isEmpty { return } var (prev, next) = nodesBeforeAndAfter(index: index) @@ -144,32 +144,32 @@ public final class LinkedList { prev?.next = next next?.previous = prev } - + public func removeAll() { head = nil } - + @discardableResult public func remove(node: Node) -> T { let prev = node.previous let next = node.next - + if let prev = prev { prev.next = next } else { head = next } next?.previous = prev - + node.previous = nil node.next = nil return node.value } - + @discardableResult public func removeLast() -> T { assert(!isEmpty) return remove(node: last!) } - + @discardableResult public func remove(atIndex index: Int) -> T { let node = self.node(atIndex: index) assert(node != nil) @@ -211,7 +211,7 @@ extension LinkedList { } return result } - + public func filter(predicate: (T) -> Bool) -> LinkedList { let result = LinkedList() var node = head @@ -228,7 +228,7 @@ extension LinkedList { extension LinkedList { convenience init(array: Array) { self.init() - + for element in array { self.append(element) } @@ -238,7 +238,7 @@ extension LinkedList { extension LinkedList: ExpressibleByArrayLiteral { public convenience init(arrayLiteral elements: T...) { self.init() - + for element in elements { self.append(element) } diff --git a/Linked List/Tests/LinkedListTests.swift b/Linked List/Tests/LinkedListTests.swift index ea063cacb..7fd31c2c7 100755 --- a/Linked List/Tests/LinkedListTests.swift +++ b/Linked List/Tests/LinkedListTests.swift @@ -165,7 +165,7 @@ class LinkedListTest: XCTestCase { XCTAssertTrue(prev!.next === node) XCTAssertTrue(next!.previous === node) } - + func testInsertListAtIndex() { let list = buildList() let list2 = LinkedList() @@ -190,7 +190,7 @@ class LinkedListTest: XCTestCase { XCTAssertEqual(list.node(atIndex: 1)?.value, 102) XCTAssertEqual(list.node(atIndex: 2)?.value, 8) } - + func testInsertListAtLastIndex() { let list = buildList() let list2 = LinkedList() @@ -202,7 +202,7 @@ class LinkedListTest: XCTestCase { XCTAssertEqual(list.node(atIndex: 6)?.value, 99) XCTAssertEqual(list.node(atIndex: 7)?.value, 102) } - + func testAppendList() { let list = buildList() let list2 = LinkedList() @@ -214,7 +214,7 @@ class LinkedListTest: XCTestCase { XCTAssertEqual(list.node(atIndex: 6)?.value, 99) XCTAssertEqual(list.node(atIndex: 7)?.value, 102) } - + func testAppendListToEmptyList() { let list = LinkedList() let list2 = LinkedList() @@ -225,7 +225,7 @@ class LinkedListTest: XCTestCase { XCTAssertEqual(list.node(atIndex: 0)?.value, 5) XCTAssertEqual(list.node(atIndex: 1)?.value, 10) } - + func testRemoveAtIndexOnListWithOneElement() { let list = LinkedList() list.append(123) @@ -308,10 +308,10 @@ class LinkedListTest: XCTestCase { XCTAssertTrue(last === list.first) XCTAssertEqual(nodeCount, list.count) } - + func testArrayLiteralInitTypeInfer() { let arrayLiteralInitInfer: LinkedList = [1.0, 2.0, 3.0] - + XCTAssertEqual(arrayLiteralInitInfer.count, 3) XCTAssertEqual(arrayLiteralInitInfer.first?.value, 1.0) XCTAssertEqual(arrayLiteralInitInfer.last?.value, 3.0) @@ -319,10 +319,10 @@ class LinkedListTest: XCTestCase { XCTAssertEqual(arrayLiteralInitInfer.removeLast(), 3.0) XCTAssertEqual(arrayLiteralInitInfer.count, 2) } - + func testArrayLiteralInitExplicit() { let arrayLiteralInitExplicit: LinkedList = [1, 2, 3] - + XCTAssertEqual(arrayLiteralInitExplicit.count, 3) XCTAssertEqual(arrayLiteralInitExplicit.first?.value, 1) XCTAssertEqual(arrayLiteralInitExplicit.last?.value, 3) diff --git a/Miller-Rabin Primality Test/MRPrimality.playground/Sources/MRPrimality.swift b/Miller-Rabin Primality Test/MRPrimality.playground/Sources/MRPrimality.swift index 9dca23996..ee2ace8b9 100644 --- a/Miller-Rabin Primality Test/MRPrimality.playground/Sources/MRPrimality.swift +++ b/Miller-Rabin Primality Test/MRPrimality.playground/Sources/MRPrimality.swift @@ -23,38 +23,38 @@ import Foundation */ public func mrPrimalityTest(_ n: UInt64, iteration k: Int = 1) -> Bool { guard n > 2 && n % 2 == 1 else { return false } - + var d = n - 1 var s = 0 - + while d % 2 == 0 { d /= 2 s += 1 } - + let range = UInt64.max - UInt64.max % (n - 2) var r: UInt64 = 0 repeat { arc4random_buf(&r, MemoryLayout.size(ofValue: r)) } while r >= range - + r = r % (n - 2) + 2 - + for _ in 1 ... k { var x = powmod64(r, d, n) if x == 1 || x == n - 1 { continue } - + if s == 1 { s = 2 } - + for _ in 1 ... s - 1 { x = powmod64(x, 2, n) if x == 1 { return false } if x == n - 1 { break } } - + if x != n - 1 { return false } } - + return true } @@ -71,17 +71,17 @@ public func mrPrimalityTest(_ n: UInt64, iteration k: Int = 1) -> Bool { */ private func powmod64(_ base: UInt64, _ exp: UInt64, _ m: UInt64) -> UInt64 { if m == 1 { return 0 } - + var result: UInt64 = 1 var b = base % m var e = exp - + while e > 0 { if e % 2 == 1 { result = mulmod64(result, b, m) } b = mulmod64(b, b, m) e >>= 1 } - + return result } @@ -100,12 +100,12 @@ private func mulmod64(_ first: UInt64, _ second: UInt64, _ m: UInt64) -> UInt64 var result: UInt64 = 0 var a = first var b = second - + while a != 0 { if a % 2 == 1 { result = ((result % m) + (b % m)) % m } // This may overflow if 'm' is a 64bit number && both 'result' and 'b' are very close to but smaller than 'm'. a >>= 1 b = (b << 1) % m } - + return result } diff --git a/Miller-Rabin Primality Test/MRPrimality.swift b/Miller-Rabin Primality Test/MRPrimality.swift index 9dca23996..ee2ace8b9 100644 --- a/Miller-Rabin Primality Test/MRPrimality.swift +++ b/Miller-Rabin Primality Test/MRPrimality.swift @@ -23,38 +23,38 @@ import Foundation */ public func mrPrimalityTest(_ n: UInt64, iteration k: Int = 1) -> Bool { guard n > 2 && n % 2 == 1 else { return false } - + var d = n - 1 var s = 0 - + while d % 2 == 0 { d /= 2 s += 1 } - + let range = UInt64.max - UInt64.max % (n - 2) var r: UInt64 = 0 repeat { arc4random_buf(&r, MemoryLayout.size(ofValue: r)) } while r >= range - + r = r % (n - 2) + 2 - + for _ in 1 ... k { var x = powmod64(r, d, n) if x == 1 || x == n - 1 { continue } - + if s == 1 { s = 2 } - + for _ in 1 ... s - 1 { x = powmod64(x, 2, n) if x == 1 { return false } if x == n - 1 { break } } - + if x != n - 1 { return false } } - + return true } @@ -71,17 +71,17 @@ public func mrPrimalityTest(_ n: UInt64, iteration k: Int = 1) -> Bool { */ private func powmod64(_ base: UInt64, _ exp: UInt64, _ m: UInt64) -> UInt64 { if m == 1 { return 0 } - + var result: UInt64 = 1 var b = base % m var e = exp - + while e > 0 { if e % 2 == 1 { result = mulmod64(result, b, m) } b = mulmod64(b, b, m) e >>= 1 } - + return result } @@ -100,12 +100,12 @@ private func mulmod64(_ first: UInt64, _ second: UInt64, _ m: UInt64) -> UInt64 var result: UInt64 = 0 var a = first var b = second - + while a != 0 { if a % 2 == 1 { result = ((result % m) + (b % m)) % m } // This may overflow if 'm' is a 64bit number && both 'result' and 'b' are very close to but smaller than 'm'. a >>= 1 b = (b << 1) % m } - + return result } diff --git a/Minimum Edit Distance/MinimumEditDistance.playground/Contents.swift b/Minimum Edit Distance/MinimumEditDistance.playground/Contents.swift index d651ddf2e..238afeb9b 100755 --- a/Minimum Edit Distance/MinimumEditDistance.playground/Contents.swift +++ b/Minimum Edit Distance/MinimumEditDistance.playground/Contents.swift @@ -1,21 +1,21 @@ extension String { - + public func minimumEditDistance(other: String) -> Int { let m = self.characters.count let n = other.characters.count var matrix = [[Int]](repeating: [Int](repeating: 0, count: n + 1), count: m + 1) - + // initialize matrix for index in 1...m { // the distance of any first string to an empty second string matrix[index][0] = index } - + for index in 1...n { // the distance of any second string to an empty first string matrix[0][index] = index } - + // compute Levenshtein distance for (i, selfChar) in self.characters.enumerated() { for (j, otherChar) in other.characters.enumerated() { diff --git a/Ordered Array/OrderedArray.playground/Contents.swift b/Ordered Array/OrderedArray.playground/Contents.swift index 1a0320a65..5ca0d7d31 100644 --- a/Ordered Array/OrderedArray.playground/Contents.swift +++ b/Ordered Array/OrderedArray.playground/Contents.swift @@ -49,7 +49,7 @@ public struct OrderedArray { private func findInsertionPoint(_ newElement: T) -> Int { var startIndex = 0 var endIndex = array.count - + while startIndex < endIndex { let midIndex = startIndex + (endIndex - startIndex) / 2 if array[midIndex] == newElement { diff --git a/Palindromes/Palindromes.playground/Contents.swift b/Palindromes/Palindromes.playground/Contents.swift index e8562a367..b9e857dd0 100644 --- a/Palindromes/Palindromes.playground/Contents.swift +++ b/Palindromes/Palindromes.playground/Contents.swift @@ -10,7 +10,7 @@ import Foundation func isPalindrome(_ str: String) -> Bool { let strippedString = str.replacingOccurrences(of: "\\W", with: "", options: .regularExpression, range: nil) let length = strippedString.characters.count - + if length > 1 { return palindrome(strippedString.lowercased(), left: 0, right: length - 1) } @@ -28,14 +28,14 @@ private func palindrome(_ str: String, left: Int, right: Int) -> Bool { if left >= right { return true } - + let lhs = str[str.index(str.startIndex, offsetBy: left)] let rhs = str[str.index(str.startIndex, offsetBy: right)] - + if lhs != rhs { return false } - + return palindrome(str, left: left + 1, right: right - 1) } diff --git a/Palindromes/Palindromes.swift b/Palindromes/Palindromes.swift index 2760137ca..9ddd04c80 100644 --- a/Palindromes/Palindromes.swift +++ b/Palindromes/Palindromes.swift @@ -3,7 +3,7 @@ import Foundation func isPalindrome(_ str: String) -> Bool { let strippedString = str.replacingOccurrences(of: "\\W", with: "", options: .regularExpression, range: nil) let length = strippedString.characters.count - + if length > 1 { return palindrome(strippedString.lowercased(), left: 0, right: length - 1) } @@ -14,13 +14,13 @@ private func palindrome(_ str: String, left: Int, right: Int) -> Bool { if left >= right { return true } - + let lhs = str[str.index(str.startIndex, offsetBy: left)] let rhs = str[str.index(str.startIndex, offsetBy: right)] - + if lhs != rhs { return false } - + return palindrome(str, left: left + 1, right: right - 1) } diff --git a/Palindromes/Test/Palindromes.swift b/Palindromes/Test/Palindromes.swift index 2760137ca..9ddd04c80 100644 --- a/Palindromes/Test/Palindromes.swift +++ b/Palindromes/Test/Palindromes.swift @@ -3,7 +3,7 @@ import Foundation func isPalindrome(_ str: String) -> Bool { let strippedString = str.replacingOccurrences(of: "\\W", with: "", options: .regularExpression, range: nil) let length = strippedString.characters.count - + if length > 1 { return palindrome(strippedString.lowercased(), left: 0, right: length - 1) } @@ -14,13 +14,13 @@ private func palindrome(_ str: String, left: Int, right: Int) -> Bool { if left >= right { return true } - + let lhs = str[str.index(str.startIndex, offsetBy: left)] let rhs = str[str.index(str.startIndex, offsetBy: right)] - + if lhs != rhs { return false } - + return palindrome(str, left: left + 1, right: right - 1) } diff --git a/Palindromes/Test/Test/Test.swift b/Palindromes/Test/Test/Test.swift index 1dd79ea97..ddf970300 100644 --- a/Palindromes/Test/Test/Test.swift +++ b/Palindromes/Test/Test/Test.swift @@ -9,22 +9,22 @@ import XCTest class PalindromeTests: XCTestCase { - + override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } - + override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } - + func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } - + func testPerformanceExample() { // This is an example of a performance test case. self.measure { @@ -34,12 +34,12 @@ class PalindromeTests: XCTestCase { _ = isPalindrome("abababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababa") } } - + func testPalindromeWord() { XCTAssertTrue(isPalindrome("abbcbba")) XCTAssertTrue(isPalindrome("racecar")) } - + func testPalindromeSentence() { XCTAssertTrue(isPalindrome("A man, a plan, a canal, Panama!")) XCTAssertTrue(isPalindrome("Madam, I'm Adam")) @@ -47,17 +47,17 @@ class PalindromeTests: XCTestCase { XCTAssertTrue(isPalindrome("In girum imus nocte et consumimur igni")) XCTAssertTrue(isPalindrome("Never odd or even")) } - + func testPalindromeNumber() { XCTAssertTrue(isPalindrome("5885")) XCTAssertTrue(isPalindrome("5 8 8 5")) XCTAssertTrue(isPalindrome("58 85")) } - + func testSpecialCharacters() { XCTAssertTrue(isPalindrome("৯৯")) } - + func testNonPalindromes() { XCTAssertFalse(isPalindrome("\\\\")) XCTAssertFalse(isPalindrome("desserts")) diff --git a/QuadTree/QuadTree.playground/Sources/QuadTree.swift b/QuadTree/QuadTree.playground/Sources/QuadTree.swift index 14d0dbba7..7fd459e97 100644 --- a/QuadTree/QuadTree.playground/Sources/QuadTree.swift +++ b/QuadTree/QuadTree.playground/Sources/QuadTree.swift @@ -1,7 +1,7 @@ public struct Point { let x: Double let y: Double - + public init(_ x: Double, _ y: Double) { self.x = x self.y = y @@ -17,18 +17,18 @@ extension Point: CustomStringConvertible { public struct Size: CustomStringConvertible { var xLength: Double var yLength: Double - + public init(xLength: Double, yLength: Double) { precondition(xLength >= 0, "xLength can not be negative") precondition(yLength >= 0, "yLength can not be negative") self.xLength = xLength self.yLength = yLength } - + var half: Size { return Size(xLength: xLength / 2, yLength: yLength / 2) } - + public var description: String { return "Size(\(xLength), \(yLength))" } @@ -38,49 +38,49 @@ public struct Rect { // left top vertice var origin: Point var size: Size - + public init(origin: Point, size: Size) { self.origin = origin self.size = size } - + var minX: Double { return origin.x } - + var minY: Double { return origin.y } - + var maxX: Double { return origin.x + size.xLength } - + var maxY: Double { return origin.y + size.yLength } - + func containts(point: Point) -> Bool { return (minX <= point.x && point.x <= maxX) && (minY <= point.y && point.y <= maxY) } - + var leftTopRect: Rect { return Rect(origin: origin, size: size.half) } - + var leftBottomRect: Rect { return Rect(origin: Point(origin.x, origin.y + size.half.yLength), size: size.half) } - + var rightTopRect: Rect { return Rect(origin: Point(origin.x + size.half.xLength, origin.y), size: size.half) } - + var rightBottomRect: Rect { return Rect(origin: Point(origin.x + size.half.xLength, origin.y + size.half.yLength), size: size.half) } - + func intersects(rect: Rect) -> Bool { func lineSegmentsIntersect(lStart: Double, lEnd: Double, rStart: Double, rEnd: Double) -> Bool { @@ -91,7 +91,7 @@ public struct Rect { if !lineSegmentsIntersect(lStart: minX, lEnd: maxX, rStart: rect.minX, rEnd: rect.maxX) { return false } - + // vertical return lineSegmentsIntersect(lStart: minY, lEnd: maxY, rStart: rect.minY, rEnd: rect.maxY) } @@ -109,37 +109,37 @@ protocol PointsContainer { } class QuadTreeNode { - + enum NodeType { case leaf case `internal`(children: Children) } - + struct Children: Sequence { let leftTop: QuadTreeNode let leftBottom: QuadTreeNode let rightTop: QuadTreeNode let rightBottom: QuadTreeNode - + init(parentNode: QuadTreeNode) { leftTop = QuadTreeNode(rect: parentNode.rect.leftTopRect) leftBottom = QuadTreeNode(rect: parentNode.rect.leftBottomRect) rightTop = QuadTreeNode(rect: parentNode.rect.rightTopRect) rightBottom = QuadTreeNode(rect: parentNode.rect.rightBottomRect) } - + struct ChildrenIterator: IteratorProtocol { private var index = 0 private let children: Children - + init(children: Children) { self.children = children } - + mutating func next() -> QuadTreeNode? { - + defer { index += 1 } - + switch index { case 0: return children.leftTop case 1: return children.leftBottom @@ -149,26 +149,26 @@ class QuadTreeNode { } } } - + public func makeIterator() -> ChildrenIterator { return ChildrenIterator(children: self) } } - + var points: [Point] = [] let rect: Rect var type: NodeType = .leaf - + static let maxPointCapacity = 3 - + init(rect: Rect) { self.rect = rect } - + var recursiveDescription: String { return recursiveDescription(withTabCount: 0) } - + private func recursiveDescription(withTabCount count: Int) -> String { let indent = String(repeating: "\t", count: count) var result = "\(indent)" + description + "\n" @@ -185,13 +185,13 @@ class QuadTreeNode { } extension QuadTreeNode: PointsContainer { - + @discardableResult func add(point: Point) -> Bool { if !rect.containts(point: point) { return false } - + switch type { case .internal(let children): // pass the point to one of the children @@ -200,7 +200,7 @@ extension QuadTreeNode: PointsContainer { return true } } - + fatalError("rect.containts evaluted to true, but none of the children added the point") case .leaf: points.append(point) @@ -211,7 +211,7 @@ extension QuadTreeNode: PointsContainer { } return true } - + private func subdivide() { switch type { case .leaf: @@ -220,25 +220,25 @@ extension QuadTreeNode: PointsContainer { preconditionFailure("Calling subdivide on an internal node") } } - + func points(inRect rect: Rect) -> [Point] { - + // if the node's rect and the given rect don't intersect, return an empty array, // because there can't be any points that lie the node's (or its children's) rect and // in the given rect if !self.rect.intersects(rect: rect) { return [] } - + var result: [Point] = [] - + // collect the node's points that lie in the rect for point in points { if rect.containts(point: point) { result.append(point) } } - + switch type { case .leaf: break @@ -248,7 +248,7 @@ extension QuadTreeNode: PointsContainer { result.append(contentsOf: childNode.points(inRect: rect)) } } - + return result } } @@ -265,18 +265,18 @@ extension QuadTreeNode: CustomStringConvertible { } public class QuadTree: PointsContainer { - + let root: QuadTreeNode - + public init(rect: Rect) { self.root = QuadTreeNode(rect: rect) } - + @discardableResult public func add(point: Point) -> Bool { return root.add(point: point) } - + public func points(inRect rect: Rect) -> [Point] { return root.points(inRect: rect) } diff --git a/QuadTree/Tests/Tests/Tests.swift b/QuadTree/Tests/Tests/Tests.swift index b408c4f7e..9bd8ad28f 100644 --- a/QuadTree/Tests/Tests/Tests.swift +++ b/QuadTree/Tests/Tests/Tests.swift @@ -17,68 +17,68 @@ public func == (lhs: Point, rhs: Point) -> Bool { } class Tests: XCTestCase { - + func testRectContains() { let rect = Rect(origin: Point(0, 0), size: Size(xLength: 3, yLength: 3)) - + XCTAssertTrue(rect.containts(point: Point(1, 1))) XCTAssertTrue(rect.containts(point: Point(0, 0))) XCTAssertTrue(rect.containts(point: Point(0, 3))) XCTAssertTrue(rect.containts(point: Point(3, 3))) - + XCTAssertFalse(rect.containts(point: Point(-1, 1))) XCTAssertFalse(rect.containts(point: Point(-0.1, 0.1))) XCTAssertFalse(rect.containts(point: Point(0, 3.1))) XCTAssertFalse(rect.containts(point: Point(-4, 1))) } - + func testIntersects() { let rect = Rect(origin: Point(0, 0), size: Size(xLength: 5, yLength: 5)) let rect2 = Rect(origin: Point(1, 1), size: Size(xLength: 1, yLength: 1)) XCTAssertTrue(rect.intersects(rect: rect2)) - + let rect3 = Rect(origin: Point(1, 0), size: Size(xLength: 1, yLength: 10)) let rect4 = Rect(origin: Point(0, 1), size: Size(xLength: 10, yLength: 1)) XCTAssertTrue(rect3.intersects(rect: rect4)) - + let rect5 = Rect(origin: Point(0, 0), size: Size(xLength: 4, yLength: 4)) let rect6 = Rect(origin: Point(2, 2), size: Size(xLength: 4, yLength: 4)) XCTAssertTrue(rect5.intersects(rect: rect6)) - + let rect7 = Rect(origin: Point(0, 0), size: Size(xLength: 4, yLength: 4)) let rect8 = Rect(origin: Point(4, 4), size: Size(xLength: 1, yLength: 1)) XCTAssertTrue(rect7.intersects(rect: rect8)) - + let rect9 = Rect(origin: Point(-1, -1), size: Size(xLength: 0.5, yLength: 0.5)) let rect10 = Rect(origin: Point(0, 0), size: Size(xLength: 1, yLength: 1)) XCTAssertFalse(rect9.intersects(rect: rect10)) - + let rect11 = Rect(origin: Point(0, 0), size: Size(xLength: 2, yLength: 1)) let rect12 = Rect(origin: Point(3, 0), size: Size(xLength: 1, yLength: 1)) XCTAssertFalse(rect11.intersects(rect: rect12)) } - + func testQuadTree() { let rect = Rect(origin: Point(0, 0), size: Size(xLength: 5, yLength: 5)) let qt = QuadTree(rect: rect) - + XCTAssertTrue(qt.points(inRect: rect) == [Point]()) - + XCTAssertFalse(qt.add(point: Point(-0.1, 0.1))) - + XCTAssertTrue(qt.points(inRect: rect) == [Point]()) - + XCTAssertTrue(qt.add(point: Point(1, 1))) XCTAssertTrue(qt.add(point: Point(3, 3))) XCTAssertTrue(qt.add(point: Point(4, 4))) XCTAssertTrue(qt.add(point: Point(0.5, 0.5))) - + XCTAssertFalse(qt.add(point: Point(5.5, 0))) XCTAssertFalse(qt.add(point: Point(5.5, 1))) XCTAssertFalse(qt.add(point: Point(5.5, 2))) - + XCTAssertTrue(qt.add(point: Point(1.5, 1.5))) - + let rect2 = Rect(origin: Point(0, 0), size: Size(xLength: 2, yLength: 2)) XCTAssertTrue(qt.points(inRect: rect2) == [Point(1, 1), Point(0.5, 0.5), Point(1.5, 1.5)]) } diff --git a/Radix Sort/RadixSort.playground/Sources/radixSort.swift b/Radix Sort/RadixSort.playground/Sources/radixSort.swift index 136ede4fd..81c2479e8 100644 --- a/Radix Sort/RadixSort.playground/Sources/radixSort.swift +++ b/Radix Sort/RadixSort.playground/Sources/radixSort.swift @@ -11,18 +11,18 @@ public func radixSort(_ array: inout [Int] ) { var done = false var index: Int var digit = 1 //Which digit are we on? - - + + while !done { //While our sorting is not completed done = true //Assume it is done for now - + var buckets: [[Int]] = [] //Our sorting subroutine is bucket sort, so let us predefine our buckets - + for _ in 1...radix { buckets.append([]) } - - + + for number in array { index = number / digit //Which bucket will we access? buckets[index % radix].append(number) @@ -30,9 +30,9 @@ public func radixSort(_ array: inout [Int] ) { done = false } } - + var i = 0 - + for j in 0..: CustomStringConvertible { public var right: RBTNode! public var left: RBTNode! public var parent: RBTNode! - + public var description: String { if self.value == nil { return "null" } else { var nodeValue: String - + // If the value is encapsulated by parentheses it is red // If the value is encapsulated by pipes it is black // If the value is encapsulated by double pipes it is double black (This should not occur in a verified RBTree) @@ -27,33 +27,33 @@ public class RBTNode: CustomStringConvertible { } else { nodeValue = "||\(self.value!)||" } - + return "(\(self.left.description)<-\(nodeValue)->\(self.right.description))" } } - + init(tree: RBTree) { right = tree.nullLeaf left = tree.nullLeaf parent = tree.nullLeaf } - + init() { //This method is here to support the creation of a nullLeaf } - + public var isLeftChild: Bool { return self.parent.left === self } - + public var isRightChild: Bool { return self.parent.right === self } - + public var grandparent: RBTNode { return parent.parent } - + public var sibling: RBTNode { if isLeftChild { return self.parent.right @@ -61,19 +61,19 @@ public class RBTNode: CustomStringConvertible { return self.parent.left } } - + public var uncle: RBTNode { return parent.sibling } - + fileprivate var isRed: Bool { return color == .red } - + fileprivate var isBlack: Bool { return color == .black } - + fileprivate var isDoubleBlack: Bool { return color == .doubleBlack } @@ -82,70 +82,70 @@ public class RBTNode: CustomStringConvertible { public class RBTree: CustomStringConvertible { public var root: RBTNode fileprivate let nullLeaf: RBTNode - + public var description: String { return root.description } - + public init() { nullLeaf = RBTNode() nullLeaf.color = .black root = nullLeaf } - + public convenience init(withValue value: T) { self.init() insert(value) } - + public convenience init(withArray array: [T]) { self.init() insert(array) } - + public func insert(_ value: T) { let newNode = RBTNode(tree: self) newNode.value = value insertNode(n: newNode) } - + public func insert(_ values: [T]) { for value in values { print(value) insert(value) } } - + public func delete(_ value: T) { let nodeToDelete = find(value) if nodeToDelete !== nullLeaf { deleteNode(n: nodeToDelete) } } - + public func find(_ value: T) -> RBTNode { let foundNode = findNode(rootNode: root, value: value) return foundNode } - + public func minimum(n: RBTNode) -> RBTNode { var min = n if n.left !== nullLeaf { min = minimum(n: n.left) } - + return min } - + public func maximum(n: RBTNode) -> RBTNode { var max = n if n.right !== nullLeaf { max = maximum(n: n.right) } - + return max } - + public func verify() { if self.root === nullLeaf { print("The tree is empty") @@ -155,7 +155,7 @@ public class RBTree: CustomStringConvertible { property2(n: self.root) property3() } - + private func findNode(rootNode: RBTNode, value: T) -> RBTNode { var nextNode = rootNode if rootNode !== nullLeaf && value != rootNode.value { @@ -165,15 +165,15 @@ public class RBTree: CustomStringConvertible { nextNode = findNode(rootNode: rootNode.right, value: value) } } - + return nextNode } - + private func insertNode(n: RBTNode) { BSTInsertNode(n: n, parent: root) insertCase1(n: n) } - + private func BSTInsertNode(n: RBTNode, parent: RBTNode) { if parent === nullLeaf { self.root = n @@ -193,7 +193,7 @@ public class RBTree: CustomStringConvertible { } } } - + // if node is root change color to black, else move on private func insertCase1(n: RBTNode) { if n === root { @@ -202,14 +202,14 @@ public class RBTree: CustomStringConvertible { insertCase2(n: n) } } - + // if parent of node is not black, and node is not root move on private func insertCase2(n: RBTNode) { if !n.parent.isBlack { insertCase3(n: n) } } - + // if uncle is red do stuff otherwise move to 4 private func insertCase3(n: RBTNode) { if n.uncle.isRed { // node must have grandparent as children of root have a black parent @@ -224,14 +224,14 @@ public class RBTree: CustomStringConvertible { insertCase4(n: n) } } - + // parent is red, grandparent is black, uncle is black // There are 4 cases left: // - left left // - left right // - right right // - right left - + // the cases "left right" and "right left" can be rotated into the other two // so if either of the two is detected we apply a rotation and then move on to // deal with the final two cases, if neither is detected we move on to those cases anyway @@ -246,28 +246,28 @@ public class RBTree: CustomStringConvertible { insertCase5(n: n) } } - + private func insertCase5(n: RBTNode) { // swap color of parent and grandparent // parent is red grandparent is black n.parent.color = .black n.grandparent.color = .red - + if n.isLeftChild { // left left case rightRotate(n: n.grandparent) } else { // right right case leftRotate(n: n.grandparent) } } - + private func deleteNode(n: RBTNode) { var toDel = n - + if toDel.left === nullLeaf && toDel.right === nullLeaf && toDel.parent === nullLeaf { self.root = nullLeaf return } - + if toDel.left === nullLeaf && toDel.right === nullLeaf && toDel.isRed { if toDel.isLeftChild { toDel.parent.left = nullLeaf @@ -276,38 +276,38 @@ public class RBTree: CustomStringConvertible { } return } - + if toDel.left !== nullLeaf && toDel.right !== nullLeaf { let pred = maximum(n: toDel.left) toDel.value = pred.value toDel = pred } - + // from here toDel has at most 1 non nullLeaf child - + var child: RBTNode if toDel.left !== nullLeaf { child = toDel.left } else { child = toDel.right } - + if toDel.isRed || child.isRed { child.color = .black - + if toDel.isLeftChild { toDel.parent.left = child } else { toDel.parent.right = child } - + if child !== nullLeaf { child.parent = toDel.parent } } else { // both toDel and child are black - + var sibling = toDel.sibling - + if toDel.isLeftChild { toDel.parent.left = child } else { @@ -317,10 +317,10 @@ public class RBTree: CustomStringConvertible { child.parent = toDel.parent } child.color = .doubleBlack - + while child.isDoubleBlack || (child.parent !== nullLeaf && child.parent != nil) { if sibling.isBlack { - + var leftRedChild: RBTNode! = nil if sibling.left.isRed { leftRedChild = sibling.left @@ -329,7 +329,7 @@ public class RBTree: CustomStringConvertible { if sibling.right.isRed { rightRedChild = sibling.right } - + if leftRedChild != nil || rightRedChild != nil { // at least one of sibling's children are red child.color = .black if sibling.isLeftChild { @@ -389,7 +389,7 @@ public class RBTree: CustomStringConvertible { } } else { // sibling is red sibling.color = .black - + if sibling.isLeftChild { // left case rightRotate(n: sibling.parent) sibling = sibling.right.left @@ -400,7 +400,7 @@ public class RBTree: CustomStringConvertible { sibling.parent.color = .red } } - + // sibling check is here for when child is a nullLeaf and thus does not have a parent. // child is here as sibling can become nil when child is the root if (sibling.parent === nullLeaf) || (child !== nullLeaf && child.parent === nullLeaf) { @@ -409,14 +409,14 @@ public class RBTree: CustomStringConvertible { } } } - + private func property1() { - + if self.root.isRed { print("Root is not black") } } - + private func property2(n: RBTNode) { if n === nullLeaf { return @@ -431,48 +431,48 @@ public class RBTree: CustomStringConvertible { property2(n: n.left) property2(n: n.right) } - + private func property3() { let bDepth = blackDepth(root: self.root) - + let leaves: [RBTNode] = getLeaves(n: self.root) - + for leaflet in leaves { var leaf = leaflet var i = 0 - + while leaf !== nullLeaf { if leaf.isBlack { i = i + 1 } leaf = leaf.parent } - + if i != bDepth { print("black depth: \(bDepth), is not equal (depth: \(i)) for leaf with value: \(leaflet.value)") } } - + } - + private func getLeaves(n: RBTNode) -> [RBTNode] { var leaves = [RBTNode]() - + if n !== nullLeaf { if n.left === nullLeaf && n.right === nullLeaf { leaves.append(n) } else { let leftLeaves = getLeaves(n: n.left) let rightLeaves = getLeaves(n: n.right) - + leaves.append(contentsOf: leftLeaves) leaves.append(contentsOf: rightLeaves) } } - + return leaves } - + private func blackDepth(root: RBTNode) -> Int { if root === nullLeaf { return 0 @@ -481,7 +481,7 @@ public class RBTree: CustomStringConvertible { return returnValue + (max(blackDepth(root: root.left), blackDepth(root: root.right))) } } - + private func leftRotate(n: RBTNode) { let newRoot = n.right! n.right = newRoot.left! @@ -499,7 +499,7 @@ public class RBTree: CustomStringConvertible { newRoot.left = n n.parent = newRoot } - + private func rightRotate(n: RBTNode) { let newRoot = n.left! n.left = newRoot.right! diff --git a/Run-Length Encoding/RLE.playground/Contents.swift b/Run-Length Encoding/RLE.playground/Contents.swift index 11e177d0d..26f7dca48 100644 --- a/Run-Length Encoding/RLE.playground/Contents.swift +++ b/Run-Length Encoding/RLE.playground/Contents.swift @@ -12,16 +12,16 @@ originalString == restoredString func encodeAndDecode(_ bytes: [UInt8]) -> Bool { var bytes = bytes - + var data1 = Data(bytes: &bytes, count: bytes.count) print("data1 is \(data1.count) bytes") - + var rleData = data1.compressRLE() print("encoded data is \(rleData.count) bytes") - + var data2 = rleData.decompressRLE() print("data2 is \(data2.count) bytes") - + return data1 == data2 } @@ -66,10 +66,10 @@ func testBufferWithoutSpans() -> Bool { func testBufferWithSpans(_ spanSize: Int) -> Bool { print("span size \(spanSize)") - + let length = spanSize * 32 var bytes: [UInt8] = Array(repeating: 0, count: length) - + for t in stride(from: 0, to: length, by: spanSize) { for i in 0.. Bool { for bool in tests { result = result && bool } - + return result } diff --git a/Run-Length Encoding/RLE.playground/Sources/RLE.swift b/Run-Length Encoding/RLE.playground/Sources/RLE.swift index 5707e3d9d..0bb6fa00d 100644 --- a/Run-Length Encoding/RLE.playground/Sources/RLE.swift +++ b/Run-Length Encoding/RLE.playground/Sources/RLE.swift @@ -13,7 +13,7 @@ extension Data { var count = 0 var byte = ptr.pointee var next = byte - + // Is the next byte the same? Keep reading until we find a different // value, or we reach the end of the data, or the run is 64 bytes. while next == byte && ptr < end && count < 64 { @@ -21,7 +21,7 @@ extension Data { next = ptr.pointee count += 1 } - + if count > 1 || byte >= 192 { // byte run of up to 64 repeats var size = 191 + UInt8(count) data.append(&size, count: 1) @@ -33,7 +33,7 @@ extension Data { } return data } - + /* Converts a run-length encoded NSData back to the original. */ @@ -42,20 +42,20 @@ extension Data { self.withUnsafeBytes { (uPtr: UnsafePointer) in var ptr = uPtr let end = ptr + count - + while ptr < end { // Read the next byte. This is either a single value less than 192, // or the start of a byte run. var byte = ptr.pointee ptr = ptr.advanced(by: 1) - + if byte < 192 { // single value data.append(&byte, count: 1) } else if ptr < end { // byte run // Read the actual data value. var value = ptr.pointee ptr = ptr.advanced(by: 1) - + // And write it out repeatedly. for _ in 0 ..< byte - 191 { data.append(&value, count: 1) diff --git a/Segment Tree/SegmentTree.playground/Contents.swift b/Segment Tree/SegmentTree.playground/Contents.swift index 5bba56cc0..08474aee2 100644 --- a/Segment Tree/SegmentTree.playground/Contents.swift +++ b/Segment Tree/SegmentTree.playground/Contents.swift @@ -1,19 +1,19 @@ //: Playground - noun: a place where people can play public class SegmentTree { - + private var value: T private var function: (T, T) -> T private var leftBound: Int private var rightBound: Int private var leftChild: SegmentTree? private var rightChild: SegmentTree? - + public init(array: [T], leftBound: Int, rightBound: Int, function: @escaping (T, T) -> T) { self.leftBound = leftBound self.rightBound = rightBound self.function = function - + if leftBound == rightBound { value = array[leftBound] } else { @@ -23,19 +23,19 @@ public class SegmentTree { value = function(leftChild!.value, rightChild!.value) } } - + public convenience init(array: [T], function: @escaping (T, T) -> T) { self.init(array: array, leftBound: 0, rightBound: array.count-1, function: function) } - + public func query(leftBound: Int, rightBound: Int) -> T { if self.leftBound == leftBound && self.rightBound == rightBound { return self.value } - + guard let leftChild = leftChild else { fatalError("leftChild should not be nil") } guard let rightChild = rightChild else { fatalError("rightChild should not be nil") } - + if leftChild.rightBound < leftBound { return rightChild.query(leftBound: leftBound, rightBound: rightBound) } else if rightChild.leftBound > rightBound { @@ -46,7 +46,7 @@ public class SegmentTree { return function(leftResult, rightResult) } } - + public func replaceItem(at index: Int, withItem item: T) { if leftBound == rightBound { value = item @@ -83,7 +83,7 @@ func gcd(_ m: Int, _ n: Int) -> Int { var a = 0 var b = max(m, n) var r = min(m, n) - + while r != 0 { a = b b = r diff --git a/Segment Tree/SegmentTree.swift b/Segment Tree/SegmentTree.swift index a3ec8b1bf..6f4edd306 100644 --- a/Segment Tree/SegmentTree.swift +++ b/Segment Tree/SegmentTree.swift @@ -8,19 +8,19 @@ */ public class SegmentTree { - + private var value: T private var function: (T, T) -> T private var leftBound: Int private var rightBound: Int private var leftChild: SegmentTree? private var rightChild: SegmentTree? - + public init(array: [T], leftBound: Int, rightBound: Int, function: @escaping (T, T) -> T) { self.leftBound = leftBound self.rightBound = rightBound self.function = function - + if leftBound == rightBound { value = array[leftBound] } else { @@ -30,19 +30,19 @@ public class SegmentTree { value = function(leftChild!.value, rightChild!.value) } } - + public convenience init(array: [T], function: @escaping (T, T) -> T) { self.init(array: array, leftBound: 0, rightBound: array.count-1, function: function) } - + public func query(leftBound: Int, rightBound: Int) -> T { if self.leftBound == leftBound && self.rightBound == rightBound { return self.value } - + guard let leftChild = leftChild else { fatalError("leftChild should not be nil") } guard let rightChild = rightChild else { fatalError("rightChild should not be nil") } - + if leftChild.rightBound < leftBound { return rightChild.query(leftBound: leftBound, rightBound: rightBound) } else if rightChild.leftBound > rightBound { @@ -53,7 +53,7 @@ public class SegmentTree { return function(leftResult, rightResult) } } - + public func replaceItem(at index: Int, withItem item: T) { if leftBound == rightBound { value = item diff --git a/Select Minimum Maximum/MinimumMaximumPairs.swift b/Select Minimum Maximum/MinimumMaximumPairs.swift index b7deb570a..81942b303 100644 --- a/Select Minimum Maximum/MinimumMaximumPairs.swift +++ b/Select Minimum Maximum/MinimumMaximumPairs.swift @@ -35,6 +35,6 @@ func minimumMaximum(_ array: [T]) -> (minimum: T, maximum: T)? { } } } - + return (minimum, maximum) } diff --git a/Select Minimum Maximum/SelectMinimumMaximum.playground/Contents.swift b/Select Minimum Maximum/SelectMinimumMaximum.playground/Contents.swift index 182060805..dbf3a7468 100644 --- a/Select Minimum Maximum/SelectMinimumMaximum.playground/Contents.swift +++ b/Select Minimum Maximum/SelectMinimumMaximum.playground/Contents.swift @@ -4,7 +4,7 @@ func minimum(_ array: [T]) -> T? { guard !array.isEmpty else { return nil } - + var minimum = array.removeFirst() for element in array { minimum = element < minimum ? element : minimum @@ -18,7 +18,7 @@ func maximum(_ array: [T]) -> T? { guard !array.isEmpty else { return nil } - + var maximum = array.removeFirst() for element in array { maximum = element > maximum ? element : maximum @@ -32,18 +32,18 @@ func minimumMaximum(_ array: [T]) -> (minimum: T, maximum: T)? { guard !array.isEmpty else { return nil } - + var minimum = array.first! var maximum = array.first! - + let hasOddNumberOfItems = array.count % 2 != 0 if hasOddNumberOfItems { array.removeFirst() } - + while !array.isEmpty { let pair = (array.removeFirst(), array.removeFirst()) - + if pair.0 > pair.1 { if pair.0 > maximum { maximum = pair.0 @@ -60,7 +60,7 @@ func minimumMaximum(_ array: [T]) -> (minimum: T, maximum: T)? { } } } - + return (minimum, maximum) } diff --git a/Shell Sort/ShellSortExample.swift b/Shell Sort/ShellSortExample.swift index aaf58cf4d..e9cee7543 100644 --- a/Shell Sort/ShellSortExample.swift +++ b/Shell Sort/ShellSortExample.swift @@ -10,18 +10,18 @@ import Foundation public func shellSort(_ list : inout [Int]) { var sublistCount = list.count / 2 - + while sublistCount > 0 { for var index in 0.. list[index + sublistCount] { swap(&list[index], &list[index + sublistCount]) } - + guard sublistCount == 1 && index > 0 else { continue } - + while list[index - 1] > list[index] && index - 1 > 0 { swap(&list[index - 1], &list[index]) index -= 1 diff --git a/Shortest Path (Unweighted)/Tests/Graph.swift b/Shortest Path (Unweighted)/Tests/Graph.swift index 8322ba0a9..4d2e59eab 100644 --- a/Shortest Path (Unweighted)/Tests/Graph.swift +++ b/Shortest Path (Unweighted)/Tests/Graph.swift @@ -2,7 +2,7 @@ open class Edge: Equatable { open var neighbor: Node - + public init(neighbor: Node) { self.neighbor = neighbor } @@ -17,28 +17,28 @@ public func == (lhs: Edge, rhs: Edge) -> Bool { open class Node: CustomStringConvertible, Equatable { open var neighbors: [Edge] - + open fileprivate(set) var label: String open var distance: Int? open var visited: Bool - + public init(label: String) { self.label = label neighbors = [] visited = false } - + open var description: String { if let distance = distance { return "Node(label: \(label), distance: \(distance))" } return "Node(label: \(label), distance: infinity)" } - + open var hasDistance: Bool { return distance != nil } - + open func remove(_ edge: Edge) { neighbors.remove(at: neighbors.index { $0 === edge }!) } @@ -52,25 +52,25 @@ public func == (lhs: Node, rhs: Node) -> Bool { open class Graph: CustomStringConvertible, Equatable { open fileprivate(set) var nodes: [Node] - + public init() { self.nodes = [] } - + open func addNode(label: String) -> Node { let node = Node(label: label) nodes.append(node) return node } - + open func addEdge(_ source: Node, neighbor: Node) { let edge = Edge(neighbor: neighbor) source.neighbors.append(edge) } - + open var description: String { var description = "" - + for node in nodes { if !node.neighbors.isEmpty { description += "[node: \(node.label) edges: \(node.neighbors.map { $0.neighbor.label})]" @@ -78,18 +78,18 @@ open class Graph: CustomStringConvertible, Equatable { } return description } - + open func findNodeWithLabel(label: String) -> Node { return nodes.filter { $0.label == label }.first! } - + open func duplicate() -> Graph { let duplicated = Graph() - + for node in nodes { duplicated.addNode(label: node.label) } - + for node in nodes { for edge in node.neighbors { let source = duplicated.findNodeWithLabel(label: node.label) @@ -97,7 +97,7 @@ open class Graph: CustomStringConvertible, Equatable { duplicated.addEdge(source, neighbor: neighbour) } } - + return duplicated } } diff --git a/Shunting Yard/ShuntingYard.playground/Contents.swift b/Shunting Yard/ShuntingYard.playground/Contents.swift index fa9f5745b..bd4d15515 100644 --- a/Shunting Yard/ShuntingYard.playground/Contents.swift +++ b/Shunting Yard/ShuntingYard.playground/Contents.swift @@ -12,7 +12,7 @@ public enum OperatorType: CustomStringConvertible { case multiply case percent case exponent - + public var description: String { switch self { case .add: @@ -36,7 +36,7 @@ public enum TokenType: CustomStringConvertible { case closeBracket case Operator(OperatorToken) case operand(Double) - + public var description: String { switch self { case .openBracket: @@ -53,11 +53,11 @@ public enum TokenType: CustomStringConvertible { public struct OperatorToken: CustomStringConvertible { let operatorType: OperatorType - + init(operatorType: OperatorType) { self.operatorType = operatorType } - + var precedence: Int { switch operatorType { case .add, .subtract: @@ -68,7 +68,7 @@ public struct OperatorToken: CustomStringConvertible { return 10 } } - + var associativity: OperatorAssociativity { switch operatorType { case .add, .subtract, .divide, .multiply, .percent: @@ -77,7 +77,7 @@ public struct OperatorToken: CustomStringConvertible { return .rightAssociative } } - + public var description: String { return operatorType.description } @@ -93,19 +93,19 @@ func < (left: OperatorToken, right: OperatorToken) -> Bool { public struct Token: CustomStringConvertible { let tokenType: TokenType - + init(tokenType: TokenType) { self.tokenType = tokenType } - + init(operand: Double) { tokenType = .operand(operand) } - + init(operatorType: OperatorType) { tokenType = .Operator(OperatorToken(operatorType: operatorType)) } - + var isOpenBracket: Bool { switch tokenType { case .openBracket: @@ -114,7 +114,7 @@ public struct Token: CustomStringConvertible { return false } } - + var isOperator: Bool { switch tokenType { case .Operator(_): @@ -123,7 +123,7 @@ public struct Token: CustomStringConvertible { return false } } - + var operatorToken: OperatorToken? { switch tokenType { case .Operator(let operatorToken): @@ -132,7 +132,7 @@ public struct Token: CustomStringConvertible { return nil } } - + public var description: String { return tokenType.description } @@ -140,27 +140,27 @@ public struct Token: CustomStringConvertible { public class InfixExpressionBuilder { private var expression = [Token]() - + public func addOperator(_ operatorType: OperatorType) -> InfixExpressionBuilder { expression.append(Token(operatorType: operatorType)) return self } - + public func addOperand(_ operand: Double) -> InfixExpressionBuilder { expression.append(Token(operand: operand)) return self } - + public func addOpenBracket() -> InfixExpressionBuilder { expression.append(Token(tokenType: .openBracket)) return self } - + public func addCloseBracket() -> InfixExpressionBuilder { expression.append(Token(tokenType: .closeBracket)) return self } - + public func build() -> [Token] { // Maybe do some validation here return expression @@ -169,29 +169,29 @@ public class InfixExpressionBuilder { // This returns the result of the shunting yard algorithm public func reversePolishNotation(_ expression: [Token]) -> String { - + var tokenStack = Stack() var reversePolishNotation = [Token]() - + for token in expression { switch token.tokenType { case .operand(_): reversePolishNotation.append(token) - + case .openBracket: tokenStack.push(token) - + case .closeBracket: while tokenStack.count > 0, let tempToken = tokenStack.pop(), !tempToken.isOpenBracket { reversePolishNotation.append(tempToken) } - + case .Operator(let operatorToken): for tempToken in tokenStack.makeIterator() { if !tempToken.isOperator { break } - + if let tempOperatorToken = tempToken.operatorToken { if operatorToken.associativity == .leftAssociative && operatorToken <= tempOperatorToken || operatorToken.associativity == .rightAssociative && operatorToken < tempOperatorToken { @@ -204,11 +204,11 @@ public func reversePolishNotation(_ expression: [Token]) -> String { tokenStack.push(token) } } - + while tokenStack.count > 0 { reversePolishNotation.append(tokenStack.pop()!) } - + return reversePolishNotation.map({token in token.description}).joined(separator: " ") } diff --git a/Shunting Yard/ShuntingYard.playground/Sources/Stack.swift b/Shunting Yard/ShuntingYard.playground/Sources/Stack.swift index 27286fdbd..c54c5a600 100644 --- a/Shunting Yard/ShuntingYard.playground/Sources/Stack.swift +++ b/Shunting Yard/ShuntingYard.playground/Sources/Stack.swift @@ -2,27 +2,27 @@ import Foundation public struct Stack { fileprivate var array = [T]() - + public init() { - + } - + public var isEmpty: Bool { return array.isEmpty } - + public var count: Int { return array.count } - + public mutating func push(_ element: T) { array.append(element) } - + public mutating func pop() -> T? { return array.popLast() } - + public var top: T? { return array.last } diff --git a/Shunting Yard/ShuntingYard.swift b/Shunting Yard/ShuntingYard.swift index 97a72249d..201264650 100644 --- a/Shunting Yard/ShuntingYard.swift +++ b/Shunting Yard/ShuntingYard.swift @@ -18,7 +18,7 @@ public enum OperatorType: CustomStringConvertible { case multiply case percent case exponent - + public var description: String { switch self { case .add: @@ -42,7 +42,7 @@ public enum TokenType: CustomStringConvertible { case closeBracket case Operator(OperatorToken) case operand(Double) - + public var description: String { switch self { case .openBracket: @@ -59,11 +59,11 @@ public enum TokenType: CustomStringConvertible { public struct OperatorToken: CustomStringConvertible { let operatorType: OperatorType - + init(operatorType: OperatorType) { self.operatorType = operatorType } - + var precedence: Int { switch operatorType { case .add, .subtract: @@ -74,7 +74,7 @@ public struct OperatorToken: CustomStringConvertible { return 10 } } - + var associativity: OperatorAssociativity { switch operatorType { case .add, .subtract, .divide, .multiply, .percent: @@ -83,7 +83,7 @@ public struct OperatorToken: CustomStringConvertible { return .rightAssociative } } - + public var description: String { return operatorType.description } @@ -99,19 +99,19 @@ func < (left: OperatorToken, right: OperatorToken) -> Bool { public struct Token: CustomStringConvertible { let tokenType: TokenType - + init(tokenType: TokenType) { self.tokenType = tokenType } - + init(operand: Double) { tokenType = .operand(operand) } - + init(operatorType: OperatorType) { tokenType = .Operator(OperatorToken(operatorType: operatorType)) } - + var isOpenBracket: Bool { switch tokenType { case .openBracket: @@ -120,7 +120,7 @@ public struct Token: CustomStringConvertible { return false } } - + var isOperator: Bool { switch tokenType { case .Operator(_): @@ -129,7 +129,7 @@ public struct Token: CustomStringConvertible { return false } } - + var operatorToken: OperatorToken? { switch tokenType { case .Operator(let operatorToken): @@ -138,7 +138,7 @@ public struct Token: CustomStringConvertible { return nil } } - + public var description: String { return tokenType.description } @@ -146,27 +146,27 @@ public struct Token: CustomStringConvertible { public class InfixExpressionBuilder { private var expression = [Token]() - + public func addOperator(_ operatorType: OperatorType) -> InfixExpressionBuilder { expression.append(Token(operatorType: operatorType)) return self } - + public func addOperand(_ operand: Double) -> InfixExpressionBuilder { expression.append(Token(operand: operand)) return self } - + public func addOpenBracket() -> InfixExpressionBuilder { expression.append(Token(tokenType: .openBracket)) return self } - + public func addCloseBracket() -> InfixExpressionBuilder { expression.append(Token(tokenType: .closeBracket)) return self } - + public func build() -> [Token] { // Maybe do some validation here return expression @@ -175,29 +175,29 @@ public class InfixExpressionBuilder { // This returns the result of the shunting yard algorithm public func reversePolishNotation(_ expression: [Token]) -> String { - + var tokenStack = Stack() var reversePolishNotation = [Token]() - + for token in expression { switch token.tokenType { case .operand(_): reversePolishNotation.append(token) - + case .openBracket: tokenStack.push(token) - + case .closeBracket: while tokenStack.count > 0, let tempToken = tokenStack.pop(), !tempToken.isOpenBracket { reversePolishNotation.append(tempToken) } - + case .Operator(let operatorToken): for tempToken in tokenStack.makeIterator() { if !tempToken.isOperator { break } - + if let tempOperatorToken = tempToken.operatorToken { if operatorToken.associativity == .leftAssociative && operatorToken <= tempOperatorToken || operatorToken.associativity == .rightAssociative && operatorToken < tempOperatorToken { @@ -210,10 +210,10 @@ public func reversePolishNotation(_ expression: [Token]) -> String { tokenStack.push(token) } } - + while tokenStack.count > 0 { reversePolishNotation.append(tokenStack.pop()!) } - + return reversePolishNotation.map({token in token.description}).joined(separator: " ") } diff --git a/Skip-List/SkipList.swift b/Skip-List/SkipList.swift index e844f9959..cd832eef9 100644 --- a/Skip-List/SkipList.swift +++ b/Skip-List/SkipList.swift @@ -70,29 +70,29 @@ private func coinFlip() -> Bool { public class DataNode { public typealias Node = DataNode - - var data: Payload? + + var data: Payload? fileprivate var key: Key? var next: Node? var down: Node? - + public init(key: Key, data: Payload) { self.key = key self.data = data } public init(asHead head: Bool){} - + } open class SkipList { public typealias Node = DataNode - + fileprivate(set) var head: Node? public init() {} - + } @@ -100,18 +100,18 @@ open class SkipList { // MARK: - Search lanes for a node with a given key extension SkipList { - + func findNode(key: Key) -> Node? { var currentNode: Node? = head var isFound: Bool = false while !isFound { if let node = currentNode { - + switch node.next { case .none: - - currentNode = node.down + + currentNode = node.down case .some(let value) where value.key != nil: if value.key == key { @@ -122,14 +122,14 @@ extension SkipList { currentNode = node.down } else { currentNode = node.next - } + } } - + default: continue } - - } else { + + } else { break } } @@ -139,7 +139,7 @@ extension SkipList { } else { return nil } - + } func search(key: Key) -> Payload? { @@ -147,9 +147,9 @@ extension SkipList { return nil } - return node.next!.data - } - + return node.next!.data + } + } @@ -157,12 +157,12 @@ extension SkipList { // MARK: - Insert a node into lanes depending on skip list status ( bootstrap base-layer if head is empty / start insertion from current head ). extension SkipList { - private func bootstrapBaseLayer(key: Key, data: Payload) { - head = Node(asHead: true) + private func bootstrapBaseLayer(key: Key, data: Payload) { + head = Node(asHead: true) var node = Node(key: key, data: data) head!.next = node - + var currentTopNode = node while coinFlip() { @@ -174,7 +174,7 @@ extension SkipList { head = newHead currentTopNode = node } - + } @@ -191,13 +191,13 @@ extension SkipList { } else { currentNode = nextNode } - + } else { stack.push(currentNode!) - currentNode = currentNode!.down + currentNode = currentNode!.down } - - } + + } let itemAtLayer = stack.pop() var node = Node(key: key, data: data) @@ -208,24 +208,24 @@ extension SkipList { while coinFlip() { if stack.isEmpty { let newHead = Node(asHead: true) - + node = Node(key: key, data: data) node.down = currentTopNode newHead.next = node newHead.down = head head = newHead currentTopNode = node - - } else { + + } else { let nextNode = stack.pop() - + node = Node(key: key, data: data) node.down = currentTopNode node.next = nextNode!.next nextNode!.next = node currentTopNode = node } - } + } } @@ -233,7 +233,7 @@ extension SkipList { if head != nil { if let node = findNode(key: key) { // replace, in case of key already exists. - var currentNode = node.next + var currentNode = node.next while currentNode != nil && currentNode!.key == key { currentNode!.data = data currentNode = currentNode!.down @@ -241,12 +241,12 @@ extension SkipList { } else { insertItem(key: key, data: data) } - + } else { bootstrapBaseLayer(key: key, data: data) } } - + } @@ -257,32 +257,32 @@ extension SkipList { guard let item = findNode(key: key) else { return } - + var currentNode = Optional(item) - + while currentNode != nil { let node = currentNode!.next - + if node!.key != key { currentNode = node continue } let nextNode = node!.next - + currentNode!.next = nextNode currentNode = currentNode!.down - + } - - } + + } } // MARK: - Get associated payload from a node with a given key. extension SkipList { - + public func get(key: Key) -> Payload? { return search(key: key) } diff --git a/Strassen Matrix Multiplication/StrassensMatrixMultiplication.playground/Sources/Matrix.swift b/Strassen Matrix Multiplication/StrassensMatrixMultiplication.playground/Sources/Matrix.swift index ccfa58b09..324e906ee 100644 --- a/Strassen Matrix Multiplication/StrassensMatrixMultiplication.playground/Sources/Matrix.swift +++ b/Strassen Matrix Multiplication/StrassensMatrixMultiplication.playground/Sources/Matrix.swift @@ -9,53 +9,53 @@ import Foundation public struct Matrix { - + // MARK: - Martix Objects - + public enum Index { case row, column } - + public struct Size: Equatable { let rows: Int, columns: Int - + public static func == (lhs: Size, rhs: Size) -> Bool { return lhs.columns == rhs.columns && lhs.rows == rhs.rows } } - + // MARK: - Variables - + let rows: Int, columns: Int let size: Size - + var grid: [T] - + var isSquare: Bool { return rows == columns } - + // MARK: - Init - + public init(rows: Int, columns: Int, initialValue: T = T.zero) { self.rows = rows self.columns = columns self.size = Size(rows: rows, columns: columns) self.grid = Array(repeating: initialValue, count: rows * columns) } - + public init(size: Int, initialValue: T = T.zero) { self.init(rows: size, columns: size, initialValue: initialValue) } - + // MARK: - Private Functions - + fileprivate func indexIsValid(row: Int, column: Int) -> Bool { return row >= 0 && row < rows && column >= 0 && column < columns } - + // MARK: - Subscript - + public subscript(row: Int, column: Int) -> T { get { assert(indexIsValid(row: row, column: column), "Index out of range") @@ -65,7 +65,7 @@ public struct Matrix { grid[(row * columns) + column] = newValue } } - + public subscript(type: Matrix.Index, value: Int) -> [T] { get { switch type { @@ -95,24 +95,24 @@ public struct Matrix { } } } - + // MARK: - Public Functions - + public func row(for columnIndex: Int) -> [T] { assert(indexIsValid(row: columnIndex, column: 0), "Index out of range") return Array(grid[(columnIndex * columns)..<(columnIndex * columns) + columns]) } - + public func column(for rowIndex: Int) -> [T] { assert(indexIsValid(row: 0, column: rowIndex), "Index out of range") - + let column = (0.. T in let currentColumnIndex = currentRow * columns + rowIndex return grid[currentColumnIndex] } return column } - + public func forEach(_ body: (Int, Int) throws -> Void) rethrows { for row in 0..) -> Matrix { let A = self assert(A.columns == B.rows, "Two matricies can only be matrix mulitiplied if one has dimensions mxn & the other has dimensions nxp where m, n, p are in R") - + var C = Matrix(rows: A.rows, columns: B.columns) - + for i in 0..) -> Matrix { let A = self assert(A.columns == B.rows, "Two matricies can only be matrix mulitiplied if one has dimensions mxn & the other has dimensions nxp where m, n, p are in R") - + let n = max(A.rows, A.columns, B.rows, B.columns) let m = nextPowerOfTwo(after: n) - + var APrep = Matrix(size: m) var BPrep = Matrix(size: m) - + A.forEach { (i, j) in APrep[i,j] = A[i,j] } - + B.forEach { (i, j) in BPrep[i,j] = B[i,j] } - + let CPrep = APrep.strassenR(by: BPrep) var C = Matrix(rows: A.rows, columns: B.columns) for i in 0..) -> Matrix { let A = self assert(A.isSquare && B.isSquare, "This function requires square matricies!") guard A.rows > 1 && B.rows > 1 else { return A * B } - + let n = A.rows let nBy2 = n / 2 - + /* Assume submatricies are allocated as follows matrix A = |a b|, matrix B = |e f| |c d| |g h| */ - + var a = Matrix(size: nBy2) var b = Matrix(size: nBy2) var c = Matrix(size: nBy2) @@ -196,7 +196,7 @@ extension Matrix { var f = Matrix(size: nBy2) var g = Matrix(size: nBy2) var h = Matrix(size: nBy2) - + for i in 0.. Int { return Int(pow(2, ceil(log2(Double(n))))) } @@ -248,7 +248,7 @@ extension Matrix: Addable { assert(lhs.size == rhs.size, "To term-by-term add matricies they need to be the same size!") let rows = lhs.rows let columns = lhs.columns - + var newMatrix = Matrix(rows: rows, columns: columns) for row in 0..(lhs: Matrix, rhs: Matrix) -> Matrix { assert(lhs.size == rhs.size, "To term-by-term subtract matricies they need to be the same size!") let rows = lhs.rows let columns = lhs.columns - + var newMatrix = Matrix(rows: rows, columns: columns) for row in 0..(rows: rows, columns: columns) for row in 0.. String { let allowedCharsCount = UInt32(allowedChars.characters.count) var randomString = "" - + for _ in (0..() for _ in (1...testCount) { var randomLength = Int(arc4random_uniform(10)) - + var key = Utils.shared.randomAlphaNumericString(withLength: randomLength) - + while testStrings.contains(where: { $0.key == key}) { //That key is taken, so we generate a new one with another length randomLength = Int(arc4random_uniform(10)) @@ -29,20 +29,20 @@ class TernarySearchTreeTests: XCTestCase { } let data = Utils.shared.randomAlphaNumericString(withLength: randomLength) // print("Key: \(key) Data: \(data)") - + if key != "" && data != "" { testStrings.append((key, data)) treeOfStrings.insert(data: data, withKey: key) } } - + for aTest in testStrings { let data = treeOfStrings.find(key: aTest.key) XCTAssertNotNil(data) XCTAssertEqual(data, aTest.data) } } - + func testCanFindNumberInTree() { var testNums: [(key: String, data: Int)] = [] let treeOfInts = TernarySearchTree() @@ -55,13 +55,13 @@ class TernarySearchTreeTests: XCTestCase { randomLength = Int(arc4random_uniform(10)) key = Utils.shared.randomAlphaNumericString(withLength: randomLength) } - + if key != "" { testNums.append((key, randomNum)) treeOfInts.insert(data: randomNum, withKey: key) } } - + for aTest in testNums { let data = treeOfInts.find(key: aTest.key) XCTAssertNotNil(data) diff --git a/Ternary Search Tree/Utils.swift b/Ternary Search Tree/Utils.swift index cabfe1b68..97f09fdd2 100644 --- a/Ternary Search Tree/Utils.swift +++ b/Ternary Search Tree/Utils.swift @@ -9,22 +9,22 @@ import Foundation public struct Utils { - + public static let shared = Utils() - + let allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" //Random string generator from: //http://stackoverflow.com/questions/26845307/generate-random-alphanumeric-string-in-swift/26845710 public func randomAlphaNumericString(withLength length: Int) -> String { let allowedCharsCount = UInt32(allowedChars.characters.count) var randomString = "" - + for _ in (0.. ThreadedBinaryTree? { return search(value)?.remove() } - + /* Deletes "this" node from the tree. */ public func remove() -> ThreadedBinaryTree? { let replacement: ThreadedBinaryTree? - + if let left = left { if let right = right { replacement = removeNodeWithTwoChildren(left, right) @@ -155,33 +155,33 @@ extension ThreadedBinaryTree { parent?.rightThread = rightThread } } - + reconnectParentToNode(replacement) - + // The current node is no longer part of the tree, so clean it up. parent = nil left = nil right = nil leftThread = nil rightThread = nil - + return replacement } - + private func removeNodeWithTwoChildren(_ left: ThreadedBinaryTree, _ right: ThreadedBinaryTree) -> ThreadedBinaryTree { // This node has two children. It must be replaced by the smallest // child that is larger than this node's value, which is the leftmost // descendent of the right child. let successor = right.minimum() - + // If this in-order successor has a right child of its own (it cannot // have a left child by definition), then that must take its place. _ = successor.remove() - + // Connect our left child with the new node. successor.left = left left.parent = successor - + // Connect our right child with the new node. If the right child does // not have any left children of its own, then the in-order successor // *is* the right child. @@ -191,11 +191,11 @@ extension ThreadedBinaryTree { } else { successor.right = nil } - + // And finally, connect the successor node to our parent. return successor } - + private func reconnectParentToNode(_ node: ThreadedBinaryTree?) { if let parent = parent { if isLeftChild { @@ -228,7 +228,7 @@ extension ThreadedBinaryTree { } return nil } - + /* // Recursive version of search // Educational but undesirable due to the overhead cost of recursion @@ -242,11 +242,11 @@ extension ThreadedBinaryTree { } } */ - + public func contains(value: T) -> Bool { return search(value) != nil } - + /* Returns the leftmost descendent. O(h) time. */ @@ -257,7 +257,7 @@ extension ThreadedBinaryTree { } return node } - + /* Returns the rightmost descendent. O(h) time. */ @@ -268,7 +268,7 @@ extension ThreadedBinaryTree { } return node } - + /* Calculates the depth of this node, i.e. the distance to the root. Takes O(h) time. @@ -282,7 +282,7 @@ extension ThreadedBinaryTree { } return edges } - + /* Calculates the height of this node, i.e. the distance to the lowest leaf. Since this looks at all children of this node, performance is O(n). @@ -294,7 +294,7 @@ extension ThreadedBinaryTree { return 1 + max(left?.height() ?? 0, right?.height() ?? 0) } } - + /* Finds the node whose value precedes our value in sorted order. */ @@ -305,7 +305,7 @@ extension ThreadedBinaryTree { return leftThread } } - + /* Finds the node whose value succeeds our value in sorted order. */ @@ -333,7 +333,7 @@ extension ThreadedBinaryTree { } } } - + public func traverseInOrderBackward(_ visit: (T) -> Void) { var n: ThreadedBinaryTree n = maximum() @@ -346,19 +346,19 @@ extension ThreadedBinaryTree { } } } - + public func traversePreOrder(_ visit: (T) -> Void) { visit(value) left?.traversePreOrder(visit) right?.traversePreOrder(visit) } - + public func traversePostOrder(_ visit: (T) -> Void) { left?.traversePostOrder(visit) right?.traversePostOrder(visit) visit(value) } - + /* Performs an in-order traversal and collects the results in an array. */ @@ -390,7 +390,7 @@ extension ThreadedBinaryTree { let rightBST = right?.isBST(minValue: value, maxValue: maxValue) ?? true return leftBST && rightBST } - + /* Is this binary tree properly threaded? Either left or leftThread (but not both) must be nil (likewise for right). @@ -452,7 +452,7 @@ extension ThreadedBinaryTree: CustomDebugStringConvertible { } return s } - + public func toArray() -> [T] { return map { $0 } } diff --git a/Treap/Treap.swift b/Treap/Treap.swift index 6e80abfb2..7038e843e 100644 --- a/Treap/Treap.swift +++ b/Treap/Treap.swift @@ -27,11 +27,11 @@ import Foundation public indirect enum Treap { case empty case node(key: Key, val: Element, p: Int, left: Treap, right: Treap) - + public init() { self = .empty } - + internal func get(_ key: Key) -> Element? { switch self { case .empty: @@ -46,7 +46,7 @@ public indirect enum Treap { return nil } } - + public func contains(_ key: Key) -> Bool { switch self { case .empty: @@ -61,7 +61,7 @@ public indirect enum Treap { return false } } - + public var depth: Int { switch self { case .empty: @@ -80,12 +80,12 @@ public indirect enum Treap { public var count: Int { return Treap.countHelper(self) } - + fileprivate static func countHelper(_ treap: Treap) -> Int { if case let .node(_, _, _, left, right) = treap { return countHelper(left) + 1 + countHelper(right) } - + return 0 } } @@ -121,7 +121,7 @@ public extension Treap { return .empty } } - + fileprivate func insertAndBalance(_ nodeKey: Key, _ nodeVal: Element, _ nodeP: Int, _ left: Treap, _ right: Treap, _ key: Key, _ val: Element, _ p: Int) -> Treap { let newChild: Treap @@ -141,14 +141,14 @@ public extension Treap { newNode = .empty return newNode } - + if case let .node(_, _, newChildP, _, _) = newChild , newChildP < nodeP { return rotate(newNode) } else { return newNode } } - + internal func delete(key: Key) throws -> Treap { switch self { case .empty: diff --git a/Treap/Treap/TreapTests/TreapTests.swift b/Treap/Treap/TreapTests/TreapTests.swift index f349e6ab8..d4fc4cfdb 100644 --- a/Treap/Treap/TreapTests/TreapTests.swift +++ b/Treap/Treap/TreapTests/TreapTests.swift @@ -27,17 +27,17 @@ THE SOFTWARE.*/ import XCTest class TreapTests: XCTestCase { - + override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } - + override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } - + func testSanity() { var treap = Treap.empty treap = treap.set(key: 5, val: "a").set(key: 7, val: "b") @@ -51,7 +51,7 @@ class TreapTests: XCTestCase { XCTAssert(!treap.contains(5)) XCTAssert(treap.contains(7)) } - + func testFairlyBalanced() { var treap = Treap.empty for i in 0..<1000 { @@ -60,7 +60,7 @@ class TreapTests: XCTestCase { let depth = treap.depth XCTAssert(depth < 30, "treap.depth was \(depth)") } - + func testFairlyBalancedCollection() { var treap = Treap() for i in 0..<1000 { @@ -69,5 +69,5 @@ class TreapTests: XCTestCase { let depth = treap.depth XCTAssert(depth > 0 && depth < 30) } - + } diff --git a/Treap/TreapCollectionType.swift b/Treap/TreapCollectionType.swift index 7292c5f0a..eeee065fe 100644 --- a/Treap/TreapCollectionType.swift +++ b/Treap/TreapCollectionType.swift @@ -25,52 +25,52 @@ THE SOFTWARE.*/ import Foundation extension Treap: MutableCollection { - + public typealias Index = TreapIndex - + public subscript(index: TreapIndex) -> Element { get { guard let result = self.get(index.keys[index.keyIndex]) else { fatalError("Invalid index!") } - + return result } - + mutating set { let key = index.keys[index.keyIndex] self = self.set(key: key, val: newValue) } } - + public subscript(key: Key) -> Element? { get { return self.get(key) } - + mutating set { guard let value = newValue else { _ = try? self.delete(key: key) return } - + self = self.set(key: key, val: value) } } - + public var startIndex: TreapIndex { return TreapIndex(keys: keys, keyIndex: 0) } - + public var endIndex: TreapIndex { let keys = self.keys return TreapIndex(keys: keys, keyIndex: keys.count) } - + public func index(after i: TreapIndex) -> TreapIndex { return i.successor() } - + fileprivate var keys: [Key] { var results: [Key] = [] if case let .node(key, _, _, left, right) = self { @@ -78,28 +78,28 @@ extension Treap: MutableCollection { results.append(key) results.append(contentsOf: right.keys) } - + return results } } public struct TreapIndex: Comparable { - + public static func < (lhs: TreapIndex, rhs: TreapIndex) -> Bool { return lhs.keyIndex < rhs.keyIndex } - + fileprivate let keys: [Key] fileprivate let keyIndex: Int - + public func successor() -> TreapIndex { return TreapIndex(keys: keys, keyIndex: keyIndex + 1) } - + public func predecessor() -> TreapIndex { return TreapIndex(keys: keys, keyIndex: keyIndex - 1) } - + fileprivate init(keys: [Key] = [], keyIndex: Int = 0) { self.keys = keys self.keyIndex = keyIndex diff --git a/Treap/TreapMergeSplit.swift b/Treap/TreapMergeSplit.swift index 34cfec3d2..62d18d16f 100644 --- a/Treap/TreapMergeSplit.swift +++ b/Treap/TreapMergeSplit.swift @@ -37,7 +37,7 @@ public extension Treap { } else { fatalError("No values in treap") } - + switch self { case .node: if case let .node(_, _, _, left, right) = current.set(key: key, val: val, p: -1) { @@ -49,7 +49,7 @@ public extension Treap { return (left: .empty, right: .empty) } } - + internal var leastKey: Key? { switch self { case .empty: @@ -60,7 +60,7 @@ public extension Treap { return left.leastKey } } - + internal var mostKey: Key? { switch self { case .empty: @@ -79,7 +79,7 @@ internal func merge(_ left: Treap, right return right case (_, .empty): return left - + case let (.node(leftKey, leftVal, leftP, leftLeft, leftRight), .node(rightKey, rightVal, rightP, rightLeft, rightRight)): if leftP < rightP { return .node(key: leftKey, val: leftVal, p: leftP, left: leftLeft, right: merge(leftRight, right: right)) @@ -96,16 +96,16 @@ extension Treap: CustomStringConvertible { public var description: String { return Treap.descHelper(self, indent: 0) } - + fileprivate static func descHelper(_ treap: Treap, indent: Int) -> String { if case let .node(key, value, priority, left, right) = treap { var result = "" let tabs = String(repeating: "\t", count: indent) - + result += descHelper(left, indent: indent + 1) result += "\n" + tabs + "\(key), \(value), \(priority)\n" result += descHelper(right, indent: indent + 1) - + return result } else { return "" diff --git a/Trie/Trie/Trie/Trie.swift b/Trie/Trie/Trie/Trie.swift index 4321479c3..7ff9638d7 100644 --- a/Trie/Trie/Trie/Trie.swift +++ b/Trie/Trie/Trie/Trie.swift @@ -18,8 +18,8 @@ class TrieNode { var isLeaf: Bool { return children.count == 0 } - - + + /// Initializes a node. /// /// - Parameters: @@ -29,7 +29,7 @@ class TrieNode { self.value = value self.parentNode = parentNode } - + /// Adds a child node to self. If the child is already present, /// do nothing. /// @@ -92,7 +92,7 @@ class Trie: NSObject, NSCoding { // MARK: - Adds methods: insert, remove, contains extension Trie { - + /// Inserts a word into the trie. If the word is already present, /// there is no change. /// @@ -117,7 +117,7 @@ extension Trie { wordCount += 1 currentNode.isTerminating = true } - + /// Determines whether a word is in the trie. /// /// - Parameter word: the word to check for @@ -168,7 +168,7 @@ extension Trie { return nil } - + /// Deletes a word from the trie by starting with the last letter /// and moving back, deleting nodes until either a non-leaf or a /// terminating node is found. @@ -187,7 +187,7 @@ extension Trie { } } } - + /// Removes a word from the trie. If the word is not present or /// it is empty, just ignore it. If the last node is a leaf, /// delete that node and higher nodes that are leaves until a @@ -210,7 +210,7 @@ extension Trie { } wordCount -= 1 } - + /// Returns an array of words in a subtrie of the trie /// /// - Parameters: diff --git a/Trie/Trie/TrieUITests/TrieUITests.swift b/Trie/Trie/TrieUITests/TrieUITests.swift index f3da2a67f..acb3b1756 100644 --- a/Trie/Trie/TrieUITests/TrieUITests.swift +++ b/Trie/Trie/TrieUITests/TrieUITests.swift @@ -9,12 +9,12 @@ import XCTest class TrieUITests: XCTestCase { - + override func setUp() { super.setUp() - + // Put setup code here. This method is called before the invocation of each test method in the class. - + // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. @@ -22,15 +22,15 @@ class TrieUITests: XCTestCase { // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } - + override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } - + func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } - + } diff --git a/Z-Algorithm/ZAlgorithm.swift b/Z-Algorithm/ZAlgorithm.swift index 9bef69687..969a3599b 100644 --- a/Z-Algorithm/ZAlgorithm.swift +++ b/Z-Algorithm/ZAlgorithm.swift @@ -9,34 +9,34 @@ import Foundation func ZetaAlgorithm(ptrn: String) -> [Int]? { - + let pattern = Array(ptrn.characters) let patternLength = pattern.count - + guard patternLength > 0 else { return nil } - + var zeta = [Int](repeating: 0, count: patternLength) - + var left = 0 var right = 0 var k_1 = 0 var betaLength = 0 var textIndex = 0 var patternIndex = 0 - + for k in 1 ..< patternLength { if k > right { patternIndex = 0 - + while k + patternIndex < patternLength && pattern[k + patternIndex] == pattern[patternIndex] { patternIndex = patternIndex + 1 } - + zeta[k] = patternIndex - + if zeta[k] > 0 { left = k right = k + zeta[k] - 1 @@ -44,18 +44,18 @@ func ZetaAlgorithm(ptrn: String) -> [Int]? { } else { k_1 = k - left + 1 betaLength = right - k + 1 - + if zeta[k_1 - 1] < betaLength { zeta[k] = zeta[k_1 - 1] } else if zeta[k_1 - 1] >= betaLength { textIndex = betaLength patternIndex = right + 1 - + while patternIndex < patternLength && pattern[textIndex] == pattern[patternIndex] { textIndex = textIndex + 1 patternIndex = patternIndex + 1 } - + zeta[k] = patternIndex - k left = k right = patternIndex - 1 diff --git a/Z-Algorithm/ZetaAlgorithm.playground/Contents.swift b/Z-Algorithm/ZetaAlgorithm.playground/Contents.swift index 395122af0..44faf6790 100644 --- a/Z-Algorithm/ZetaAlgorithm.playground/Contents.swift +++ b/Z-Algorithm/ZetaAlgorithm.playground/Contents.swift @@ -2,34 +2,34 @@ func ZetaAlgorithm(ptrn: String) -> [Int]? { - + let pattern = Array(ptrn.characters) let patternLength = pattern.count - + guard patternLength > 0 else { return nil } - + var zeta = [Int](repeating: 0, count: patternLength) - + var left = 0 var right = 0 var k_1 = 0 var betaLength = 0 var textIndex = 0 var patternIndex = 0 - + for k in 1 ..< patternLength { if k > right { patternIndex = 0 - + while k + patternIndex < patternLength && pattern[k + patternIndex] == pattern[patternIndex] { patternIndex = patternIndex + 1 } - + zeta[k] = patternIndex - + if zeta[k] > 0 { left = k right = k + zeta[k] - 1 @@ -37,18 +37,18 @@ func ZetaAlgorithm(ptrn: String) -> [Int]? { } else { k_1 = k - left + 1 betaLength = right - k + 1 - + if zeta[k_1 - 1] < betaLength { zeta[k] = zeta[k_1 - 1] } else if zeta[k_1 - 1] >= betaLength { textIndex = betaLength patternIndex = right + 1 - + while patternIndex < patternLength && pattern[textIndex] == pattern[patternIndex] { textIndex = textIndex + 1 patternIndex = patternIndex + 1 } - + zeta[k] = patternIndex - k left = k right = patternIndex - 1 @@ -60,28 +60,28 @@ func ZetaAlgorithm(ptrn: String) -> [Int]? { extension String { - + func indexesOf(pattern: String) -> [Int]? { let patternLength = pattern.characters.count let zeta = ZetaAlgorithm(ptrn: pattern + "💲" + self) - + guard zeta != nil else { return nil } - + var indexes: [Int] = [] - + /* Scan the zeta array to find matched patterns */ for i in 0 ..< zeta!.count { if zeta![i] == patternLength { indexes.append(i - patternLength - 1) } } - + guard !indexes.isEmpty else { return nil } - + return indexes } } diff --git a/Z-Algorithm/ZetaAlgorithm.swift b/Z-Algorithm/ZetaAlgorithm.swift index c35703272..e60c1617f 100644 --- a/Z-Algorithm/ZetaAlgorithm.swift +++ b/Z-Algorithm/ZetaAlgorithm.swift @@ -9,28 +9,28 @@ import Foundation extension String { - + func indexesOf(pattern: String) -> [Int]? { let patternLength = pattern.characters.count let zeta = ZetaAlgorithm(ptrn: pattern + "💲" + self) - + guard zeta != nil else { return nil } - + var indexes: [Int] = [Int]() - + /* Scan the zeta array to find matched patterns */ for i in 0 ..< zeta!.count { if zeta![i] == patternLength { indexes.append(i - patternLength - 1) } } - + guard !indexes.isEmpty else { return nil } - + return indexes } }