const bigArrWorstCase = Array(5000).fill(1);
bigArrWorstCase.push(1, 5000);
const testCases = [
{test: [1, 2, 3, 4, 3, 2, 1],result: 3},
{test: [1, 100, 50, -51, 1, 1],result: 1},
{test: [1, 2, 3, 4, 5, 6],result: -1},
{test: [20, 10, 30, 10, 10, 15, 35],result: 3},
{test: [20, 10, -80, 10, 10, 15, 35],result: 0},
{test: [10, -80, 10, 10, 15, 35, 20],result: 6},
{test: [8, 8],result: -1},
{test: [8, 0],result: 0},
{test: [],result: -1},
{test: [7, 3, -3],result: 0},
{test: [8],result: 0},
{test: bigArrWorstCase, result: 5000},
];
runTests = (cb) => {
testCases.forEach((item, index) => {
const result = cb(item.test);
if (result !== item.result) throw new Error(`Test ${index + 1}: expected ${item.result}, got ${result} instead.`)
});
}
const findEvenIndex = (arr) => {
const sum = (a, b) => a + b;
return arr.findIndex((element, index) => {
return arr.slice(0, index).reduce(sum, 0) === arr.slice(index + 1).reduce(sum, 0);
});
}
runTests(findEvenIndex)
function findEvenIndex(arr) {
for (let i = 0; i < arr.length; i++) {
let leftSum = 0;
let rightSum = 0;
for (let j = 0; j < i; j++) leftSum += arr[j];
for (let j = i + 1; j < arr.length; j++) rightSum += arr[j];
if (leftSum === rightSum) return i;
}
return -1;
}
runTests(findEvenIndex)
function findEvenIndex(arr) {
let sum = arr.reduce((acc, currentValue) => acc + currentValue, 0);
let sumLeft = 0;
for (let i = 0; i < arr.length; i++) {
if (sum - sumLeft - arr[i] === sumLeft) {
return i;
}
sumLeft = sumLeft + arr[i];
}
return -1;
}
runTests(findEvenIndex)
function findEvenIndex(arr) {
const sum = {
left: 0,
right: arr.reduce((a, b) => a + b, 0),
};
for(let i = 0; i < arr.length; i++) {
sum.right -= arr[i];
if (sum.left === sum.right) {
return i;
}
sum.left += arr[i];
}
return -1;
}
runTests(findEvenIndex)
const findEvenIndex = arr => arr.findIndex((element, index) => arr.slice(0, index).reduce((a, b) => a + b, 0) === arr.slice(index + 1).reduce((a, b) => a + b, 0));
runTests(findEvenIndex)