Algorithm/codewars

Equal Sides Of An Array 답안

Bonita SY 2021. 3. 24. 20:38
728x90
반응형

문제)

www.codewars.com/kata/5679aa472b8f57fb8c000047/train/javascript

 

Codewars: Achieve mastery through challenge

Codewars is where developers achieve code mastery through challenge. Train on kata in the dojo and reach your highest potential.

www.codewars.com

 

내가 푼 답)

function findEvenIndex(arr)
{
  var result = -1;
  for (var i=0; i<arr.length; i++) {
    var leftArr = arr.slice(0, i);
    var leftArrSum = leftArr.length === 0 ? 0 : leftArr.reduce((acc, curVal) => acc + curVal);
    var rightArr = arr.slice(i+1);
    var rightArrSum = rightArr.length === 0 ? 0 : rightArr.reduce((acc, curVal) => acc + curVal);
    if (leftArrSum === rightArrSum) {
      result = i;
    }
  }
  return result;
}

 

테스트 결과)

 

마음에 드는 남이 푼 소스)

728x90
반응형

'Algorithm > codewars' 카테고리의 다른 글

Moving Zeros To The End 답안  (0) 2021.03.24
Where my anagrams at? 답안  (0) 2021.03.24
Are they the "same"? 답안  (0) 2021.03.24
Counting Duplicates 답안  (0) 2021.03.24
Valid Braces 답안  (0) 2021.03.24