I'm learning to program and I'm doing the hackerrank algorithm exercises. I'm in the migratory birds exercise.
Accessing the exercise requires login access. As many do not have access, I copy and paste the exercise here:
You have been asked to help study the population of birds migrating across the continent. Each type of bird you are interested in will be identified by an integer value. Each time a particular kind of bird is spotted, its id number will be added to your array of sightings. You would like to be able to find out which type of bird is most common given a list of sightings.If two or more types of birds are equally common, choose the type with the smallest ID number.
Function Description
Complete the migratoryBirds function in the editor below. It has two parameters:
Integer, denoting the number of elements in the input array. Integer Array, with array elements denoting the respective type numbers of each bird in the flock. The function must return an integer denoting the type number of the most common bird.
Raw Input Format
The first line contains an integer denoting n, the number of birds sighted and reported in the array. The second line describes air as n space-separated integers representing the type numbers of each bird sighted.
Personal,
My solution is this:
function migratoryBirds($n, $ar) {
$ret = [];
for ( $i = 0 ; $i < $n ; $i++ ){
$frequencia = 0;
for ( $k = 0 ; $k < $n ; $k++) {
if( $ar[ $i ] == $ar[ $k ] ) {
$ret[ $ar[ $i ] ] = 1 + $frequencia;
$frequencia++;
}
}
}
$arrayMaiorFrequencia = $ret[ $ar[0] ];
$menorChaveArrayMaiorFrequencia = $ar[0];
for ( $i = 0; $i < $n; $i++ ) {
if( $ret[ $ar[$i] ] == $arrayMaiorFrequencia && $ar[$i] < $menorChaveArrayMaiorFrequencia ) {
$menorChaveArrayMaiorFrequencia = $ar[$i];
} elseif($ret[ $ar[$i] ] > $arrayMaiorFrequencia) {
$arrayMaiorFrequencia = $ret[ $ar[$i] ];
$menorChaveArrayMaiorFrequencia = $ar[$i];
}
}
return $menorChaveArrayMaiorFrequencia;
}
Function inputs are defined by the exercise, that is, $ ar is an array of int and $ n is the number of array elements.
However, I wonder if you can factor this solution? Note: Although you are using php, and some functions in php would make the solution much easier and faster, I CAN NOT USE ANY FUNCTION OF PHP , just the concept of algorithms. So how do I make my solution cleaner?