Created
June 30, 2013 14:58
-
-
Save maasg/5895463 to your computer and use it in GitHub Desktop.
Scala solution to TopCoder exercise CmpdWords: http://community.topcoder.com/stat?c=problem_statement&pm=3490&rd=8001
#LearningScala
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
object CmpdWords { | |
def permutedPairs(elems:List[String]): List[String] = { | |
elems match { | |
case Nil => List() | |
case x::Nil => List() | |
case x::xs => { | |
for {x <- elems; | |
y <- elems-x} yield x+y | |
} | |
} | |
} | |
def frequency(words: List[String]) = words.foldLeft(Map[String,Int]())((map,word) => { | |
val count = map.getOrElse(word,0)+1; | |
map + ((word,count)) | |
}) | |
def ambiguous(dictionary: Array[String]) : Int = { | |
val compoundWords = permutedPairs(dictionary.toList) | |
val compoundWordFrequency = frequency(compoundWords) | |
compoundWords.toSet.count(x => dictionary.contains(x) || compoundWordFrequency(x)>1) | |
} | |
ambiguous(Array("a","aa","aaa")) //> res0: Int = 3 | |
ambiguous(Array("am","eat","a", "meat", "hook","meathook")) //> res1: Int = 2 | |
ambiguous(Array("abc","bca","bab","a")) //> res2: Int = 1 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice! You can simplify how to compute all the combinations of two different words in a list like this: