FRONT/JAVASCRIPT

[Javascript] 알고리즘 기본 문제 -일곱난쟁이

연듀 2022. 3. 22. 12:05

8. 일곱난쟁이

 

내풀이

function solution(arr) {
  let answer = [];
  let sum = arr.reduce((pre, curr) => pre + curr, 0);
  let restSum = sum - 100;

  for (let i = 0; i < arr.length; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[i] + arr[j] === restSum) {
        answer = arr.filter((x) => x !== arr[i] && x !== arr[j]);
      }
    }
  }

  return answer;
}

arr = [20, 7, 23, 19, 10, 15, 25, 8, 13];
console.log(solution(arr));

 

강사님 풀이

function solution(arr) {
  let answer = arr;
  let sum = arr.reduce((a, b) => a + b, 0);
  console.log(sum);

  for (let i = 0; i < 8; i++) {
    for (let j = i + 1; j < 9; j++) {
      if (sum - (arr[i] + arr[j]) === 100) {
        arr.splice(j, 1);
        arr.splice(i, 1);
      }
    }
  }
  return answer;
}

let arr = [20, 7, 23, 19, 10, 15, 25, 8, 13];
console.log(solution(arr));