Skip to content

Instantly share code, notes, and snippets.

@possen
Created November 7, 2015 23:59
Show Gist options
  • Save possen/6df95c419c51b143f223 to your computer and use it in GitHub Desktop.
Save possen/6df95c419c51b143f223 to your computer and use it in GitHub Desktop.
Implementation of a Trie In Swift Sample
// Description: Implementation of a Trie
//
// Language: Swift 2.1
// Author: Paul Ossenbruggen
// Nov 7, 2015
import Foundation
class Trie {
var last : Bool = false
var children : Dictionary<Character, Trie> = [:]
init(last : Bool) {
self.last = last
}
static func addWords(words : [String]) -> Trie {
let root = Trie(last: false)
for word in words {
print(word)
root.addRemaining(word.lowercaseString)
}
return root
}
func addRemaining(var word : String) {
let char = word.removeAtIndex(word.startIndex)
var child = children[char]
if child == nil {
child = Trie(last: word.isEmpty)
children[char] = child
}
if !word.isEmpty {
child!.addRemaining(word)
}
}
func findBase(var word : String) -> Trie? {
if !word.isEmpty {
let char = word.removeAtIndex(word.startIndex)
if let trie = children[char] {
return trie.findBase(word)
}
}
return self
}
// var description : String {
// return "Trie \(last) \(children)"
// }
func compileResultsFromBase(var baseString: String, inout results : [String]) {
if last {
results.append(baseString)
}
for (key, value) in children {
baseString.append(key)
value.compileResultsFromBase(baseString, results: &results)
}
}
func findValuesForTerm(string : String) -> [String] {
let base = findBase(string)
var results = [String]()
base?.compileResultsFromBase(string, results: &results)
return results
}
}
// findall the words under that starting prefix
func findAllWords(term : String) -> [String]? {
do {
// just read the first 100 words from dictionary.
let file = try String(contentsOfFile: "/usr/share/dict/words", encoding: NSUTF8StringEncoding)
let words = Array(file.componentsSeparatedByString("\n")[0..<100])
words.count
let root = Trie.addWords(words)
let results = root.findValuesForTerm(term)
return results
} catch {
print("error")
}
return nil
}
// see reults in Playground
findAllWords("ab")
findAllWords("aa")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment