본문 바로가기

Algorithm

[Hackerrank/js] Plus Minus

연이은 서류탈락의 고배를 마시고 정신 못 차리는 요즘

여차저차 서류를 통과(?) 하고 코테 링크를 받았는데

Hackerrank라는 곳에서 4시간동안 본다고 (...)

 

큰 틀은 프로그래머스랑 비슷하겠으나 

아무래도 익숙하지 않은 사이트에 영어로 문제가 나오니 

적응도 해 볼겸 가입을 했다. 

 

가입 할 때 코테까지 얼마나 남았냐고 물어보는데 

제일 가까운데 1week 라서 그거 선택했더니 

이런식으로 7일짜리 플랜을 짜서 준다 

 

아무튼 그래서 문제 1번 plus minus 바로 풀어봤는데 생각보다 어렵지 않았다

 

문제 : 

Given an array of integers, calculate the ratios of its elements that are positive, negative, and zero.

Print the decimal value of each fraction on a new line with  places after the decimal.

Note: This challenge introduces precision problems. The test cases are scaled to six decimal places, though answers with absolute error of up to  are acceptable.

function plusMinus(n, arr) {
    let plusMinusCnt = new Map([
        ["positive_m", 0],
        ["zero_m", 0],
        ["negative_m", 0]
    ]); 
    
    for (const num of arr) {
        if (num >= -100 && num <= 100) {
            if (num > 0) {
                plusMinusCnt.set('positive_m', plusMinusCnt.get('positive_m') + 1 || 1)
            } else if (num === 0 ){
                plusMinusCnt.set('zero_m', plusMinusCnt.get('zero_m') + 1 || 1)
            } else {
                plusMinusCnt.set('negative_m', plusMinusCnt.get('negative_m') + 1 || 1)
            } 
        }
   }

   const plus = (plusMinusCnt.get('positive_m') / n ).toFixed(6)
   const zero = (plusMinusCnt.get('zero_m') / n ).toFixed(6)
   const negative = (plusMinusCnt.get('negative_m') / n ).toFixed(6)

   console.log(plus);
   console.log(negative);
   console.log(zero);
}

지난번에 Map() 배운거 나름 잘 써먹는 중인데

이번 문제에서 내가 간과한 점은 만약 배열에 해당 조건을 만족하는 값이 전혀 없을 때 어떻게 할 것인지

 

 

문제 안에 친절하게 다 나와있었지만 앞에 if조건을 먼저 거는걸 까먹어서 몇개의 테스트케이스를 통과하지 못했다...