-1

How to count the number of occurences of distinct elements of a 2d array in C?

int main(){
    int counter = 0;
    int one = 0;
    int two = 0;
    int three = 0;
    int five = 0;
    int six = 0;

    char array[3][5] = {
        {'1', '3', '3', '5', '1'},
        {'2', '1', '5', '6', '2'},
        {'6', '2', '5', '5', '2'}
    };

    for(int j = 0; j < 3; j++){
        for(int i = 0; i < 5; i++){
            if(array[j][i] == array[j][i]){
                counter++;
            }
        }
    }
}

For every distinct number (represented here as a char) of the 2d array, I need to print their occurence count. For example like this:

number one is found 3 times in array

number two is found 4 times in array

...

Laurent Gabiot
  • 1,251
  • 9
  • 15
david
  • 65
  • 1
  • 6

2 Answers2

0
#include<stdio.h>
int main(){   
    int i;
    int a[6]={0}; // initialize array with zero values
    char array[3][5] = {
        {'1', '3', '3', '5', '1'},
        {'2', '1', '5', '6', '2'},
        {'6', '2', '5', '5', '2'}
    };
    for(int i = 0; i < 3; i++){        
        for(int j = 0; j < 5; j++){   
                 if(array[i][j]=='1') a[0]++;
                 if(array[i][j]=='2') a[1]++;
                 if(array[i][j]=='3') a[2]++;
                 if(array[i][j]=='4') a[3]++;
                 if(array[i][j]=='5') a[4]++;
                 if(array[i][j]=='6') a[5]++;
        }
    }
    for(i=0;i<6;i++){
        printf("the count of %d is %d\n",i+1,a[i]);
    }
}
/* output : 
the count of 1 is 3
the count of 2 is 4
the count of 3 is 2
the count of 4 is 0
the count of 5 is 4
the count of 6 is 2
*/
0

You can also consider creating a Hashmap, where the key is the char in question and the value is the count. If the key exists, increment the value and save it; otherwise create the entry with the value = 1.

Following the instructions for creating a Hashmap will get you started.

Chantell Osejo
  • 1,456
  • 15
  • 25