If I have a multidimensional array, like a[i][j]
, what is the most plausible way to find the mode of elements of the array?
Asked
Active
Viewed 674 times
1
-
what do you mean by "mode" -> modulo? or Type? and C or C++? – Ol Sen Jul 25 '20 at 04:16
-
Convert to a 1D array. Sort. Count. – user3386109 Jul 25 '20 at 04:18
-
Isn't a multidimensional array a collection of one-dimensional arrays? Find mode for the individual arrays and store them in a vector. The highest value in this vector can be taken as the mode. – Jul 25 '20 at 04:24
1 Answers
2
To find the mode of the values of the matrix: first, you need to convert the 2D array to a 1D array; second, sort the values of the array; and then, identify the value that appears with the higher frequency (consecutively) in the array:
#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;
}
This returns:
Mode 4

Gorka
- 1,971
- 1
- 13
- 28
-
Will this work for rectangular matrices too? `// 1. Convert 2D to 1D for (i = 0; i < 3 * 3; i++) { v[i] = a[i % 3][i / 3]; }` – NoobCoder Jul 25 '20 at 09:16
-
@NoobCoder The more general solution that doesn't require any math is `k = 0; for(i=0;i
– user3386109 Jul 25 '20 at 15:25 -
-
@user3386109 `for (i = 0; i < rows * cols; i++) v[i] = a[i % rows][i / rows];` is also valid for general cases, but probably your approach is better understood by a beginner. – Gorka Jul 25 '20 at 15:54
-
If you do not need the matrix `a` later, you could skip the 2D to 1D conversion and replace `v` with `a` in the code. This can be done because multi-dimensional arrays are stored contiguously in memory, see [this](https://stackoverflow.com/a/2565048/13473361) discussion. In this case, basically, finding the mode in a multidimensional array is the same as finding the mode in a simple array. – Gorka Jul 25 '20 at 17:17