Last active
February 13, 2021 16:44
-
-
Save nellytadi/62b1b86ba7ebb107c252647614bbe1a5 to your computer and use it in GitHub Desktop.
This is an algorithm written in PHP for finding the most-repeated number in an array of numbers.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function inEfficientFindHighestReOccurringNumber($array){ | |
$highest_reoccuring_number = 0; | |
$prevcount = 0; | |
for ($i = 0; $i < count($array); $i++){ | |
$count = 0; | |
for ($y = 0; $y < count($array); $y++){ | |
if($array[$i] == $array[$y]){ | |
$count++; | |
} | |
} | |
if($count > $prevcount){ | |
$highest_reoccuring_number = $array[$i]; | |
$prevcount = $count; | |
} | |
} | |
return $highest_reoccuring_number; | |
} | |
function efficientFindHighestReOccurringNumber($array){ | |
$new_array= []; | |
for($i = 0;$i < count($array); $i++){ | |
if(array_key_exists($array[$i],$new_array)){ | |
$new_array[$array[$i]] = $new_array[$array[$i]]+1; | |
} | |
else{ | |
$new_array[$array[$i]] = 1; | |
} | |
} | |
$highest_value=0; | |
$highest_reoccuring_number = 0; | |
foreach ($new_array as $key => $value){ | |
if($value > $highest_value){ | |
$highest_reoccuring_number = $key; | |
$highest_value = $value; | |
} | |
} | |
return $highest_reoccuring_number; | |
} | |
function testFindHighestReOccurringNumber($array){ | |
$time_start_1 = microtime(true); | |
echo '<h1><small>Inefficient highest reoccuring number is </small>'.inEfficientFindHighestReOccurringNumber($array).'<br>'; | |
$time_end_1 = microtime(true); | |
$execution_time_1 = ($time_end_1 - $time_start_1)/60; | |
echo '<small>Total Execution Time:</small> '.number_format((float) $execution_time_1, 10) .' secs<br><br>'; | |
$time_start_2 = microtime(true); | |
echo '<small>Efficient highest reoccuring number is </small>'.efficientFindHighestReOccurringNumber($array).'<br>'; | |
$time_end_2 = microtime(true); | |
$execution_time_2 = ($time_end_2 - $time_start_2)/60; | |
echo '<small>Total Execution Time:</small> '.number_format((float) $execution_time_2, 10).' secs </h1>'; | |
} | |
$array = []; | |
for ($i=0; $i < 150; $i++) { | |
$array[$i] = rand(1,10); | |
} | |
testFindHighestReOccurringNumber($array); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment