I wrote this solution for this practice in PHP but it's not work for all case:
Given an array of bird sightings where every element represents a bird type id, determine the id of the most frequently sighted type. If more than 1 type has been spotted that maximum amount, return the smallest of their ids.
arr=[1,1,2,2,3]
Example
There are two each of types 1 and 2 , and one sighting of type .3 Pick the lower of the two types seen twice: type 1.
Function Description
Complete the migratoryBirds function in the editor below.
migratoryBirds has the following parameter(s):
int arr[n]: the types of birds sighted Returns
int: the lowest type id of the most frequently sighted birds Input Format
The first line contains an integer,n , the size of arr . The second line describes arr as n space-separated integers, each a type number of the bird sighted.
Constraints 5 < n < 2 X 10 2
It is guaranteed that each type is 1,2 ,3 ,4 , or 5 .
Sample Input 0
6
1 4 4 4 5 3
Sample Output 0
4
this is my code
function migratoryBirds($arr) {
// Write your code here
$length=count($arr);
$a1=0;$a2=0;$a3=0;$a4=0;$a5=0;
for($i=0; $i < $length; $i ){
if($arr[$i]==1){
$a1 ;
}
if($arr[$i]==2){
$a2 ;
}
if($arr[$i]==3){
$a3 ;
}
if($arr[$i]==4){
$a4 ;
}
if($arr[$i]==5){
$a5 ;
}
}
if($a1>=$a2 && $a1>=$a3 && $a1>=$a4 && $a1>=$a5){
$result=1;
}
if($a2>=$a1 && $a2>=$a3 && $a2>=$a4 && $a2>=$a5){
$result=2;
}
if($a3>=$a2 && $a3>=$a1 && $a3>=$a4 && $a3>=$a5){
$result=3;
}
if($a4>=$a2 && $a4>=$a3 && $a4>=$a1 && $a4>=$a5){
$result=4;
}
if($a5>=$a2 && $a5>=$a3 && $a5>=$a4 && $a5>=$a1){
$result=5;
}
return $result;
}
How can I solve it?
CodePudding user response:
write your condition like this
if($a1>=$a2 && $a1>=$a3 && $a1>=$a4 && $a1>=$a5){
$result=1;
}
else if($a2>=$a1 && $a2>=$a3 && $a2>=$a4 && $a2>=$a5){
$result=2;
}
else if($a3>=$a2 && $a3>=$a1 && $a3>=$a4 && $a3>=$a5){
$result=3;
}
else if($a4>=$a2 && $a4>=$a3 && $a4>=$a1 && $a4>=$a5){
$result=4;
}
else if($a5>=$a2 && $a5>=$a3 && $a5>=$a4 && $a5>=$a1){
$result=5;
}
else{
$result=1;
}