矩阵中出现频率最高的元素
Most frequent element in matrix
我需要找到矩阵中出现频率最高的元素,并打印出来。如果有不止一个最频繁出现的元素,程序应该打印其中最小的一个。
如何在矩阵(二维数组)中实现查找一维数组最大元素的代码?
#include <stdio.h>
void main() {
int i, j, k = 0, m = 3, n = 4, vel = 8, count = 0, maxCount = 0;
double mat[3][4], maxElement, arr[100] = { 1.3, 4.2, 1.3, 5, 4.2, 6.8, 3.7 };
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%lf", &mat[i][j]);
for (i = 0; i < vel; i++) {
for (j = i + 1; j < vel; j++) {
if (arr[i] == arr[j]) {
count++;
if (count > maxCount)
maxElement = arr[j];
}
}
}
printf("Most frequent is: %g", maxElement);
}
你的算法不适用于一维矩阵,但一旦固定,它可以用于二维矩阵不变:
#include <stdio.h>
double find_most_frequent(const double *arr, size_t vel) {
size_t i, j, maxcount = 0, mostfreq = 0;
for (i = 0; i < vel; i++) {
size_t count = 1;
for (j = i + 1; j < vel; j++) {
if (arr[i] == arr[j]) {
count++;
}
if (maxcount < count || (maxcount == count && arr[mostfreq] > arr[i])) {
maxcount = count;
mostfreq = i;
}
}
return arr[mostfreq];
}
#define ROWS 3
#define COLS 4
int main() {
double mat[ROWS][COLS];
double arr[] = { 1.3, 4.2, 1.3, 5, 4.2, 6.8, 3.7 };
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
if (scanf("%lf", &mat[i][j]) != 1)
return 1;
}
}
printf("Most frequent in array is: %g\n", find_most_frequent(arr, sizeof(arr) / sizeof(arr[0]));
printf("Most frequent in matrix is: %g\n", find_most_frequent(&mat[0][0], sizeof(mat) / sizeof(mat[0][0]));
return 0;
}
我需要找到矩阵中出现频率最高的元素,并打印出来。如果有不止一个最频繁出现的元素,程序应该打印其中最小的一个。
如何在矩阵(二维数组)中实现查找一维数组最大元素的代码?
#include <stdio.h>
void main() {
int i, j, k = 0, m = 3, n = 4, vel = 8, count = 0, maxCount = 0;
double mat[3][4], maxElement, arr[100] = { 1.3, 4.2, 1.3, 5, 4.2, 6.8, 3.7 };
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%lf", &mat[i][j]);
for (i = 0; i < vel; i++) {
for (j = i + 1; j < vel; j++) {
if (arr[i] == arr[j]) {
count++;
if (count > maxCount)
maxElement = arr[j];
}
}
}
printf("Most frequent is: %g", maxElement);
}
你的算法不适用于一维矩阵,但一旦固定,它可以用于二维矩阵不变:
#include <stdio.h>
double find_most_frequent(const double *arr, size_t vel) {
size_t i, j, maxcount = 0, mostfreq = 0;
for (i = 0; i < vel; i++) {
size_t count = 1;
for (j = i + 1; j < vel; j++) {
if (arr[i] == arr[j]) {
count++;
}
if (maxcount < count || (maxcount == count && arr[mostfreq] > arr[i])) {
maxcount = count;
mostfreq = i;
}
}
return arr[mostfreq];
}
#define ROWS 3
#define COLS 4
int main() {
double mat[ROWS][COLS];
double arr[] = { 1.3, 4.2, 1.3, 5, 4.2, 6.8, 3.7 };
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
if (scanf("%lf", &mat[i][j]) != 1)
return 1;
}
}
printf("Most frequent in array is: %g\n", find_most_frequent(arr, sizeof(arr) / sizeof(arr[0]));
printf("Most frequent in matrix is: %g\n", find_most_frequent(&mat[0][0], sizeof(mat) / sizeof(mat[0][0]));
return 0;
}