小编典典

如何找到排序数组的模式?

algorithm

我需要编写一个函数来查找数组的模式。我不擅长提出算法,但我希望其他人知道如何做到这一点。

我知道数组的大小和每个元素中的值,并且我将数组从最小到最大排序。

数组将被传递给mode函数,例如

模式= findMode(arrayPointer,sizePointer);

更新:

阅读评论后,我尝试了这个

int findMode(int *arrPTR, const int *sizePTR)
{
    int most_found_element = arrPTR[0];
    int most_found_element_count = 0;
    int current_element = arrPTR[0];
    int current_element_count = 0;
    int count;
    for (count = 0; count < *sizePTR; count++)
    {
        if(count == arrPTR[count])
             current_element_count++;
        else if(current_element_count > most_found_element)
        {
            most_found_element = current_element;
            most_found_element_count = current_element_count;
        }
        current_element = count;
        current_element_count=1;
    }

    return most_found_element;
}

尽管有人可以整理我的算法,但我仍然无法掌握该算法。我从没使用过向量,所以我不太了解其他示例。


阅读 227

收藏
2020-07-28

共1个答案

小编典典

set most_found_element to the first element in the array
set most_found_element_count to zero
set current_element to the first element of the array
set current_element_count to zero
for each element e in the array
    if e is the same as the current_element
        increase current_element_count by one
    else
        if current_element_count is greater than most_found_element_count
            set most_found_element to the current_element
            set most_found_element_count to current_element_count
        set current_element to e
        set current_element_count to one
if current_element_count is greater than most_found_element_count
    set most_found_element to the current_element
    set most_found_element_count to current_element_count
print most_found_element and most_found_element_count

我以为名字会解释这一点,但是我们开始:

When we start, no element has been found the most times
  so the "high-score" count is zero.
Also, the "current" value is the first, but we haven't looked at it yet 
  so we've seen it zero times so far
Then we go through each element one by one
  if it's the same as "current" value, 
     then add this to the number of times we've seen the current value.
  if we've reached the next value, we've counted all of the "current" value.
     if there was more of the current value than the "high-score"
        then the "high-score" is now the current value
     and since we reached a new value
        the new current value is the value we just reached
Now that we've seen all of the elements, we have to check the last one
  if there was more of the current value than the "high-score"
    then the "high-score" is now the current value
Now the "high-score" holds the one that was in the array the most times!

另请注意:我的原始算法/代码存在错误,循环结束后我们必须对“当前”进行额外检查,因为它永远找不到“最后一个之后”。

2020-07-28