Skip to content

Instantly share code, notes, and snippets.

@bmjames
Created November 25, 2009 16:00
Show Gist options
  • Save bmjames/242801 to your computer and use it in GitHub Desktop.
Save bmjames/242801 to your computer and use it in GitHub Desktop.
import scala.collection.mutable.{Map => MutableMap}
import scala.io.Source
class AnagramMap {
protected val anagrams = MutableMap.empty[String, Set[String]]
def add(word: String) {
val normalised = normalise(word.toLowerCase)
val equivalents = anagrams.getOrElseUpdate(normalised, Set.empty[String])
anagrams(normalised) = equivalents + word.toLowerCase
}
def getAnagrams = anagrams.values filter { _.size > 1 } toList
protected def normalise(word: String) = word.toList sort {_<_} mkString
}
val a = new AnagramMap
for (line <- Source.fromFile("/usr/share/dict/words").getLines)
a add line.trim
val anagrams = a.getAnagrams
anagrams map { _ mkString ", " } foreach println
println("Found "+anagrams.length+" sets of anagrams")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment