This is homework. I've been stuck on this a long time...
I have to create leaf nodes. For this I have the class LeafTreeNode
.
LeafTreeNode.java :
import java.util.Map;
public class LeafTreeNode implements TreeNode {
private char symbol;
private int symbolCount;
public LeafTreeNode(char symbol, int symbolCount) {
this.symbol = symbol;
this.symbolCount = symbolCount;
}
public int symbolCount() {
return symbolCount;
}
public void getSymbolCodes(String prefix, Map<Character, String> symbolCodes) {
symbolCodes.put(symbol, prefix);
}
}
Now I have to use the method characterHistogram(String s)
and create a leaf node for each character occurring in s
.
This method is in a new class Huffman
.
I have to do this in the method huffmanCode(String s)
.
Huffman
import java.util.Map;
public class Huffman{
private LeafTreeNode Blattknoten;
public int[] characterHistogram(String s) {
// Only ASCII
int[] histogram = new int[256];
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c < 256) {
histogram[c]++;
}
System.out.println(s.charAt(i) + " <-> " + histogram[c]);
}
return histogram;
}
public void printHuffmanCoding(Map<Character, String> map) {
// for (Character c : map.keySet()) {
// System.out.println("'" + c + "': " + map.get(c));
// }
}
/**
* Compute the Huffman coding map for s
*
* @param s
* String to encode
* @return Huffman coding map
*/
public Map<Character, String> huffmanCode(String s) {
int[] histogram = characterHistogram(s);
System.out.println(1);
// Blattknoten.symbolCount();
// Blattknoten
// Blattknoten.getSymbolCodes(s, null);
// for( int i = 0; i < histogram.length;i++){
// histogram[i];
// }
// LeafTreeNode.getSymbolCodes(s, null)
// TODO 3.
return null;
}
/**
* @param s
* String to encode
* @param map
* Huffman coding map
* @return the length of the Huffman coding of s
*/
public long lengthHuffmanCoding(String s, Map<Character, String> map) {
// TODO 4.
return 42L;
}
/**
* @param s
* String to encode
* @return the length of the 8-bit coding of s
*/
public long length8BitCoding(String s) {
// TODO 4.
return 42L;
}
/**
* Compute the compression ratio we can achieve for s given the Huffman
* encoding map as compared to 8-bit coding of the symbols.
*
* @param s
* String to encode
* @param map
* Huffman coding map
* @return compression ratio
*/
public float computeCompressionRatio(String s, Map<Character, String> map) {
// TODO 4.
return 42.f;
}
public static void main(String[] args) {
Huffman h = new Huffman();
String s = "Insert String here";
Map<Character, String> map = h.huffmanCode(s);
h.printHuffmanCoding(map);
float cr = h.computeCompressionRatio(s, map);
System.out.println("Compression ratio: " + (cr * 100) + "%");
}
}
I tried to use the methods from LeafTreeNode
but this didn't work. How I can create a leaf node?
Go through all 256 histogram entries, and for each one whose count is not zero, you use new LeafTreeNode(i, histogram[i])
.
The next question will be: what do you do with each leaf once it's created?