Question: Take an array with integers and find an index N where the sum of the integers to the left of N is equal to the sum of the integers to the right of N. If there is no index that would make this happen, return -1. Let's say you are given the array {1,2,3,4,3,2,1}: Your function equalsides() will return the index 3, because at the 3rd position of the array, the sum of left side of the index ({1,2,3}) and the sum of the right side of the index ({3,2,1}) both equal 6.
I have written the following
In code it is the following
function findEvenIndex(arr)
{
//Code goes here!
let mid =1;
let leftSum=0;
let rightSum=0;
while(mid<(arr.length-1)){
for(i=0;i<mid;i++){
leftSum=leftSum+arr[i]
}
rightSum = rightSum + arr[mid]
if(rightSum==leftSum){
console.log("mid: "+ mid);
return mid;
}
else{
mid++;
}
}
return -1;
}
however I am not sure why this is not working, any help would be appreciated
The easiest thing is to use slice
+ reduce
to find the start
and end
sum for that index
function findEvenIndex(arr) {
let index = -1;
for (var i = 0; i < arr.length; i++) {
let start = arr.slice(0, i+1).reduce((a, b) => a + b, 0);
let end = arr.slice(i).reduce((a, b) => a + b, 0)
if (start === end) {
index = i
}
}
return index;
}
console.log(findEvenIndex([1,2,3,4,3,2,1]))
const inputElement = document.querySelector("#input")
const button = document.querySelector("#btn")
const resultElement = document.querySelector("#result")
button.addEventListener("click" , ()=>{
if(!inputElement.value || inputElement.value.split(",").length <3){ return; }
const numbers = inputElement.value.split(",").map(number=>Number(number))
resultElement.textContent = findIndexOfEqualSum([...numbers])
})
function findIndexOfEqualSum(arr) {
for(let i=0; i < arr.length -1; i++){
let leftSide=0
let rightSide=0
for(j=0 ; j < i; j++){
leftSide+= arr[j]
}
for(g=i+1 ; g < arr.length; g++){
rightSide+= arr[g]
}
if(leftSide==rightSide) return i;
}
return -1;
}
<body>
<style>
body>*:not(:last-child) {
margin-bottom: .5rem;
}
#input {
display:block;
width:100%;
padding:.5rem;
}
</style>
<input
id="input"
type="text"
placeholder="enter comma seperated numbers"
>
<button id="btn"> Find Index </button>
<div id="result"> Result will be here </div>
</body>
A slightly different approach
function findEvenIndex(arr) {
let left = 0, right = arr.reduce((a, b) => a + b, 0);
for (let i = 0; left <= right; ++i) {
right -= arr[i];
if (left === right) {
return i;
}
left += arr[i];
}
return -1;
}
console.log(findEvenIndex([1, 2, 3, 4, 3, 2, 1]))