Plus Minus PHP
2023-10-13T12:33:30 - Vicky Chhetri
Read Time:1 Minute, 3 Second
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 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);