首页 > 解决方案 > 如何找到多维数组的模式?

问题描述

如果我有一个多维数组,例如a[i][j],找到数组元素模式的最合理的方法是什么?

标签: c++arrayscmultidimensional-arrayfrequency

解决方案


要找到矩阵的值的模式:首先,您需要将二维数组转换为一维数组;其次,对数组的值进行排序;然后,确定数组中出现频率较高(连续)的值:

#include <stdio.h>
#include <stdlib.h>

static int sort(const void* xx, const void* yy)
{
  int x = *((int*)xx);
  int y = *((int*)yy);

  if (x < y)
    return -1;
  if (x > y)
    return +1;

  return 0;
}

int main(void)
{

  int i, freq, max_freq, mode;

  int a[4][3] = { { 1, 4, 5 }, { 3, 2, 4 }, { 5, 5, 2 }, { 4, 4, 2 } };
  int v[4 * 3];

  // 1. Convert 2D to 1D
  for (i = 0; i < 4 * 3; i++) {
    v[i] = a[i % 4][i / 4];
  }

  // 2. Sort the array
  qsort(v, 4 * 3, sizeof(int), sort);

  for (i = 1, freq = 1, max_freq = 0; i < 4 * 3; i++) {

    if (v[i - 1] == v[i]) {

      // 3. If consecutive values are equal,
      //    increment by 1 the frequency of the value
      freq++;

      if (freq > max_freq) {

        // 3. If the value has a higher frequency than
        //    the saved one, save the current value.
        max_freq = freq;
        mode = v[i];
      }
    } else {
      // 3. Since it is a new value, restart the frequency count.
      freq = 1;
    }
 }

  printf("Mode %d\n", mode);

  return 0;
}

这将返回:

Mode 4

推荐阅读