I encoded a solution to the TapeEquilibrium problem on Codility using Scala. I tried many test inputs with different loads, and when I run the results using the Codility Develipment environment and on eclipse, I get the correct answers. However, when I submit the result, it fails on almost every test with the wrong answer. I can’t push on the exact inputs, but I created similar inputs with random numbers, and these inputs always work. For a while I was looking through my logic, but I can’t understand what I am doing wrong. Can anybody help me.
The test can be found here.
Here is my code
import org.scalacheck.Gen
import org.scalacheck._
object Problem1 extends App {
def solution( A: Array[ Int ] ): Int = {
var sumRight = A.foldLeft( 0 )( _ + _ )
var sumLeft = 0;
def absDiffer( a: Int, b: Int ) = if ( a < b ) b - a else a - b
def minimizer( ar: List[ Int ], prevDiff: Int, sumL: Int, sumR: Int ): Int = {
val diff = absDiffer( sumL, sumR )
if ( diff <= prevDiff )
minimizer( ar.tail, diff, ar.head + sumL, sumR - ar.head )
else
prevDiff
}
minimizer( A.toList, absDiffer( A.head, sumRight - A.head ), A.head, sumRight - A.head )
}
def randomInput( length: Int ) = {
Gen.listOfN( length, Gen.oneOf( Range( -1000, 1000 ) ) ).sample.get
}
def randomPosInput( length: Int ) = {
Gen.listOfN( length, Gen.oneOf( Range( 1, 100 ) ) ).sample.get
}
def randomNegInput( length: Int ) = {
Gen.listOfN( length, Gen.oneOf( Range( -1000, -1 ) ) ).sample.get
}
val ar = randomPosInput( 100000 )
val inputString = ar.mkString( "[", ", ", "]" )
val clipboard = java.awt.Toolkit.getDefaultToolkit().getSystemClipboard()
val sel = new java.awt.datatransfer.StringSelection( inputString )
clipboard.setContents( sel, sel )
println( inputString )
println( solution( ar.toArray ) )
}
source
share