Created
February 17, 2017 00:05
-
-
Save johhansantana/f25031369d254ddd52ee19be47da0f75 to your computer and use it in GitHub Desktop.
Find Equilibrium index in array in javascript
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
const findEquilibrium = A => { | |
let firstArray = []; | |
let firstSum = 0; | |
let secondArray = []; | |
let secondSum = 0; | |
for (let i = 0; i < A.length; i++) { | |
let currentIndex = i + 1; | |
firstArray.push(A[i]); | |
firstSum = firstArray.reduce((a, b) => { | |
return a + b; | |
}, 0); | |
secondArray = []; | |
secondSum = 0; | |
for (let i = currentIndex; i < A.length; i++) { | |
if (A[i] != undefined) { | |
secondArray.push(A[i]); | |
} | |
secondSum = secondArray.reduce((a, b) => { | |
return a + b; | |
}, 0); | |
} | |
if (firstSum == secondSum) break; | |
} | |
return firstArray.length; | |
}; | |
const a = [1,2,3,3,2,1]; // = 3 | |
const b = [10,1,5,3,1]; // = 1 | |
const c = [1,4,2,1,1,2,5,6]; // = 6 | |
console.log(findEquilibrium(a)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment