I need to find most frequent element in matrix, and print it. If there are more than one most frequent elements, program should print the smallest of them.
How could my code of finding maximum element of 1D array be implemented in matrix (2D array)?
#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);
}
CodePudding user response:
Your algorithm does not work for the 1D matrix, but once fixed, it can be used for the 2D matrix unchanged:
#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;
}