Bleeding edge

[프로그래머스] 신고 결과 받기 - 자바스크립트 본문

코딩테스트 공부

[프로그래머스] 신고 결과 받기 - 자바스크립트

codevil 2022. 7. 18. 20:15

https://school.programmers.co.kr/learn/courses/30/lessons/92334#

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

문제에서 캐치해야할 것은 두가지다

1. 신고를 하면 신고 받은 횟수를 저장한다.(중복은 안된다 신고는 한번 유효하다)

2. 유저가 신고를 받은 횟수가, k번을 넘어가면 정지가 되고,  신고했을 때 신고한 사람들은 신고해서 정지를 먹인 사람들의 숫자를 만드는 리스트를 만든다 

 

1. 일상생활로 예시를 들면, 내가 신고해서 정지를 먹은 자동차가 몇개일까..? 알아보는 문제같다고 생각이 들었다. 문제 풀이는 우선 1번부터 유효하게 구해야한다.

function reportList (report){
    const uniqueArr = Array.from(new Set([...report]))
    const map = new Map()
    uniqueArr.map((element)=>{
        const [from, to] = element.split(" ")
        map.set(to, [...(map.get(to)||[]), from])
    })    
    return map
}

set을 이용하여 빠르게 중복을 제거하고, hash map을 이용하여, 값을 저장한다.

2. 목록을 저장하기 위하여, 0을 대입해둔다.

    const result = Array.from({length:id_list.length}).fill(0)

1번에서 구한 값을, k이상 넘은 값들로 필터한다

    const filteredReportList = Array.from(map).filter((array)=>array[1].length>=k)

3. 2번에서 구한 값들을 이용하여, filteredReportList에 있으면 result에 있는 값들을 1씩 더하게 만든다

    for(let i=0;i<filteredReportList.length;i++){
        const [to, fromlist] = filteredReportList[i]
            for(let j=0;j<fromlist.length;j++){
                const index = id_list.indexOf(fromlist[j])
                result[index] = result[index]+1
            }
        }

 

이전에는 그렇게 어렵게 느껴졌는데, map을 사용하다 보니 스무스하게 풀리는 거 같다.

전체 풀이

function solution(id_list, report, k) {
    const result = Array.from({length:id_list.length}).fill(0)
    const map = reportList(report)
    const filteredReportList = Array.from(map).filter((array)=>array[1].length>=k)
    for(let i=0;i<filteredReportList.length;i++){
        const [to, fromlist] = filteredReportList[i]
            for(let j=0;j<fromlist.length;j++){
                const index = id_list.indexOf(fromlist[j])
                result[index] = result[index]+1
            }
        }
    return result
}
function reportList (report){
    const uniqueArr = Array.from(new Set([...report]))
    const map = new Map()
    uniqueArr.map((element)=>{
        const [from, to] = element.split(" ")
        map.set(to, [...(map.get(to)||[]), from])
    })    
    return map
}