Created
November 25, 2009 16:00
-
-
Save bmjames/242801 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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