/**
* 실패율.js
* https://programmers.co.kr/learn/courses/30/lessons/42889
*/
function solution(N, stages) {
const stageReached = new Array(N+1).fill(0);
stages.forEach((stage) => {
for (let i = 0; i < stage; i++) {
stageReached[i]++;
}
});
const stageFailed = [];
for (let j = 0; j < stageReached.length - 1; j++) {
const failureRate = (stageReached[j] - stageReached[j+1]) / (stageReached[j]);
stageFailed.push({failureRate, stage: j+1});
}
return stageFailed.sort((a, b) => b.failureRate - a.failureRate).map((obj) => obj.stage);
}
module.exports.solution = solution;
스테이지보다 1개 많게 stageReached 배열을 만들고 모두 0으로 초기화 해준다. stages 배열을 돌면서 현재 스테이지 포함 그 이하 모든 스테이지에 도달한 사람 숫자를 늘려준다.
실패율 = (N 스테이지 이상 도달한 수 - N 스테이지 초과 도달한 수) / (N 스테이지 이상 도달한 수)
= (N 스테이지 이상 도달한 수 - N+1 스테이지 이상 도달한 수) / (N 스테이지 이상 도달한 수)
위와 같은 공식으로 실패율을 구하고, 실패율과 stage 를 객체에 담아 stageFiled 배열에 추가해준다.
stageFiled 배열을 실패율을 기준으로 내림차순으로 정렬하고 stage 를 return 해준다.
/**
* 실패율.test.js
*/
const { solution } = require("./실패율")
test('[2, 1, 2, 6, 2, 4, 3, 3]', () => {
expect(solution(5, [2, 1, 2, 6, 2, 4, 3, 3])).toEqual([3,4,2,1,5]);
});
test('[4,4,4,4,4]', () => {
expect(solution(4, [4,4,4,4,4])).toEqual([4,1,2,3]);
});
'알고리즘 > 프로그래머스' 카테고리의 다른 글
[프로그래머스][자바스크립트][Level1] 2016년 (0) | 2022.01.06 |
---|---|
[프로그래머스][자바스크립트][Level1] 두 개 뽑아서 더하기 (0) | 2022.01.06 |
[프로그래머스][자바스크립트][Level2] H-Index (0) | 2022.01.04 |
[프로그래머스][자바스크립트][Level2] 가장 큰 수 (0) | 2022.01.04 |
[프로그래머스][자바스크립트][Level1] 없는 숫자 더하기 (0) | 2022.01.04 |
댓글