jcadima
2/3/2017 - 2:19 AM

Count of positives / sum of negatives

Count of positives / sum of negatives

<?php
/*
Given an array of integers.
Return an array, where the first element is the count of positives numbers and the second element is sum of negative numbers.
If the input array is empty or null, return an empty array
*/

function countPositivesSumNegatives($input) {
    if ( empty($input) ) return [] ;
    // $neg =  array_sum( array_filter($input, "negative") ) ; 
    $neg = array_sum( array_filter($input, function($n) { 
      return $n < 0 ;
    }) ) ;
    //$pos =  count(array_filter($input, "positive")) ; 
    $pos = count( array_filter($input, function($n) { 
      return $n > 0 ;
    }) ) ;
    return [$pos,$neg];
}


/*
function negative($num) {
	return $num < 0 ;
}

function positive($num) {
	return $num > 0 ;
}
*/


class CountPositivesSumNegativesTestCases extends TestCase
{
    public function testExample() {
      $this->assertSame([10, -65], countPositivesSumNegatives([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15]));
      $this->assertSame([8, -50], countPositivesSumNegatives([0, 2, 3, 0, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14]));
    }
}