Mode Program

优质
小牛编辑
132浏览
2023-12-01

在统计数学中,模式是出现最多时间的值。

For Example - 假设一组值3,5,2,7,3。此值集的模式为3,因为它看起来比任何其他数字更多。

算法 (Algorithm)

我们可以推导出一种算法来寻找模式,如下所示 -

START
   Step 1 → Take an integer set A of n values
   Step 2 → Count the occurence of each integer value in A
   Step 3 → Display the value with highest occurence
STOP

伪代码 (Pseudocode)

我们现在可以使用上述算法导出伪代码,如下所示 -

procedure mode()
   Array A
   FOR EACH value i in A DO
      Set Count to 0
      FOR j FROM 0 to i DO
         IF A[i] = A[j]
            Increment Count
         END IF
      END FOR
      IF Count > MaxCount
         MaxCount =  Count
         Value    =  A[i]
      END IF
   END FOR
   DISPLAY Value as Mode
end procedure

实现 (Implementation)

该算法的实现如下 -

#include <stdio.h>
int mode(int a[],int n) {
   int maxValue = 0, maxCount = 0, i, j;
   for (i = 0; i < n; ++i) {
      int count = 0;
      for (j = 0; j < n; ++j) {
         if (a[j] == a[i])
         ++count;
      }
      if (count > maxCount) {
         maxCount = count;
         maxValue = a[i];
      }
   }
   return maxValue;
}
int main() {
   int n = 5;
   int a[] = {0,6,7,2,7};
   printf("Mode = %d ", mode(a,n));
   return 0;
}

输出 (Output)

该方案的产出应该是 -

Mode = 7