Skip to content

Instantly share code, notes, and snippets.

@maasg
Created June 30, 2013 14:58
Show Gist options
  • Save maasg/5895463 to your computer and use it in GitHub Desktop.
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
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
}
@sbocq
Copy link

sbocq commented Aug 10, 2013

Nice! You can simplify how to compute all the combinations of two different words in a list like this:

def permutedPairs(elems:List[String]): List[String] = 
  for {
    x <- elems
    y <- elems if y != x
  } yield x+y

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment