So I'm trying to make a basic program to learn the basics of C++, I'm generating 100 random numbers from 0 to 100 and storing them in a vector, I am then displaying the sum, mean, median, mode, high and low of the vector. I have everything else done except the mode which is where I get stuck. Here is the code I have so far.
int modeFunction()
{
numMode = 0;
count = 0;
for (int n = 0; n < 100; n++)
{
for (int y = 0; y < 100; y++)
{
if (numVector.at(y) == numVector.at(n))
{
numMode = numVector.at(y);
count++;
}
}
}
return numMode;
}
After that I get stuck because in my mind that should work but it doesn't. It just out puts the last number, usually 100. Any help would be much appreciated.
since all the values are between 0 and 100, you can find the mode efficiently with a histogram:
Since mode is the number that occurs most frequent you shouldn't change
numMode
unless the new number's count is greater thannumMode
's count.EDIT: To clarify, you need to keep a separate count for the current element and the current number that you think is the mode. Ideally, setting
newMode
to the first element is a good approach.In addition, mode isn't necessary unique (i.e. "1 1 2 2"). You may want to keep that in mind if you care about that.
bmcnett's approach works great if number of elements are small enough. If you have large number of elements but the all element value are with in a small range using map/hashmap works well. Something like
Alternative solutions. Note: untested.
Your algorithm is wrong - it outputs the last number in the array because that's all it can ever do. Every time the number at index
y
matches the number at indexn
you overwrite the results for the previousn
. Since you're using the same loop conditions,y
andn
are always the same at at least one point in the nested loop for each possiblen
value - and you'll always end up withnumMode
beingnumVector.at(99)
.You need to change your algorithm to save the count for each
n
index along the way (or at least whichn
index ended up with the greatestcount
), so that you can know at the end of then
loop which entry occured the most times.