findEvenIndex.js

Codewars 알고리즘 풀이


Problem

  • You are going to be given an array of integers.
    • 정수 배열이 주어진다.
  • Your job is to take that array 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 N.
    • N의 왼쪽에 있는 정수의 합이, N의 오른쪽에 있는 정수의 합과 같은 index N을 찾는다.
  • If there is no index that would make this happen, return -1.
    • 없다면 -1을 반환한다.



Solution 01

function findEvenIndex(arr) {
  let left = 0;
  let right = arr.reduce((total, i) => total + i, 0);
  
  for (let i = 0; i < arr.length; i++) {
    right -= arr[i];
    
    if (left === right) return i;
    left += arr[i];
  }
  return -1;
}

findEvenIndex([]);                       // -1 (Empty)
findEvenIndex([1, 2, 3, 4]);             // -1 (Nothing)
findEvenIndex([1, 2, 3, 4, 3, 2, 1]);    // 3 (N: 4)
findEvenIndex([1, 100, 50, -51, 1, 1]);  // 1 (N: 100)


Solution 02

function findEvenIndex(arr) {
  for (let i = 0; i < arr.length; i++) {
    let sumLeft = arr.slice(0, i).reduce((total, i) => total + i, 0);
    let sumRight = arr.slice(i + 1).reduce((total, i) => total + i, 0);
    
    if (sumLeft === sumRight) {
      return i;
    }
  }
  return -1;
}

findEvenIndex([]);                       // -1 (Empty)
findEvenIndex([1, 2, 3, 4]);             // -1 (Nothing)
findEvenIndex([1, 2, 3, 4, 3, 2, 1]);    // 3 (N: 4)
findEvenIndex([1, 100, 50, -51, 1, 1]);  // 1 (N: 100)


Solution 03

function findEvenIndex(arr) {
  let result = -1;
  
  for (let i = 0; i < arr.length; i++) {
    let sumLeft = arr.slice(0, i).reduce((total, i) => total + i, 0);
    let sumRight = arr.slice(i + 1).reduce((total, i) => total + i, 0);
    
    if (sumLeft === sumRight) {
      result = i;
      break;
    }
  }
  return result;
}

findEvenIndex([]);                       // -1 (Empty)
findEvenIndex([1, 2, 3, 4]);             // -1 (Nothing)
findEvenIndex([1, 2, 3, 4, 3, 2, 1]);    // 3 (N: 4)
findEvenIndex([1, 100, 50, -51, 1, 1]);  // 1 (N: 100)


Solution 04

function findEvenIndex(arr) {
  for (var i = 1; i < arr.length - 1; i++) {
    if (arr.slice(0, i).reduce((total, i) => total + i, 0) === arr.slice(i + 1).reduce((total, i) => total + i, 0)) {
      return i;
    }
  }
  return -1;
}

findEvenIndex([]);                       // -1 (Empty)
findEvenIndex([1, 2, 3, 4]);             // -1 (Nothing)
findEvenIndex([1, 2, 3, 4, 3, 2, 1]);    // 3 (N: 4)
findEvenIndex([1, 100, 50, -51, 1, 1]);  // 1 (N: 100)