Skip to content

Instantly share code, notes, and snippets.

@JRuumis
Created March 9, 2016 22:51
Show Gist options
  • Select an option

  • Save JRuumis/78bc7f2317cef6f137ca to your computer and use it in GitHub Desktop.

Select an option

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
/**
* 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