Java 如何计算哈夫曼码的位数?

Java 如何计算哈夫曼码的位数?,java,class,nodes,huffman-code,Java,Class,Nodes,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<

我正在计算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, "");
还有两个关于设置对象的类和一个用于比较节点的类。 哈夫曼工作得很好,我得出以下结果:

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:3o:4(…)


有什么想法吗

您想创建一个类型为的映射作为Huffman类的私有属性。然后在if语句的主体中,您需要将一对新的字符串放入映射中,该对是您拥有的字符和字符串。在您的情况下,这将是root.c和s

由于它是一个字符串,您当然需要将其转换为整数数组。您可以在此处找到简单的方法:

然后可以创建一个方法,从Huffman类调用属性(即映射),然后从映射调用所需的任何数组

因此,您的Huffman类必须成为一个具有构造函数的对象,因此您将创建一个Huffman对象,然后运行print code方法,然后从Huffman对象获取映射

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.