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
- Declare two variables mid and i where mid the index we are looking for i= this is starting index
- Then while (mid<= arr.length-1) we will go through the array and add up each side of the array one side from i=0 to i=mid and then from i=mid to i=array.length-1, while adding up each side to leftSum and rightSum respectively
- And if leftSum==rightSum in any of these instances we will return mid if it didnt it will increase mid by one and reiterate ,
- If mid is not returned we will return -1 at the end.
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
CodePudding user response:
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]))
CodePudding user response:
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>