Skip to content

Instantly share code, notes, and snippets.

@haldun
Created May 25, 2016 05:07
Show Gist options
  • Save haldun/6f7222153ecf9ecfef6a5d21a220ff27 to your computer and use it in GitHub Desktop.
Save haldun/6f7222153ecf9ecfef6a5d21a220ff27 to your computer and use it in GitHub Desktop.
class PrefixMatcher {
private var set = new scala.collection.immutable.TreeSet[String]()
private def successor(s: String) = s.take(s.length - 1) + (s.charAt(s.length - 1) + 1).toChar
def add(s: String) = set += s
def findMatches(prefix: String): Set[String] =
if (prefix.isEmpty) set
else set.range(prefix, successor(prefix))
}
object PrefixMatcherApp extends App {
import scala.io.Source
def time[R](block: => R): R = {
val t0 = System.nanoTime()
val result = block // call-by-name
val t1 = System.nanoTime()
println("Elapsed time: " + (t1 - t0) / 1000000.0 + "ms")
result
}
val matcher = new PrefixMatcher()
time {
Source.fromFile("/usr/share/dict/words").getLines.foreach(matcher.add)
}
time {
val matches = matcher.findMatches("ar")
println(matches.size)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment