CodeWars 코딩 문제 2021/02/05 - Simple arithmetic progression

이호현·2021년 2월 5일
0

Algorithm

목록 보기
76/138

[문제]

In this Kata, you will be given an array of integers and your task is to return the number of arithmetic progressions of size 3 that are possible from that list. In each progression, the differences between the elements must be the same.

[1, 2, 3, 5, 7, 9] ==> 5
// [1, 2, 3], [1, 3, 5], [1, 5, 9], [3, 5, 7], and [5, 7, 9]

All array elements will be unique and sorted. More examples in test cases.

(요약) 주어진 배열에서 요소 3개씩을 뽑아 등차인 배열의 개수 찾기

[풀이]

function solve(arr){
  return combination(arr, 3).filter(arr => (arr[1] - arr[0]) === (arr[2] - arr[1])).length;
}

function combination(arr, selectNum) {
  const result = [];
  if (selectNum === 1) return arr.map((v) => [v]);
  arr.forEach((v, idx, arr) => {
    const fixed = v;
    const restArr = arr.slice(idx + 1);
    const combinationArr = combination(restArr, selectNum - 1);
    const combineFix = combinationArr.map((v) => [fixed, ...v]);
    result.push(...combineFix);
  });
  return result;
}

주어진 배열에서 조합 알고리즘을 사용.
주어진 배열이 오름차순 정렬된 상태라 숫자 3개를 뽑고, 따로 정렬을 안해도 됨.
그래서 index1에서 0을 빼고, 2에서 1을 뺀 차가 같으면 됨.
아니면 아래처럼

(arr[0] + arr[2]) / 2 === arr[1]

작은 수와 큰 수의 평균이 중간수랑 같아도 됨.

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

0개의 댓글