CodingSpace

[HackerRank/Algorithms] Warmup - Plus Minus 본문

HackerRank/Algorithm

[HackerRank/Algorithms] Warmup - Plus Minus

개발자_조이킴 2022. 8. 21. 23:59

Problem. Warmup - Plus Minus


Link.

https://www.hackerrank.com/challenges/plus-minus/problem?isFullScreen=true

 

Diagonal Difference | HackerRank

Calculate the absolute difference of sums across the two diagonals of a square matrix.

www.hackerrank.com


Description.

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.

 


Key Point. 


My Answer. 

'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 len = arr.length;
    let positive = 0;
    let negative = 0;
    let zero = 0
    
    for(let i = 0; i < len; i++) {
        if(arr[i] > 0)
            positive = positive + 1;
        else if(arr[i] < 0)
            negative = negative + 1;
        else if(arr[i] === 0)
            zero = zero + 1;
    }
    
    positive = (positive / len).toFixed(6);
    negative = (negative / len).toFixed(6);
    zero = (zero / len).toFixed(6);
    
    console.log(positive);
    console.log(negative);
    console.log(zero);
}

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

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

    plusMinus(arr);
}

References. 

 

Comments