Created
September 3, 2015 06:15
-
-
Save jeffsteinmetz/881c48b5c2ae2af3871e to your computer and use it in GitHub Desktop.
My purely functional Scala solution to the equilibrium index problem by codility
This file contains 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
// My scala solution (purely functional with no mutable variables) | |
// to the sample codility problem for finding | |
// any equilibrium index in an array of ints with up to | |
// 10 million entries. Description of problem is here: | |
// http://blog.codility.com/2011/03/solutions-for-task-equi.html | |
// this is O(N) and uses a scala List (instead of an Array) to maximize the | |
// speed of .head and .tail operations | |
import scala.annotation.tailrec | |
object Solution { | |
def solution(A: Array[Int]): Int = { | |
// convert to Long to avoid overflows, then to List[Long] | |
val B: List[Long] = A.map(_.toLong).toList | |
testEquil(B, 0L, B.sum, 0) | |
} | |
@tailrec | |
def testEquil(A: List[Long], leftSum: Long, rightSum: Long, P: Int): Int = { | |
if (A.isEmpty) return -1 | |
if (leftSum == rightSum - A.head) return P | |
testEquil(A.tail, leftSum + A.head, rightSum - A.head, P+1) | |
} | |
} | |
// example call with 10 million entries | |
val result = Solution.solution(Array.fill(5000000)(1) ++ Array(100) ++ Array.fill(5000000)(1)) | |
println(result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment