-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHuffmanCoder.java
More file actions
103 lines (88 loc) · 2.45 KB
/
HuffmanCoder.java
File metadata and controls
103 lines (88 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/**
* The Class HuffmanCoder.
*
* @author Toni Lachmaniucu Date: April 2 2018
*/
public class HuffmanCoder {
/** The huffmantree containing the characters and their frequencies. */
private HuffmanTree<HuffmanPair> huffTree;
/** The encoding list containing the encoding data symbol/code pairs. */
private ArrayUnorderedList<EncodingData> encodingList;
/**
* Instantiates a new huffman coder object.
*
* @param pairsList
* the list of huffman pairs (symbols and frequencies)
*/
public HuffmanCoder(ArrayOrderedList<HuffmanPair> pairsList) {
huffTree = new HuffmanTree<HuffmanPair>(pairsList);
encodingList = new ArrayUnorderedList<EncodingData>();
buildEncodingList(huffTree.getRoot(), "");
}
/**
* Decodes the given code into a character.
*
* @param code
* the code
* @return the char
*/
public char decode(String code) {
BinaryTreeNode<HuffmanPair> node = huffTree.getRoot();
int i = 0;
while (!node.isLeaf() && i < code.length()) {
if (code.charAt(i) == '0') {
node = node.getLeft();
} else if (code.charAt(i) == '1') {
node = node.getRight();
}
i++;
}
if (node.isLeaf() && i == code.length()) {
return node.getElement().getCharacter();
}
return (char) 0;
}
/**
* Encode.
*
* @param c
* the character to encode
* @return the encoding of the character
* @throws ElementNotFoundException
* the element not found exception
*/
public String encode(char c) throws ElementNotFoundException {
for (EncodingData data : encodingList) {
if (data.getSymbol() == c) {
return data.getEncoding();
}
}
throw new ElementNotFoundException("That character is not in the current encoding list!");
}
/*
* Returns a string representation of the huffman coder object based on the
* toString of the ArrayUnorderedList class.
*
* @see java.lang.Object#toString()
*/
public String toString() {
return encodingList.toString();
}
/**
* Builds the encoding list.
*
* @param node
* the current node
* @param encoding
* the encoding for that node object.
*/
private void buildEncodingList(BinaryTreeNode<HuffmanPair> node, String encoding) {
if (node.isLeaf()) {
EncodingData dat = new EncodingData(node.getElement().getCharacter(), encoding);
encodingList.addToFront(dat);
} else {
buildEncodingList(node.getLeft(), encoding + 0);
buildEncodingList(node.getRight(), encoding + 1);
}
}
}