Last active
April 25, 2016 07:47
-
-
Save maasg/5840429 to your computer and use it in GitHub Desktop.
Scala Solution to Top Coder problem: http://community.topcoder.com/stat?c=problem_statement&pm=4670&rd=8006
#Learning Scala
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
import scala.collection.immutable.StringOps | |
// Solution to Top Coder problem: http://community.topcoder.com/stat?c=problem_statement&pm=4670&rd=8006 | |
object ListeningIn { | |
def probableMatch(typed:String , phrase:String ): String = { | |
// recursively consumes both char sequences finding matches. Accumulates the elements in phraseSeq that do not match typeSeq | |
// not tail rec | |
def matcher(typeSeq:Seq[Char], phraseSeq:Seq[Char]): Option[Seq[Char]] = (typeSeq, phraseSeq) match { | |
case (Seq(), Seq()) => Some("") | |
case (Seq(), Seq(xs@_*)) => Some(xs) | |
case (Seq(_*), Seq()) => None | |
case (ts@Seq(x, xs@_*), ps@Seq(y, ys@_*)) => | |
if (ts.length > ps.length) None | |
else if (x!=y) matcher(ts,ys).map(x=> y +:x) else matcher(xs,ys) | |
} | |
matcher(typed, phrase) match { | |
case Some(chars) => chars.mkString | |
case None => "UNMATCHED" | |
} | |
} | |
probableMatch("port to me","teleport to me") //> res0: String = tele | |
probableMatch("back to base","back to base") //> res1: String = UNMATCHED | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment