Last active
December 17, 2015 05:43
-
-
Save maddiesch/dc9a4464ced7c35e8718 to your computer and use it in GitHub Desktop.
Playing with CS stuff
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: Playground - noun: a place where people can play | |
import UIKit | |
class Node<T : Hashable> : CustomStringConvertible { | |
weak var parent: Node? { | |
get { return _parent } | |
} | |
var left: Node? { | |
get { return _left } | |
} | |
var right: Node? { | |
get { return _right } | |
} | |
let value: T | |
private var _left: Node? | |
private var _right: Node? | |
private weak var _parent: Node? | |
init(value: T) { | |
self.value = value | |
} | |
var description: String { | |
get { | |
var str = "<\(value)" | |
if let left = _left { | |
str += " l:\(left)" | |
} | |
if let right = _right { | |
str += " r:\(right)" | |
} | |
return str + ">" | |
} | |
} | |
} | |
// Inserting | |
extension Node { | |
final func addValue(value: T) { | |
addChild(Node(value: value)) | |
} | |
final func addChild(node: Node<T>) { | |
if node.value.hashValue < self.value.hashValue { | |
if let left = _left { | |
left.addChild(node) | |
} else { | |
node._parent = self | |
_left = node | |
} | |
} else { | |
if let right = _right { | |
right.addChild(node) | |
} else { | |
node._parent = self | |
_right = node | |
} | |
} | |
} | |
} | |
// Searching | |
extension Node { | |
final func containsValue(value: T) -> Bool { | |
return containsNode(Node(value: value)) | |
} | |
final func containsNode(node: Node<T>) -> Bool { | |
if node.value == self.value { | |
return true | |
} | |
if node.value.hashValue < self.value.hashValue { | |
if let left = _left { | |
return left.containsNode(node) | |
} else { | |
return false | |
} | |
} else { | |
if let right = _right { | |
return right.containsNode(node) | |
} else { | |
return false | |
} | |
} | |
} | |
} | |
let root = Node(value: 80) | |
root.addValue(20) | |
root.addValue(30) | |
root.addValue(10) | |
root.addValue(100) | |
root.addValue(90) | |
root.addValue(60) | |
root.containsValue(60) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func reverse(string: String) -> String { | |
if string == "" { | |
return string | |
} else { | |
let sub = string.substringFromIndex(string.startIndex.advancedBy(1)) | |
let subSol = reverse(sub) | |
return subSol + string.substringToIndex(string.startIndex.advancedBy(1)) | |
} | |
} | |
var string = "How are you" | |
reverse(string) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment