[Solved] How to return the integer with the lowest value that occurs the most frequently in an array?


I tinkered with your function, and separated the statistic gathering from its analysis, to make it easy to find the most frequent, but lowest, number. The 6 and 7 both occur twice. The 7’s bracket the 6’s in the number presented, but the function returns 6.

#include <stdio.h>

int getFreq(int arg) {
    int tmp;
    int storage[10] = { 0 };
    int maxFreq = -1;
    int digit = 0;

    tmp = (arg < 0) ? -arg : arg;
    do {
        storage[tmp % 10]++;
        tmp /= 10;
    } while (tmp);

    for (tmp=9; tmp>=0; tmp--) {
        if (storage[tmp] >= maxFreq) {
            digit = tmp;
            maxFreq = storage[tmp];
        }
    }
    return digit;
}

int main(void)
{
    int val = 17266375;
    printf("Most frequent (lowest) from %d = %d\n", val, getFreq(val));
    return 0;
}

Program output:

Most frequent (lowest) from 17266375 = 6

solved How to return the integer with the lowest value that occurs the most frequently in an array?