CodeWars 코딩 문제 2021/02/05 - Simple arithmetic progression
[문제]
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개를 뽑고, 따로 정렬을 안해도 됨.
그래서 index
가 1
에서 0
을 빼고, 2
에서 1
을 뺀 차가 같으면 됨.
아니면 아래처럼
(arr[0] + arr[2]) / 2 === arr[1]
작은 수와 큰 수의 평균이 중간수랑 같아도 됨.
Author And Source
이 문제에 관하여(CodeWars 코딩 문제 2021/02/05 - Simple arithmetic progression), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://velog.io/@hemtory/CodeWars20210205
저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
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개를 뽑고, 따로 정렬을 안해도 됨.
그래서 index
가 1
에서 0
을 빼고, 2
에서 1
을 뺀 차가 같으면 됨.
아니면 아래처럼
(arr[0] + arr[2]) / 2 === arr[1]
작은 수와 큰 수의 평균이 중간수랑 같아도 됨.
Author And Source
이 문제에 관하여(CodeWars 코딩 문제 2021/02/05 - Simple arithmetic progression), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@hemtory/CodeWars20210205저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)