modevalue of an array

L

Larry

Hi,

I need to calculate the modevalue (number that coocurs the most) of an
array like this:

short values[5] = {1,1,2,3,4};

can it actually be done?

thanks
 
J

John H.

I need to calculate the mode of an array
can it actually be done?

Yes it can be done.
If you post some of your efforts at doing this so far, we might be
able to help you more.
 
L

Larry

Yes it can be done.
If you post some of your efforts at doing this so far, we might be
able to help you more.

#include <iostream>
#include <map>
using namespace std;

#define length(x) (sizeof (x) / sizeof *(x))

int main()
{
int a[] = {1,2,9,5,6,4,8,1,2,1,7,9,8,9,9,9,9,9};

map<int,int> freq;

for ( size_t i = 0; i < length ( a ); i++ )
{
++freq[a];
}

map<int,int>::const_iterator it = freq.begin();

while ( it != freq.end() )
{
cout<< it->first <<": "<< it->second <<endl;
++it;
}

return 0;
}
 
R

Rolf Magnus

Larry said:
Yes it can be done.
If you post some of your efforts at doing this so far, we might be
able to help you more.

#include <iostream>
#include <map>
using namespace std;

#define length(x) (sizeof (x) / sizeof *(x))

int main()
{
int a[] = {1,2,9,5,6,4,8,1,2,1,7,9,8,9,9,9,9,9};

map<int,int> freq;

for ( size_t i = 0; i < length ( a ); i++ )
{
++freq[a];
}

map<int,int>::const_iterator it = freq.begin();

while ( it != freq.end() )
{
cout<< it->first <<": "<< it->second <<endl;
++it;
}

return 0;
}


That's a good start. Now all you need to in your second loop is remember the
pair that had the largest value for it->second you have encountered so far
(*it is of type std::pair<int, int>). After the loop, the first member of
that pair is what you were searching for.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,151
Messages
2,570,854
Members
47,394
Latest member
Olekdev

Latest Threads

Top