开发者

Storing values within a hashmap

I am trying to code a frequency analysis program for fun. I currently have everything being stored in a hashmap and I index the values using an iterator.

My values however are stored as integers, how could I go about converting these entries into percentages, or a more accessible format so i can compare them later?

I was thinking i could use getValue(), but this is an object.

Can anyone point me in the right direction? Should i be using a hash开发者_Go百科map? should i transfer them into an array the size of the hashmap?


Hashmaps are indeed ideal for building freuqency tables, and the value type should definitely be Integer (if you try to store percentages, you'd have to update all percentages each time you add a new value). If you have another class that contains the hashmap as a field, you could make a method for retrieving the percentage of a specific character (note that I don't recall the exact method names):

public float getPercentage(char c) {
    if (!map.containsKey(c))
        return 0;
    int sum = 0;
    for (Integer count : map.values())
        sum += count;
    return map.get(c) / (float)sum;
}

If you want the percentages for all characters, you should make a method that produces a new hashmap that contains the percentages, calculated in a similar fashion. If you want to be fancy (read: overengineer), you could even implement an Iterator that produces percentages from the original Integer hashmap.


I'm assuming you have a map of the form {'A':5, 'B':4, etc} meaning A appears five times in your text, B four times, etc.

In that case, to calculate the frequency of a given letter, you need to know the total number of letters in the map (i.e. 9 in the example above). You can do this one of two ways:

  1. Iterate over the entire map, and sum up the values
  2. Keep a running count of the number of times you add something to the map, so you can use it later.

Both are reasonable solutions to the problem. I'd prefer option 2, especially if you are doing things interactively, whereas option 1 might suffice in a batch mode setting.


You should parametrize your hashmap so that getValue() returns an Integer. You could use the object type Float if you would like a percentage instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜