Hello forum,
I am currently writting a code to find the most repeated number (and how many times it repeats) in an array. So far everything is working nicely in my code, but I can't figure out one thing: in case of two numbers repeating the same amout of times I need it to print out the bigger one. I would much appreciate any ideas/hints on how to do that (I couldn't find anything related in any literature I have access to). Here is my code so far so You could have a better idea of what I'm doing here.
you need some sort of data structure to store each unique value entered with the number of times it was repeated. Then you can go through the data structure and find the number[s] with the most repeats. There are many ways to implement such a data structure. Being able to sort it by the number of repeats would help.
(hint: maybe something like std::map would work...)
Edit: on a second thought, you don't need a fancy data structure. All you need to do is add another if statement before this line:
if (maxRepeat<repeat){ maxRepeat = repeat; mostrep=mas[i] ;}
If maxRepeat and repeat are equal, compare mas[i] to mostrep and store the larger value.
If in my previous code I input numbers 1, 1, 2, 2, it would print out "1 repeats 2 times". After adding an extra if statement it prints "2 repeats 2 times". So if I changed the input to 2, 2, 1, 1, it prints out "1 repeats 2 times". Basically from having the first most repeated number as the outcome, now it has the second.
hmm... I don't think you changed it the way I recommended, since the version I changed and tested seems to be working just fine. Here is my version of MostRepeated. I added comments with the changed section.
int MostRepeated ( int* mas , int n )
{
int i, j, maxRepeat=1 , mostrep, repeat=0;
for (i=0 ; i<n ; i++)
{
repeat = 0;
for (j=0; j<n; j++)
{
if (mas[i] == mas[j])
repeat++ ;
}
// Here is an additional if statement
// Special case if number of repeats is equal
if (maxRepeat == repeat)
{
// Keep the larger number
mostrep = max(mostrep, mas[i]);
}
if (maxRepeat<repeat)
{
maxRepeat = repeat;
mostrep=mas[i] ;
}
}
return mostrep;
}
you have to include <algorithm> to use the C++ max function I used.