Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

count occurrence of element in array

Tags:

java

arrays

char [] array = {a,a,a,b,b,c,c,c,a,d};

I want to count every same element in that array so I can sort it from highest frequency to the lowest one. I want the output become like this:

4 (for a)
2 (for b)
3 (for c)
1 (for d)

I have try this

public static void CountbyChar(String s){
    int [] arr = new int [s.length()];
    char [] c =s.toCharArray();
    for (int i=0;i<c.length;i++){
        arr[i]=1;
        for (int j=i+1;j<c.length;j++){
            if(c[i]==c[j]){
                arr[i]++;
            }
        }
    }
    for (int x:arr){
        System.out.println(x);
    }
}

But I got:

4
3
2
2
1
2
1
1

Where is my fault?

like image 871
husnul Avatar asked Jan 14 '23 18:01

husnul


1 Answers

The problem is that you are creating a new counter for each character in the string, rather than creating one for each possible letter. Essentially, your program counts how many times a character occurs in a string in positions after the current character.

Fixing this issue should be relatively easy: make counters for each letter of the alphabet, and increment them when you see the corresponding letter. Assuming that you do it case-sensitively, you can do it like this:

public static void CountbyChar(String s){
    int [] arr = new int [256];
    for (char c : s.toCharArray()){
        if (c < 256) {
            arr[c]++;
        }
    }
    for (int i = 0 ; i != 256 ; i++) {
        if (arr[i] != 0) {
            System.out.print((char)i);
            System.out.print(" : ");
            System.out.println(arr[i]);
        }
    }
}
like image 174
Sergey Kalinichenko Avatar answered Jan 21 '23 11:01

Sergey Kalinichenko