Tuesday, July 14, 2009

Finding the mode of an array C++?

I have a vector that records the number of occurances based on user input, but I cannot figure out how to find the mode of that data here is my code listing the occurances and what I have so far for the mode:





cout%26lt;%26lt;"Roll"%26lt;%26lt;" "%26lt;%26lt;"Count"%26lt;%26lt;endl;


for(num = 1; num %26lt;=50;num++){


cout%26lt;%26lt;num%26lt;%26lt;" "%26lt;%26lt;Count[num]%26lt;%26lt;endl;


}





void Mode(CountType %26amp;Count, int %26amp;num, int %26amp;i)


{





int pos_mode;


int mode;


for(pos_mode = 1; pos_mode %26lt;=50;pos_mode++){


if (Count[pos_mode] %26gt; Count[num]){


mode = pos_mode;





}

















}


cout%26lt;%26lt;"The mode is: "%26lt;%26lt;mode;


}

Finding the mode of an array C++?
Try this:





I'm assuming CountType to be integer.





void Mode(CountType* Count)


{


//first sort the count array yourself





int n = 0;


int count = 0;


int max = 0;


int mode = 0;





for(int i = 0;i%26lt;50;i++)


{





if(n != Count[i])


{


n = Count[i];


count = 1;


}


else


{


count++;


}





if(count %26gt; max)


{


max = count;


mode = n;


}





}





cout%26lt;%26lt;"Mode: "%26lt;%26lt;mode%26lt;%26lt;endl;


}








Don't forget to sort the array first, it is important.


No comments:

Post a Comment