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
.