Skip to content

Instantly share code, notes, and snippets.

@khanlou
Last active April 18, 2018 00:55
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 khanlou/ce9a6ed4310dfbbcf8ab4b80692ead58 to your computer and use it in GitHub Desktop.
Save khanlou/ce9a6ed4310dfbbcf8ab4b80692ead58 to your computer and use it in GitHub Desktop.
import Foundation
let url = try URL(string: "http://norvig.com/ngrams/TWL06.txt").unwrap()
let data = try Data(contentsOf: url)
let string = try String(data: data, encoding: .utf8).unwrap()
let array = string.components(separatedBy: .newlines)
let lexicon = Set(array.fourLetterStrings())
let allLetters = Array("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
func findPath(between sourceWord: String, and targetWord: String) -> [String]? {
if sourceWord == targetWord { return [] }
var seen: Set = [sourceWord]
var queue: [(item: String, path: [String])] = [(sourceWord, [])]
while true {
if queue.count == 0 { return nil }
let (item, path) = queue.removeFirst()
if item == targetWord { return path + [item] }
let sourceAsArray = Array(item)
for characterIndex in sourceAsArray.indices {
for letter in allLetters {
var copy = sourceAsArray
copy[characterIndex] = letter
let oneLetterAway = String(copy)
if lexicon.contains(oneLetterAway) && !seen.contains(oneLetterAway) {
queue.append((oneLetterAway, path + [item]))
seen.insert(oneLetterAway)
}
}
}
}
}
let path = try findPath(between: "TOON", and: "PLEA").unwrap()
print(path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment