从直方图中寻找模式

时间:2013-04-16 15:30:17

标签: c structure histogram mode

我有这个函数来打印直方图,我想也要使用这个函数计算模式,我明白要找到模式你需要比较每个得分的出现次数,但我无法弄清楚如何实现这进入代码。反正有没有实现这个功能来找到模式?

这是我的功能

int calMode(RECORD list[], int count){
int tempMode = 0;
int i, k;
int current = 0;

while (current < count)
{
    printf("%d:", list[current].score);
    for(k=0; (i=current + k) < count ; ++k)
   {
        if(list[current].score == list[i].score)
            printf("*");
        else
            break;
    }
      if(k > tempMode)
        tempMode = k;
    printf("\n");
    current = current + k;
}
printf("%d\n", tempMode);
   return tempMode;
}

2 个答案:

答案 0 :(得分:0)

嗯,你需要一个不同的算法。您需要找到项目的最大.score成员,并存储相应的索引。这样的事情可能会这样:

int max = list[0].score;
RECORD *max_item[count] = { &list[0] };
size_t index = 1;
while (count-- > 1) {
    // We're looking for any items that are greater than or equal to the
    // current max, so when we find items that are less, we jump back to
    // the condition evaluation using "continue".
    if (list[count].score < max) { continue; }

    // When we find a value that's greater than the current maximum, we
    // need to discard all previously stored "maximum" items and update
    // our current maximum.
    if (list[count].score > max) {
        index = 0;
        max = list[count].score;
    }

    // At this point, the current item can't be less than the current max.
    // This is because of the "continue;" earlier. Add this item to our
    // list of "maximum" items.
    max_item[index++] = &list[count];
}

max现在在您的直方图中存储最高分数,index存储包含该最高分数的项目数,max_item存储包含该最高分数的RECORD指针项目

答案 1 :(得分:0)

int calMode(RECORD list[], int count){
    int tempMode;
    int i, k;
    int current = 0;
    int max = -1;
    int update = 0;

    while (current < count){
        printf("%d:", list[current].score);
        for(k=0; (i=current + k) < count ; ++k){
            if(list[current].score == list[i].score)
                printf("*");
            else
                break;
        }
        printf("\n");

        if(k>max){
            max = k;
            tempMode = list[current].score;
            update  = 1;
        } else if(k == max){
            update = 0;
        }

        current = current + k;
    }
    if(update == 0)
        tempMode = -1;//indeterminable
    return tempMode;
}