HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Solving for equilibrium index in an array

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
solvingequilibriumarrayforindex

Problem

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 impro

Solution

I'm piggy backing on @jonah's answer. The first code snippet returns what Codility is asking for: any equilibrium index. Second code snippet returns all answers like in @jonah's suggestion. I also added two accumulating arrays for side by side comparison. You can add a breakpoint at the end of the function to compare the two arrays.



var A = [-1, 3, -4, 5, 1, -6, 2, 1];

function solution(A) {
var rightSum = A.reduce((acc, val) => acc + val, 0), leftSum = 0;

for (var i = 0; i





var A = [-1,3,-4,5,1,-6,2,1];

function solution(A) {

var rightSum = A.reduce((acc, val) => acc + val, 0), leftSum = 0, rightSums = [], leftSums = [], answers = [];

for (var i = 0; i

Context

StackExchange Code Review Q#108262, answer score: 5

Revisions (0)

No revisions yet.