Created
January 27, 2014 17:16
-
-
Save vivekn/8652998 to your computer and use it in GitHub Desktop.
This file contains 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
package autocorrect | |
import scala.collection.mutable.Map | |
import scala.collection.mutable.ArrayBuffer | |
class BKTree(val str: String) { | |
var children: Map[Int, BKTree] = Map[Int, BKTree]() | |
def add(word: String): Unit = { | |
val dist = Utils.levenshtein(str, word) | |
if (children contains dist) children(dist) add word | |
else children(dist) = new BKTree(word) | |
} | |
def find(word: String, tolerance: Int, results: ArrayBuffer[(Int, String)]): ArrayBuffer[(Int, String)] = { | |
val dist = Utils.levenshtein(str, word) | |
if (dist <= tolerance) results.append((dist, str)) | |
for(i <- (dist - tolerance) to (dist + tolerance) if children contains i) { | |
children(i).find(word, tolerance, results) | |
} | |
results | |
} | |
def suggest(word: String, tolerance: Int):ArrayBuffer[String] = { | |
val results = find(word, tolerance, ArrayBuffer[(Int, String)]()).sorted | |
for((_, word) <- results) yield word | |
} | |
val += :(String) => Unit = add | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment