What\'s wrong with my code? I can only print out the first element not the most
ID: 3694940 • Letter: W
Question
What's wrong with my code? I can only print out the first element not the most frequently element, also I can't print out -1 if there is no such unique element
/**
* Returns the most frequently occuring element
* or -1 if there is no such unique element.
*/
public Integer getMode() {
/*
to do
[1] => 1
[2 2] => 2
[2 4 4] => 4
[1 2 3 4] => -1
*/
//MY CODE ADDED HERE
this.mode=new Integer(-1);
int fcount,fno;
fno=this.elements[0];
for(int i=0;i<length;i++)
{
fcount=0;
for(int j=i;j<length;j++)
{
if(fno==this.elements[j])
fcount++;
}
if(this.mode<fcount)
this.mode=this.elements[i];
}
return this.mode;
}
Explanation / Answer
Answer for Question:
Please try the below code it may solved the given problem statement..
public Integer getMode()
{
/*
to do
[1] => 1
[2 2] => 2
[2 4 4] => 4
[1 2 3 4] => -1
*/
//MY CODE ADDED HERE
this.mode = new Integer(-1);
int fcount =0, fno = 0;
int max_ount = 0;
fno = this.elements[0];
int ele =0;
for(int i=0 ;i< length;i++)
{
fcount=1;
for(int j=i+1;j<length;j++)
{
if(this.elements[i] == this.elements[j])
fcount++;
}
if(fcount > max_ount)
max_ount = fcount;
}
for(int i=0 ;i< length;i++)
{
fcount=1;
for(int j=i+1;j<length;j++)
{
if(this.elements[i] == this.elements[j])
fcount++;
}
if(fcount == max_ount)
ele = this.elements[i];
}
return ele;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.