Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Most frequent element in matrix

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);
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading