Skip to content

Commit

Permalink
mode (dominant) from numbers
Browse files Browse the repository at this point in the history
  • Loading branch information
akondas committed May 8, 2016
1 parent ed1e07e commit a761d0e
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 5 deletions.
39 changes: 35 additions & 4 deletions src/Phpml/Math/Statistic/Mean.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,13 @@ class Mean
* @param array $numbers
*
* @return float
*
* @throws InvalidArgumentException
*/
public static function arithmetic(array $numbers)
{
self::checkArrayLength($numbers);

return array_sum($numbers) / count($numbers);
}

Expand All @@ -26,11 +30,10 @@ public static function arithmetic(array $numbers)
* @throws InvalidArgumentException
*/
public static function median(array $numbers) {
$count = count($numbers);
if (0 == $count) {
throw InvalidArgumentException::arrayCantBeEmpty();
}

self::checkArrayLength($numbers);

$count = count($numbers);
$middleIndex = floor($count / 2);
sort($numbers, SORT_NUMERIC);
$median = $numbers[$middleIndex];
Expand All @@ -42,4 +45,32 @@ public static function median(array $numbers) {
return $median;
}

/**
* @param array $numbers
*
* @return mixed
*
* @throws InvalidArgumentException
*/
public static function mode(array $numbers)
{
self::checkArrayLength($numbers);

$values = array_count_values($numbers);

return array_search(max($values), $values);
}

/**
* @param array $array
*
* @throws InvalidArgumentException
*/
private static function checkArrayLength(array $array)
{
if (0 == count($array)) {
throw InvalidArgumentException::arrayCantBeEmpty();
}
}

}
26 changes: 25 additions & 1 deletion tests/Phpml/Math/Statistic/MeanTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,15 @@

class MeanTest extends \PHPUnit_Framework_TestCase
{

/**
* @expectedException \Phpml\Exception\InvalidArgumentException
*/
public function testArithmeticThrowExceptionOnEmptyArray()
{
Mean::arithmetic([]);
}

public function testArithmeticMean()
{
$delta = 0.01;
Expand All @@ -19,7 +28,7 @@ public function testArithmeticMean()
/**
* @expectedException \Phpml\Exception\InvalidArgumentException
*/
public function testThrowExceptionOnEmptyArrayMedian()
public function testMedianThrowExceptionOnEmptyArray()
{
Mean::median([]);
}
Expand All @@ -38,4 +47,19 @@ public function testMedianOnEvenLengthArray()
$this->assertEquals(3.5, Mean::median($numbers));
}

/**
* @expectedException \Phpml\Exception\InvalidArgumentException
*/
public function testModeThrowExceptionOnEmptyArray()
{
Mean::mode([]);
}

public function testModeOnArray()
{
$numbers = [5, 2, 6, 1, 3, 4, 6, 6, 5];

$this->assertEquals(6, Mean::mode($numbers));
}

}

0 comments on commit a761d0e

Please sign in to comment.