简体   繁体   中英

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

I managed to write code to return which number occurs the most but when multiple numbers occur the same amount of times I need to return the one with the lowest value.

int getFreq(int arg) {

    int tmp;
    int storage[10] = { 0 };
    int maxDigit = -1;
    int maxfreq = -1;

    tmp = (arg < 0) ? -arg : arg;

    do {

        storage[tmp % 10]++;

        if (storage[tmp % 10] > maxDigit) {

            maxDigit = storage[tmp % 10];
            maxFreq = tmp % 10;

        }

        tmp /= 10;

    } while (tmp != 0);

    return maxFreq;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM