diff --git a/src/Average.php b/src/Average.php index 17b5229..6724d8e 100644 --- a/src/Average.php +++ b/src/Average.php @@ -9,7 +9,7 @@ class Average * @param array $numbers Array of numbers * @return float Mean average */ - public function mean(array $numbers) + public function mean(array $numbers): float { return array_sum($numbers) / count($numbers); } @@ -19,16 +19,25 @@ public function mean(array $numbers) * @param array $numbers Array of numbers * @return float Median average */ - public function median(array $numbers) + public function median(array $numbers): float { sort($numbers); $size = count($numbers); if ($size % 2) { return $numbers[$size / 2]; - } else { - return $this->mean( + } + return $this->mean( array_slice($numbers, ($size / 2) - 1, 2) ); - } + } + /** + * Calculate the median average + * @param array $numbers Array of numbers + * @return float Median average + */ + public function mode(array $numbers): int + { + $values = array_count_values($numbers); + return array_search(max($values), $values); } } diff --git a/tests/AverageTest.php b/tests/AverageTest.php index 044bcc5..b877832 100644 --- a/tests/AverageTest.php +++ b/tests/AverageTest.php @@ -18,9 +18,21 @@ public function testCalculationOfMean() $this->assertEquals(4.4, $this->Average->mean($numbers)); } - public function testCalculationOfMedian() + public function testCalculationOfMedianForOddNumberOfValues() { $numbers = [3, 7, 6, 1, 5]; $this->assertEquals(5, $this->Average->median($numbers)); } + + public function testCalculationOfMedianForEvenNumberOfValues() + { + $numbers = [3, 7, 6, 5]; + $this->assertEquals(5.5, $this->Average->median($numbers)); + } + + public function testCalculationOfMode() + { + $numbers = [1, 3, 3, 3, 4, 4, 6, 6, 9]; + $this->assertEquals(3, $this->Average->mode($numbers)); + } }