ananymous59
ananymous59

Reputation: 200

Average of occurrences of a character in a string array

I want to compute the average of occurrences of a character in a string eg if i pass an array ["hie","raisin","critical"],and i pass a target i then my method should return 1.6. How do i do this in java

public class Try {

    public static double averageCount(String[] array,char target)
    {
        double avg=0.0;
        String str;
        char ch;
        int total=0;

        for (int i = 0; i < array.length; i++) {
            str=array[i];
            total=count(str,target);

            System.out.println(total);

        }
        avg=total/array.length+1;
        return avg;
    }
    public static int count(String str, char target)
    {
        int count=0;
        for (int i = 0; i <str.length(); i++) {

            if(str.charAt(i)==target)
            {
                count++;
            }
        }

        return count;
    }

    public static void main(String[] args) {
        double avg=0.0;

Upvotes: 1

Views: 280

Answers (3)

Chetan Kinger
Chetan Kinger

Reputation: 15212

If you are using Java 8, you could simplify your count logic a bit as follows :

String[] array = new String[]{"hie","raisin","critical"};
String target = "i";
double count = Arrays.stream(array).map(s->s.split("")).flatMap(Arrays::stream).filter(ch->ch.equals(target)).count();
double average = count/array.length;
System.out.println(average);

Upvotes: 0

Peter Pan
Peter Pan

Reputation: 24138

My Implemention:

String[]  array = new String[]{"hie","raisin","critical"};
Double[] occs = new Double[256];
for(int i = 0; i < occs.length; i++) {
    occs[i] = 0.;
}
for(String str: array) {
    for(char ch: str.toCharArray()) {
        occs[ch]++;
    }
}
System.out.println(occs['i']/array.length); // 1.66...
System.out.println(occs['r']/array.length); // 0.66...

Upvotes: 3

Uma Kanth
Uma Kanth

Reputation: 5629

You need to add the total to the previous value.

total = count(); //this replaces the original total.

use

total = total + count();

or

total += count();

And average would be

total / array.length //array.length would return the total number of elements in it.(here 3)

Upvotes: 2

Related Questions