Plus Minus

HackerRank 問題: Plus Minus

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.

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

HackerRank 問題: Plus Minus

Answer

<?php

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

function plusMinus($arr) {
    // Number Ratio
    $positive_ratio = 0;
    $negative_ratio = 0;
    $zero_ratio = 0;

    // Number Count
    $positive_count = 0;
    $negative_count = 0;
    $zero_count = 0;

    // count all type of number
    foreach($arr as $check_num) {
        if ($check_num > 0) {
            $positive_count++;
        } else if($check_num < 0){
            $negative_count++;
        } else {
            $zero_count++;
        }
    }

    // total number count
    $total_count = $positive_count + $negative_count + $zero_count;

    // Number Ratio
    $positive_ratio = round($positive_count / $total_count, 6);
    $negative_ratio = round($negative_count / $total_count, 6);
    $zero_ratio = round($zero_count / $total_count, 6);

    // Print answer with 6 places after the decimal.
    echo sprintf("%6f\n", $positive_ratio);
    echo sprintf("%6f\n", $negative_ratio);
    echo sprintf("%6f\n", $zero_ratio);
}

$n = intval(trim(fgets(STDIN)));

$arr_temp = rtrim(fgets(STDIN));

$arr = array_map('intval', preg_split('/ /', $arr_temp, -1, PREG_SPLIT_NO_EMPTY));

plusMinus($arr);

Reference