Created
September 22, 2016 08:44
-
-
Save stsatlantis/475aa0704bcd9d3972748ee0fc9b34a8 to your computer and use it in GitHub Desktop.
CodeFight - Counting characters
This file contains hidden or 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
| 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