gpt4 book ai didi

c++ - 如何找到多维数组的模式?

转载 作者:行者123 更新时间:2023-12-02 10:00:00 25 4
gpt4 key购买 nike

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

最佳答案

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

#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

关于c++ - 如何找到多维数组的模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63084151/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com