Algorithms

Plus Minus

seoca 2020. 7. 29. 01:33

 

 

Question

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 6 places after the decimal.

주어진 Array안에서 negative value, positive value 그리고 0 의 수가 array크기에 얼마나 비례하는지 소수점 6자리까지 프린트하는 문제. 

 

Example output

0.400000

0.400000

0.200000

 

 

 

 

Solution

let arr = [1, 1, 0, -1, -1];

function diagonalDifference(arr) {
    let zero = 0, pos = 0, neg = 0;
    let leng = arr.length;

    arr.forEach(i => {
        if (i === 0)
            zero++;
        if (i > 0)
            pos++;
        if (i < 0)
            neg++;
    })

console.log((pos / leng).toFixed(6))
console.log((neg / leng).toFixed(6))
console.log((zero / leng).toFixed(6))

}

 

 

Output

0.400000
0.400000
0.200000

 

 

 

 

toFixed() 를 사용해서 소수점의 자리 수를 명시한다. 

 

for loop를 이용했을 때 forEach와는 다른 결과값이 나왔는데 자동으로 array의 element를 차례로 call하는 forEach와는 다르게

arr[i]라고 확실히 명시해주지 않은 human error였음.

 for( let i = 0; i < leng; i++) {
        if (arr[i] === 0)
            zero++;
        if (arr[i] > 0)
            plus++;
        if (arr[i] < 0)
            minus++;
 }

 

 

 

 

Reference

https://www.hackerrank.com/challenges/plus-minus/problem

 

Plus Minus | HackerRank

Calculate the fraction of positive, negative and zero values in an array.

www.hackerrank.com