[英]How to count the number of bits on Huffman code?
我正在嘗試計算 txt 文件的字節數。 為了做到這一點,我必須計算霍夫曼編碼的壓縮效率。 我有三節關於霍夫曼的課。
在主類中:
Scanner s = new Scanner(System.in);
// creating a priority queue q.
// makes a min-priority queue(min-heap).
PriorityQueue<HuffmanNode> q
= new PriorityQueue<HuffmanNode>(count.length, new MyComparator());
for (int i = 0; i < count.length; i++) {
// creating a Huffman node object
// and add it to the priority queue.
HuffmanNode hn = new HuffmanNode();
hn.c = alphabet[i];
hn.data = count[i];
hn.left = null;
hn.right = null;
// add functions adds
// the huffman node to the queue.
q.add(hn);
}
// create a root node
HuffmanNode root = null;
// Here we will extract the two minimum value
// from the heap each time until
// its size reduces to 1, extract until
// all the nodes are extracted.
while (q.size() > 1) {
// first min extract.
HuffmanNode x = q.peek();
q.poll();
// second min extarct.
HuffmanNode y = q.peek();
q.poll();
// new node f which is equal
HuffmanNode f = new HuffmanNode();
// to the sum of the frequency of the two nodes
// assigning values to the f node.
f.data = x.data + y.data;
f.c = '-';
// first extracted node as left child.
f.left = x;
// second extracted node as the right child.
f.right = y;
// marking the f node as the root node.
root = f;
// add this node to the priority-queue.
q.add(f);
}
// print the codes by traversing the tree
Huffman.printCode(root, "");
霍夫曼類:
public class Huffman {
// recursive function to print the
// huffman-code through the tree traversal.
// Here s is the huffman - code generated.
public static void printCode(HuffmanNode root, String s)
{
// base case; if the left and right are null
// then its a leaf node and we print
// the code s generated by traversing the tree.
if (root.left
== null
&& root.right
== null
&& Character.isLetter(root.c)) {
// c is the character in the node
System.out.println(root.c + ":" + s);
return;
}
// if we go to left then add "0" to the code.
// if we go to the right add"1" to the code.
// recursive calls for left and
// right sub-tree of the generated tree.
printCode(root.left, s + "0");
printCode(root.right, s + "1");
}
還有兩個關於設置對象的類,一個用於比較節點。 霍夫曼工作正常,我得到以下結果:
t:000
c:00100
g:00101
d:0011
w:01000
u:01001
r:0101
e:011
s:1000
n:1001
h:1010
i:1011
o:1100
b:110100... //for the rest aphabet letters.
我需要的是計算每個字母顯示的位數並將它們保存到一個整數數組中,例如 t:3 o:4(...)
有什么想法嗎?
您想要創建一個 < Character , int[] > 類型的映射作為 Huffman 類的私有屬性。 然后在 if 語句的正文中,您希望將新對放入映射中,該對是您擁有的字符和字符串。 在你的情況下,這將是 root.c 和 s。
由於它是一個字符串,您當然需要將其轉換為整數數組。 您可以在這里找到簡單的方法: 將字符串數組轉換為整數數組。
然后,您可以創建一個方法,該方法從 Huffman 類中調用屬性(即地圖),然后從地圖中調用您想要的任何數組。
因此,您的 Huffman 類必須成為具有構造函數的對象,因此您將創建一個 Huffman 對象,然后運行您的打印代碼方法,然后從 Huffman 對象中獲取地圖。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.