Anagrams: Difference between revisions
Content deleted Content added
add E example |
No edit summary |
||
Line 598: | Line 598: | ||
elan lane lean lena neal |
elan lane lean lena neal |
||
evil levi live veil vile |
evil levi live veil vile |
||
=={{header|Scala}}== |
|||
'''Compiler:''' [[scala]] (2.7.5) |
|||
[[Category:Scala]] |
|||
{{libheader|scala.collection.mutable}} |
|||
<lang scala> |
|||
import scala.io.Source |
|||
import scala.collection.mutable |
|||
object Anagrams{ |
|||
</lang> |
|||
We can start with a most superficial method - one for printing a list of Strings. This method prints a given list of Strings |
|||
in a line , each separated by a "|". Each such list represents one set of anagrams |
|||
<lang scala> |
|||
def printList(strLst : List[String]) { |
|||
print("|") |
|||
strLst.foreach(x => print(x + "|")) |
|||
println("") |
|||
} |
|||
</lang> |
|||
Every String has a "root", which is a String which has all the characters in it alphabetically arranged. For example, |
|||
the root for the string "string" is the string "ginrst". The root for "root" is "oort". |
|||
<lang scala> |
|||
def rootString(str:String):String = new String(str.trim.toCharArray.toList.sort(_<_).toArray) |
|||
</lang> |
|||
We need a method that takes a string and a mutable map between the Strings and List of Strings. Given a String, we compute |
|||
the root of the String and then check if the root is existing as a key in the map. If it does , we append the given string |
|||
to the value mapped to that key. Otherwise, we insert the key into the map with the value as a new singleton list containing |
|||
just the given String |
|||
<lang scala> |
|||
def handleString(str:String,strMap:mutable.Map[String,List[String]]){ |
|||
val root = rootString(str) |
|||
(strMap.get(root)) match{ |
|||
case Some(lst) => strMap.update(root,str.trim::lst) |
|||
case None => strMap.update(root,List(str.trim)) |
|||
} |
|||
} |
|||
</lang> |
|||
Finally, we need the main method that creates an empty map, reads the contents of the file line and by line and appends the |
|||
map. Then we iterate over the values of the map and prints them |
|||
<lang scala> |
|||
def main(args:Array[String]){ |
|||
val fileName = "unixdict.txt" |
|||
val strmap = new mutable.HashMap[String, List[String]] |
|||
Source.fromFile(fileName).getLines.foreach(x => handleString(x,strmap)) |
|||
strmap.values.foreach(printList) |
|||
} |
|||
} |
|||
</lang> |
|||
Sample output is given below: |
|||
|mental|mantle|mantel|lament| |
|||
|vocate|octave|avocet| |
|||
|organ|groan|argon| |