티스토리 뷰

알고리즘/프로그래머스 문제풀이

프로그래머스 NodeJS Level 1 : 실패율

YG - 96년생 , 강아지 있음, 개발자 희망 2022. 3. 16. 05:20
/* get input */
const N = 5;
const stages = [2, 1, 2, 6, 2, 4, 3, 3];
/* get input end*/

/* solve */
function solution(N, stages) {
  var answer = [];
  let itemCount = [];
  let rateArr = [];
  stages.map((item) => {
    const findIndex = itemCount.findIndex((itemCountItem) => {
      return +itemCountItem.title === +item;
    });
    if (findIndex === -1) {
      itemCount.push({ title: item, count: 1 });
    } else {
      itemCount = [
        ...itemCount.slice(0, findIndex),
        { title: item, count: itemCount[findIndex].count + 1 },
        ...itemCount.slice(findIndex + 1),
      ];
    }
  });
  const sortData = itemCount.sort((a, b) => a.title - b.title);
  let user = stages.length;
  sortData.map((item, i) => {
    rateArr.push({ title: item.title, rate: item.count / user });
    user = user - item.count;
  });

  rateArr.sort((a, b) => {
    return b.rate - a.rate;
  });
  console.log(rateArr);
  rateArr.map((item) => {
    if (item.title !== N + 1) answer.push(item.title);
  });
  const lastArr = Array.from({ length: N }, (_, i) => i + 1);
  lastArr.map((item) => {
    if (answer.indexOf(item) === -1) {
      answer.push(item);
    }
  });
  return answer;
}
/* solve end*/

/* print output */
console.log(solution(N, stages));
/* print output end*/

findIndex와 map , Array.from 등으로 객체가 없으면 {title : item , count :1 }을 생성하도록 했고 있다면 count를 더하는 식으로 먼저 구해준 후 stages.length 를 let 형식으로 두고 하나씩 비교해가며 stages.length  - item.count 를 하여 실패율을 구했습니다. 

 

그후 Array.from으로 1~N까지의 배열을 만들어서 answer에 있는 것과 없는 것을 비교하여 push 해주었습니다.

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함