0

This method computes the entropy of the letters. To compute the entropy, for each letter, compute the ratio (say it p) of the frequency count of the letter to the total frequency count of all letters. Then, compute the following value: p * Math.log (1 / p). Return the sum of the values, rounded to the nearest integer value.

public int computeEntropy() {
    int FreqCount = 0;
    double sum = 0;
    char[] O = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
    for(int k = 0; k < O.length; k++) {
        if(FreqCount > 0) {
            FreqCount = 0;
        }
    for(int j = 0; j < N.size(); j++) {
        for(int i = 0; i < N.get(j).length(); i++) {
            if(O[k] == N.get(j).charAt(i) || Character.toUpperCase(O[k]) == N.get(j).charAt(i)) {
                FreqCount++;
            }
            else 
                FreqCount += 0;
        }
    }
    p = FreqCount/RawCount;
    sum += p * Math.log (1 / p);
    return (int)sum;
}

I already get an ArrayList (N) of String which is the word separated by space. I test this method but still cannot get the correct answer. The description of this method is on the top. Can someone help me?

Roger
  • 1
  • 1
  • It would help if you provided the entire code, including the definition of N, p and RawCount. Moreover, why did you give the letter array the name O ? Apart from the fact that you should write variables lower-case it does make your code more readable. – Jan B. May 08 '18 at 17:28
  • What **is** the output you're getting? What are you expecting? "Cannot get the correct answer" and "Can someone help me" are *really* vague. – QBrute May 08 '18 at 17:29
  • Where are `p` and `RawCount` declared? Are they `int`s? – Andy Turner May 08 '18 at 17:31
  • public void subcomputeEntropy(String Tok) { for(int i=0;i – Roger May 08 '18 at 17:37
  • I use scanner to get token from the text. Next() get the words separate by space, and add these words into a ArrayList, which is N – Roger May 08 '18 at 17:38
  • And the RawCount is the total account of the letter in the text – Roger May 08 '18 at 17:39
  • subcomputeEntropy is called in main and get the tokens – Roger May 08 '18 at 17:41
  • p is type of double, RawCount is type of int – Roger May 08 '18 at 18:03
  • If `FreqCount` and `RawCount` are both ints, then you are dividing them using integer division. `RawCount` is always greater, so the result of that division is zero. It doesn't matter that you are assigning the result to a double variable. Make at least one of the operands `double`. – Andy Turner May 08 '18 at 18:08
  • that's the mistake i have, thank you so much @Andy Turner – Roger May 08 '18 at 19:52

0 Answers0