c++ - 如何找到多维数组的模式?
问题描述
如果我有一个多维数组,例如a[i][j]
,找到数组元素模式的最合理的方法是什么?
解决方案
要找到矩阵的值的模式:首先,您需要将二维数组转换为一维数组;其次,对数组的值进行排序;然后,确定数组中出现频率较高(连续)的值:
#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
推荐阅读
- wordpress - 如何在 wp 中解决这个 forEach 循环问题?
- python - 如何解决 Jupyter Notebok 中的 TypeError 错误
- bash - Github 操作不会覆盖项目文件内容
- blockchain - MetaMask RPC 错误?“MetaMask - RPC 错误:内部 JSON-RPC 错误。”
- react-native - 元素类型无效:应为字符串(用于内置组件)或类/函数(用于复合组件)但得到:未定义
- linux - root 拥有的 Docker bindmount 卷基目录
- powershell - -ExpandProperty 和图形 API
- python - 为什么 Python 中 marker=3 和 marker='3' 的输出图片不同?
- apache2 - 允许使用 Apache2 遍历目录
- sql - 在 SQL Server 中使用 while 循环设置 SQL 查询中的对角线值