Skip to content

Instantly share code, notes, and snippets.

@stsatlantis
Created September 22, 2016 08:44
Show Gist options
  • Select an option

  • Save stsatlantis/475aa0704bcd9d3972748ee0fc9b34a8 to your computer and use it in GitHub Desktop.

Select an option

Save stsatlantis/475aa0704bcd9d3972748ee0fc9b34a8 to your computer and use it in GitHub Desktop.
CodeFight - Counting characters
def shortestSolutionLength(source: Array[String]): Int = {
sealed abstract class State
case class Counting() extends State
case class Dash() extends State
case class SingleLineComment() extends State
case class Astrix() extends State
case class MultiLineComment() extends State
var count: Int = 0
def transition[T <: State](state: T, c: Char): State = {
if(c == ' ') state
else {
state match {
case Counting() =>
c match {
case '/' =>
count = count + 1
Dash()
case '\n' =>
Counting()
case _ =>
count = count + 1
Counting()
}
case Dash() =>
c match {
case '/' =>
count = count - 1
SingleLineComment()
case '*' =>
count = count - 1
MultiLineComment()
case _ =>
count = count + 1
Counting()
}
case SingleLineComment() =>
c match {
case '\n' => Counting()
case _ => SingleLineComment()
}
case Astrix() =>
c match {
case '/' => Counting()
case _ => MultiLineComment()
}
case MultiLineComment() =>
c match {
case '*' => Astrix()
case _ => MultiLineComment()
}
}
}
}
source.mkString("\n").toList.foldLeft(Counting().asInstanceOf[State])(transition)
count
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment