[프로그래머스] 2022 KAKAO BLIND RECRUITMENT > 신고 결과 받기

Lee_Sangmin·2022년 5월 6일
0

algorithm

목록 보기
1/1
post-thumbnail

문제

https://programmers.co.kr/learn/courses/30/lessons/92334?language=javascript


최초 접근

function solution(id_list, report, k) {
  let answer = [];

  const uniqueArr = report.filter((element, index) => {
    return report.indexOf(element) === index;
  });

  const test = uniqueArr.map((v, i) => {
    return v.split(" ");
  });

  const reportObj = numberOfReports(id_list, test);
  const reportedPerson = checkReport(reportObj, k);
  return sendMail(id_list, test, reportedPerson);
}

const numberOfReports = (id_list, reported) => {
  const NUMBER_OF_USERS = id_list.length;
  const NUMBER_OF_REPORTED_PERSON = reported.length;

  let obj = new Object();

  id_list.forEach(function (item, index) {
    obj[id_list[index]] = 0;
  });

  for (let i = 0; i < NUMBER_OF_REPORTED_PERSON; i++) {
    obj[reported[i][1]]++;
  }

  return obj;
};

const checkReport = (obj, k) => {
  const TOTAL_PERSON = Object.keys(obj).length;
  let returnArray = [];

  for (let i = 0; i < TOTAL_PERSON; i++) {
    if (Object.values(obj)[i] >= k) {
      returnArray.push(Object.keys(obj)[i]);
    }
  }

  return returnArray;
};

const sendMail = (id_list, test, reportedPerson) => {
  const TOTAL_PERSON = id_list.length;
  const REPORTED_PERSON = test.length;

  const createZeroArray = (len) => {
    return new Array(len).fill(0);
  };
  let ansArray = createZeroArray(TOTAL_PERSON);

  for (let k = 0; k < TOTAL_PERSON; k++)
    for (let i = 0; i < REPORTED_PERSON; i++) {
      if (test[i][0] === id_list[k] && reportedPerson.includes(test[i][1])) {
        ansArray[k]++;
      }
    }

  return ansArray;
};

1) 이용자 신고 누적 수를 객체로 리턴 해주는 함수.
2) 누적된 신고 수를 기반으로 게시판 불량 이용자 이름을 배열로 리턴해주는 함수.
3) 불량 이용자를 신고한 사람을 배열로써 값 접근하는 함수.
로 나누어 작성하였다.

초기 id_list에 대해 값으로써 접근할 수 있는 방법을 알고있었으면 이렇게 어렵게 접근하지 않았을텐데.
코드를 작성해 나가기 전에 생각하는 시간이 더 중요하다는걸 다시 느꼈다.

예상했던대로 마지막 '3)'에서 이중 for문때문에 몇개의 테스트 케이스에서 시간초과가 발생했다.


다른 풀이

참고 : https://github.com/codeisneverodd/programmers-coding-test/blob/main/level-1/%EC%8B%A0%EA%B3%A0-%EA%B2%B0%EA%B3%BC-%EB%B0%9B%EA%B8%B0.js

다른 분의 몸풀기용 문제라는 말을 듣고 좀 슬펐다😞

function solution(id_list, report, k) {
  const reportSet = new Set(report);
  const reportedCount = {}; //{"id": Number(count)}
  const reportedBy = {}; //{"id":[]}
  const mailCount = {}; //{"id":Number(count)}

  id_list.forEach((element) => {
    reportedCount[element] = 0;
    mailCount[element] = 0;
    reportedBy[element] = [];
  });

  reportSet.forEach((element) => {
    const [id, reported] = element.split(" ");
    reportedCount[reported] += 1;
    reportedBy[reported].push(id);
  });

  for (const reportedId in reportedCount) {
    if (reportedCount[reportedId] >= k) {
      reportedBy[reportedId].forEach((reporter) => {
        mailCount[reporter] += 1;
      });
    }
  }

  return id_list.map((id) => mailCount[id]);
}



문제풀이 핵심

  1. id_list.forEach()문을 통한 관련 객체의 initial값 지정

  2. reportedBy까지 모두 객체로 보유 (자신을 신고한 사람의 리스트까지 객체로 보유)


새로 알게된 사실

  • 단일 값으로 이루어진 일정 길이의 배열을 쉽게 만들 수 있는 구조
const createZeroArray = (len, value) => {
  return new Array(len).fill(value);
};

  • 값을 할당하는 객체 생성법
const objTest = (list, target) => {
  const TOTAL_NUM = target.length;

  let obj = new Object();

  list.forEach((value, index) => {
    obj[list[index]] = 0;
  });

  for (let i = 0; i < TOTAL_NUM; i++) {
    obj[target[i]]++;
  }

  console.log(obj); // { '사과': 1, '딸기': 0, '수박': 0, '키위': 1 }
};

objTest(["사과", "딸기", "수박", "키위"], ["사과", "키위"]);

  • 최종 ansArray에 맞춘 배열(id_list)에 대해서 forEach()로 모든 객체 관리방법
  const reportSet = new Set(report);
  const reportedCount = {}; //{"id": Number(count)}
  const reportedBy = {}; //{"id":[]}
  const mailCount = {}; //{"id":Number(count)}

  id_list.forEach((element) => {
    reportedCount[element] = 0;
    mailCount[element] = 0;
    reportedBy[element] = [];
  });

  • 객체의 키 가져오기
  1. Object.keys() 메소드
  2. Object.entries(obj) 메소드
  3. for ... in 루프
profile
FE developer

0개의 댓글