Created
March 9, 2016 22:51
-
-
Save JRuumis/78bc7f2317cef6f137ca to your computer and use it in GitHub Desktop.
interesting that when List[Char] is replaced with String, this is dead slow
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
| /** | |
| * Created by janisrumnieks on 09/03/2016. | |
| * https://www.hackerrank.com/challenges/sequence-full-of-colors | |
| */ | |
| case class Colours (red:Int, green:Int, yellow:Int, blue:Int) { | |
| def add (colour:Char) = colour match { | |
| case 'R' => Colours(red+1, green, yellow, blue) | |
| case 'G' => Colours(red, green+1, yellow, blue) | |
| case 'Y' => Colours(red, green, yellow+1, blue) | |
| case 'B' => Colours(red, green, yellow, blue+1) | |
| } | |
| def diffRG = math.abs(red-green) | |
| def diffYB = math.abs(yellow-blue) | |
| } | |
| // R G at most 1, Y and B at most 1 | |
| object FullOfColours3 extends App { | |
| def ballCheck (currentCols: Colours, balls:List[Char] /* very slow if this is String */): Boolean = { | |
| if ( balls.isEmpty && currentCols.diffRG == 0 && currentCols.diffYB == 0 ) true // all string is consumed | |
| else if ( balls.isEmpty) false | |
| else if ( currentCols.diffRG > 1 || currentCols.diffYB > 1 ) false // check prefix lengths | |
| else { | |
| val (b, rest) = (balls.head, balls.tail) | |
| ballCheck( currentCols.add(b), rest ) | |
| } | |
| } | |
| val in = io.StdIn | |
| Range(0, in.readInt()) | |
| .map ( _ => in.readLine().toList ) | |
| .map ( balls => ballCheck( Colours(0, 0, 0, 0), balls) ) | |
| .map ( b => if (b) "True" else "False" ) | |
| .foreach(println) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment