In this bit of code, i am attempting to split a string into Characters and place each character into a map. If the same Character appears more than once I put a counter on it and place it back into the map, incrementing the integer(frequency).
public class FrequencyMap {
public static Map<Character, Integer> generateMap(String s){
HashMap<Character, Integer> myMap = new HashMap<Character, Integer>();
//generate a map of frequencies of the characters in s
//need to break the string down into individual characters, sort them
//in there frequencies then place them in map
for(int i = 0; i < s.length(); i++){
//break string into characters
//need to determine how many characters make up the string, can do this by
//putting a counter on each letter that appears when the string is being
//broken down, if a letter reoccurs increment the counter by one.
s.substring(i);
char ch = s.charAt(i);
myMap.put(ch, i);
//calculating the occurence of a character in a string.
if(myMap.containsKey(ch)){
myMap.put(ch, myMap.get(i) + 1);
}//end of if statement
}//end of for loop
return myMap;
}//end of public generateMap()
}//end of FrequencyMap
Here is the main
public static void main(String args[]){
String str = "missisippi";
Map frequencyMap = FrequencyMap.generateMap(str);
HuffmanTree tree = new HuffmanTree(frequencyMap);
Map<Character, String> encodingMap = tree.getEncodingMap();
String encoded = tree.encode(str, encodingMap);
System.out.println(encoded);
}//end of main
Okay a few things…
Strings are immutable!!
should really be
Although I’m still not quite sure what the point of this is altogether.
Secondly..
These lines don’t make sense
You just added the key
chand then you immediately ask if the map containsch– that will always be true.I think you might have meant to put the
if-statement first and to putmyMap.put(ch, 1)in anelse-clause. Oh, andmyMap.get(i)probably should have beenmyMap.get(ch).