HackerRank - Plus Minus

세나정·2023년 5월 17일
0
post-thumbnail

문제

풀이

숫자들이 주어졌을 때 각 숫자가 음수, 양수, 0에 대해 각 수에 대한 발생 확률을 내보내는 것이 문제

주어지는 배열의 길이가 길지 않기 때문에 가장 간단하고도 직관적으로 풀었다.

전체코드

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', function(inputStdin) {
    inputString += inputStdin;
});

process.stdin.on('end', function() {
    inputString = inputString.split('\n');

    main();
});

function readLine() {
    return inputString[currentLine++];
}

/*
 * Complete the 'plusMinus' function below.
 *
 * The function accepts INTEGER_ARRAY arr as parameter.
 */

function plusMinus(arr) {
    // Write your code here
    let positive = arr.filter( v => v > 0).length
    let minus = arr.filter (v => v < 0).length
    let zero = arr.filter (v => v == 0).length
    
    console.log((positive/arr.length).toFixed(6))
    console.log((minus/arr.length).toFixed(6))
    console.log((zero/arr.length).toFixed(6))
}

function main() {
    const n = parseInt(readLine().trim(), 10);

    const arr = readLine().replace(/\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));

    plusMinus(arr);
}

profile
기록, 꺼내 쓸 수 있는 즐거움

0개의 댓글