Skip to content

Instantly share code, notes, and snippets.

@totetmatt
Created December 18, 2019 15:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save totetmatt/01984cd9f084ac02b8d19df66056b44d to your computer and use it in GitHub Desktop.
Save totetmatt/01984cd9f084ac02b8d19df66056b44d to your computer and use it in GitHub Desktop.
Christmas Coding Challenge 2019 (Scala)
case class RegexOperator(c:Char,a:Option[Char]=None) {
def eqmatch(ch:Char): Boolean = ch == c || c == '.'
}
def parsePattern(p:String) =
p.foldLeft(Seq.empty[RegexOperator])( (agg,el)=> el match {
case '*' =>agg.init :+ agg.last.copy(a=Some('*'))
case c => agg :+ RegexOperator(c)
})
def regex(p:String,s:String): Boolean = {
def _regex(p:Seq[RegexOperator],s:String): Boolean = {
if(p.isEmpty && s.isEmpty) true
else if(p.isEmpty && s.nonEmpty) false
else {
p.head match {
case RegexOperator(_,Some('*')) if s.isEmpty || !p.head.eqmatch(s.head) => _regex(p.tail,s)
case RegexOperator(_,Some('*')) if p.head.eqmatch(s.head) => _regex(p,s.tail)
case RegexOperator(_,_) if p.head.eqmatch(s.head) => _regex(p.tail,s.tail)
case _ => false
}
}
}
_regex(parsePattern(p),s)
}
Vector(
(regex("ab","aba"),false),
(regex("a*","aa"),true),
(regex(".*","ab"),true),
(regex(".","ab"),false),
(regex("c*a*b","aab"),true),
(regex(".c*a*b","aab"),true),
(regex("a*","aaa"),true)
).foreach{ w=>
assert(w._1 == w._2)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment