CodeWars 코딩 문제 2021/01/05 - Consecutive Differences

이호현·2021년 1월 5일
0

Algorithm

목록 보기
43/138

[문제]

Given a list of integers, find the positive difference between each consecutive pair of numbers, and put this into a new list of differences. Then, find the differences between consecutive pairs in this new list, and repeat until the list has a length of 1. Then, return the single value.

The list will only contain integers, and will not be empty.

For example:
differences([1, 2, 3]) => [1, 1] => [0] -> 0
differences([1, 5, 2, 7, 8, 9, 0]) => [4, 3, 5, 1, 1, 9] => [1, 2, 4, 0, 8] => .. => 1
differences([2, 3, 1]) => [1, 2] => [1] => 1

(요약) 붙어 있는 요소끼리 차를 계속 구하면서 배열 요소가 하나 남을때 그 값을 return

[풀이]

function differences(a) {
  let arr = a;

  while(arr.length > 1) {
    const tempArr = [];

    for(let i = 0; i < arr.length - 1; i++) {
      tempArr.push(arr[i] > arr[i + 1] ? arr[i] - arr[i + 1] : arr[i + 1] - arr[i]);
    }

    arr = tempArr;
  }

  return arr[0];
}

전달 받은 배열의 길이가 1이 될 때까지 서로 붙어 있는 배열의 요소들끼리 큰 수 - 작은 수를 반복.
마지막에 하나 남은 수를 return.

profile
평생 개발자로 살고싶습니다

0개의 댓글