I did a sample on Codility and finished the test task.
The problem description is very short:
The equilibrium index of a sequence is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes. For example, in a sequence
A
:$$A[0]=-7, A[1]=1, A[2]=5 ,A[3]=2, A[4]=-4, A[5]=3, A[6]=0$$
\$3\$ is an equilibrium index, because:
$$A[0]+A[1]+A[2]=A[4]+A[5]+A[6]$$
\$6\$ is also an equilibrium index, because:
$$A[0]+A[1]+A[2]+A[3]+A[4]+A[5]=0$$
(The sum of zero elements is zero) \$7\$ is not an equilibrium index - because it is not a valid index of sequence A. If you still have doubts, here is a precise definition: The integer \$k\$ is an equilibrium index of a sequence \$A[0],A[1]\dots,A[n-1]\$ if and only if \$0\le k\$ and \$\sum(A[0\dots(k-1)])=\sum(A[(k+1)\dots(n-1)])\$. Assume the sum of zero elements is equal to zero.
The code I wrote gives the correct result, but, I only scored 8% on correctness and a 54% on performance. Here is my code:
// you can write to stdout for debugging purposes, e.g.
// console.log('this is a debug message');
function solution(A) {
// write your code in JavaScript (Node.js 4.0.0
var arrLen = A.length;
var i = 0;
for(i = 0; i < arrLen; i++){
//console.log("i: " + i);
var firstSum = 0;
var secSum = 0;
var currIndex = i + 1;
//get first chunk
var j = 0;
var lenJ = currIndex;
for(j = 0; j < lenJ; j++){
//console.log("firstChink: " + j);
firstSum += A[j];
}
//get second chunk
j = currIndex + 1;
lenJ = arrLen;
for(j; j < lenJ; j++){
//console.log("secChunk: " + j);
secSum += A[j];
}
if(firstSum == secSum){
return currIndex;
}
}
return arrLen;
}
Can somebody explain why my code scored so low? And what to do to improve?