0

我有这个函数来打印直方图,我想也可以使用这个函数计算模式,我知道要找到模式你需要比较每个分数的出现次数,但我不知道如何将它实现到代码。反正有没有实现这个功能来查找模式?

这是我的功能

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;
}
4

2 回答 2

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包含该项目的 s 的指针。

于 2013-04-16T16:16:35.780 回答
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;
}
于 2013-04-16T16:19:12.197 回答