Skip to content

Instantly share code, notes, and snippets.

@aglee
Last active June 22, 2016 16:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aglee/28f6bb715815770716073b234f497efa to your computer and use it in GitHub Desktop.
Save aglee/28f6bb715815770716073b234f497efa to your computer and use it in GitHub Desktop.
A Swift exercise
func ==(lhs: Node, rhs: Node) -> Bool {
return lhs === rhs
}
class Node: Equatable {
var value: String
var children: [Node] = []
init(_ value: String) {
self.value = value
}
func outline(indent: Int = 0, visited: [Node] = []) -> String {
if visited.contains(self) {
return ""
}
let indentString = String(count: 2*indent, repeatedValue: Character(" "))
var output = indentString + self.value
for child in self.children {
let suboutline = child.outline(indent + 1, visited: visited + [self])
if (suboutline.characters.count > 0) {
output += "\n\(suboutline)"
}
}
return output
}
func add(children: [Node]) -> Node {
self.children += children
return self
}
func search(value: String, visited: [Node] = []) -> Node? {
// Have we already visited this node?
if visited.contains(self) {
return nil
}
// Does self match?
if (self.value == value) {
return self
}
// Does any descendant node match?
for child in self.children {
if let childResult = child.search(value, visited: visited + [self]) {
return childResult
}
}
// There is no match.
return nil
}
}
let a = Node("a")
let b = Node("b")
let c = Node("c")
let d = Node("d")
let e = Node("e")
let f = Node("f")
let g = Node("g")
let h = Node("h")
// Make a tree.
a.add([
b.add([
d,
e,
f ]),
c.add([
g.add([
h ])]),
])
// Add a cycle.
d.add([a])
// Test the search() method.
print(a.outline())
for searchValue in ["e", "q"] {
if let result = a.search(searchValue) {
print("search for '\(searchValue)' returned node with value '\(result.value)'")
} else {
print("search for '\(searchValue)' found no match")
}
}
@aglee
Copy link
Author

aglee commented Jun 22, 2016

Updated outline() and search() to check for cycles.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment