Friday, June 22, 2012

Google Code Jam in Scala : Dancing With the Googlers

This is a rather trivial task to solve, and shouldn't be more than a few lines in any language. The tricky bits are not in the coding, but in getting the calculations right. So the only things Scala-specific are
  • how to use min and max
  • how to count the number of items that satisfy a condition

import scala.math.{min,max}
def solve(s:Int,p:Int,ts:List[Int]):Int = {
  val normal_limit = p + max(0, p-1) + max(0, p-1)
  val suprising_limit = p + max(0, p-2) + max(0, p-2)
  val normals = ts.count(_>=normal_limit)
  val suprisings = ts.count(t=> t>=suprising_limit && t<normal_limit)
  
  return min(s,suprisings) + normals
}

Sidenote: usually it's bad practice to name your function parameters with one letter, like "s" or "p". But if you're solving a Code Jam problem, you should always use the same naming convention as the problem text. It will save lots of additional thinking cycles.

No comments: