Inspired by a random tweet about their added Scala support, I tried out the Codility sample test. I rather liked my solution and I think it’s a perfect example of some of the niceties of Scala, in a small way, so here it is:

def solution(a: Array[Int]): Int = {
  // Partial sums are Longs to avoid Int overflow.
  val sums = a.scanLeft(0L)(_ + _).tail
  def equilibrium(index: Int) = leftSum(index) == rightSum(index)
  def leftSum(index: Int) = if (index == 0) 0 else sums(index - 1)
  def rightSum(index: Int) = sums.last - sums(index)
  (0 until a.length) find (equilibrium(_)) getOrElse(-1)
}

The use of scanLeft to build up all the partial sums is particularly handy. Having done that it’s very easy to run through all the indexes until we find one that satisfies us. Note that the find method returns an Option[A] so we use getOrElse to return -1 if no solution was found (as per the requirements).

Leave a Reply

Your email address will not be published. Required fields are marked *