Skip to content

Instantly share code, notes, and snippets.

@torressam333
Last active November 20, 2022 13:53
Show Gist options
  • Save torressam333/f12e5e9b9065a3c0d9b4238d4985cbf8 to your computer and use it in GitHub Desktop.
Save torressam333/f12e5e9b9065a3c0d9b4238d4985cbf8 to your computer and use it in GitHub Desktop.
HackerRank Plus Minus Solution PHP
<?php
// Complete the plusMinus function below.
function plusMinus($arr) {
//Get total index in array
$totalCount = count($arr);
//Initialize values to zero "score"
$pos = 0;
$neg = 0;
$zero = 0;
/*
Loop through the array of mixed numbers
Check each index and value match against zero
Increment pos, neg, zero based of zero comparison
*/
for($i = 0; $i < $totalCount; $i++){
if($arr[$i] > 0){
$pos++;
}elseif($arr[$i] < 0){
$neg++;
}else{
$zero++;
}
}
//Preformat numbers to decimals
$prepos = floatval($pos/$totalCount);
$preneg = floatval($neg/$totalCount);
$prezero = floatval($zero/$totalCount);
//Format decimals to 6 places using PHP's number_format function
$pos = number_format($prepos, 6, '.', '');
$neg = number_format($preneg, 6, '.', '');
$zero = number_format($prezero, 6, '.', '');
//Print each decimal on it's own line per instructions
print($pos . "\n" . $neg . "\n" . $zero);
}
@trusted12001
Copy link

Nice job!
I will learn from this, Thank you.

@Abdaljawad-Aya
Copy link

Cool

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment