0 0
Read Time:1 Minute, 3 Second

Given an array of integers, calculate the ratios of its elements that are positivenegative, 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.

Example

There are  elements, two positive, two negative and one zero. Their ratios are ,  and . Results are printed as:

0.400000
0.400000
0.200000
<?php

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

function plusMinus($arr) {
    
    $n = count($arr);
    $positive_count = 0;
    $negative_count = 0;
    $zero_count = 0;

    foreach ($arr as $number) {
        if ($number > 0) {
            $positive_count++;
        } elseif ($number < 0) {
            $negative_count++;
        } else {
            $zero_count++;
        }
    }
 
    $positive_ratio = $positive_count / $n;
    $negative_ratio = $negative_count / $n;
    $zero_ratio = $zero_count / $n;

    // Print the ratios with 6 decimal places
    printf("%.6f\n", $positive_ratio);
    printf("%.6f\n", $negative_ratio);
    printf("%.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);
Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

About Author

Average Rating

5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%

Leave a Reply

Your email address will not be published. Required fields are marked *