Created
August 24, 2016 10:36
-
-
Save schalkneethling/cf7b93eabd4f0de714965f51b5122353 to your computer and use it in GitHub Desktop.
Using a data array of numbers returns an array of equilibrium indexes
This file contains hidden or 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
var data = [-1, 3, -4, 5, 1, -6, 2, 1]; | |
function upperTotal(index, data) { | |
var totalUpper = 0; | |
for (var i = index + 1, l = data.length; i < l; i++) { | |
totalUpper = totalUpper + data[i]; | |
} | |
return totalUpper; | |
} | |
function lowerTotal(index, data) { | |
var totalLower = 0; | |
for (var i = 0, l = data.length; i < index; i++) { | |
totalLower = totalLower + data[i]; | |
} | |
return totalLower; | |
} | |
function isEquilibriumIndex(currentIndex, data) { | |
var totalLower = lowerTotal(currentIndex, data); | |
var totalUpper = upperTotal(currentIndex, data); | |
return totalLower === totalUpper; | |
} | |
function getEquilibriumIndexes(data) { | |
var equilibriumIndexes = []; | |
for (var i = 0, l = data.length; i < l; i++) { | |
if (isEquilibriumIndex(i, data)) { | |
equilibriumIndexes.push(i); | |
} | |
} | |
return equilibriumIndexes; | |
} | |
console.log(getEquilibriumIndexes(data)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment