Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhance mode() Function to Return Multiple Modes #117

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 8 additions & 7 deletions Maths/Mode.php
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
<?php
/**
* This function calculates
* The mode value of
* the mode value(s) of
* numbers provided
*
*
* @param decimal $numbers A variable sized number input
* @return decimal $mode Mode of provided numbers
* @return array $modes Array of mode(s) of provided numbers
* @throws \Exception
*/
function mode(...$numbers)
{
if (empty($numbers)) {
throw new \Exception('Please pass values to find mean value');
throw new \Exception('Please pass values to find the mode');
}

$values = array_count_values($numbers);
$mode = array_search(max($values), $values);
$values = array_count_values($numbers);
$maxCount = max($values);

return $mode;
return array_keys($values, $maxCount, true);
}
8 changes: 5 additions & 3 deletions tests/Maths/MathsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -141,8 +141,10 @@ public function testMedian()

public function testMode()
{
mode(4,2,7,9,2,9,0,4,2);
mode(21,72,40,21,0,99,21,99,0,40);
mode(3,3,3,3);
$this->assertEquals([3], mode(1, 2, 3, 3, 4, 5));
$this->assertEquals([5, 6], mode(5, 5, 6, 6, 7));
$this->assertEquals([1, 2, 3, 4, 5], mode(1, 2, 3, 4, 5));
$this->assertEquals([2, 3, 4], mode(2, 2, 3, 3, 4, 4));
}

}
Loading