Finding the mode of an array

This is a discussion on Finding the mode of an array within the C++ Programming forums, part of the General Programming Boards category; I am trying to find the mode, or the number which occurs most often, of my array. This is the ...

Finding the mode of an array

I am trying to find the mode, or the number which occurs most often, of my array. This is the scores array, which is sorted:

Code:

820
987
1000
1020
1100
1200
1450
1550
1680
2352
2400
2400
2400

So far I have gotten the program to count how many times there is a duplicate, which is 3 because 2400 occurs 3 times. But I haven't gotten the program to print out which of the numbers occurs 3 times.
Here is my incomplete code:

Your current code does not appear to find the mode, since you do not compare the current count with the current maximum frequency count.

A simple solution would be to use a std::map<int, int> to map the numbers to their frequencies. Once you have inserted the numbers, you can use std::max_element() to find the maximum frequency and from there print out both the mode and its frequency.

I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.

i dont think your algorithm for getting the number of occurrences is correct. add a few more numbers, so that the mode is somewhere in the middle and you should notice.

ive never written one, but i assume it would be a more complicated algorithm than that to find the maximum number of occurrences, and once you have that i imagine it would be straightforward to find out which one it was.

post back with your corrected code for doing the same task. (unless im wrong, of course!)

Well, you do not need std::map to find the mode. With a sorted array, counting frequencies is pretty easy, and you seem to have the right idea. What you need to do is keep track of what is the current maximum frequency and its associated number. Think along the lines of what you would do if you have to implement an algorithm to find the maximum value in an array, except now you do not just need to keep track of the value, but also its key.

I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.