gpt4 book ai didi

java - 我在霍夫曼编码 java 中遇到一些逻辑错误

转载 作者:行者123 更新时间:2023-11-30 05:19:52 24 4
gpt4 key购买 nike

这是代码...

public class Huffman_Coding {
public static void main(String[] args) {

Scanner sc = new Scanner(System.in);
System.out.println("Enter a string to compress: ");
String str = sc.nextLine();
sc.close();
HashString hs = new HashString();

HashMap<Character, Integer> hm = hs.getStringHash(str);

PriorityQueue<Node> pq = new PriorityQueue<Node>();
for (char ch : hm.keySet()) {
pq.add(new Node(null, null, hm.get(ch), ch));
}
System.out.println(pq);
while (pq.size() != 1) {
Node left = pq.poll();
Node right = pq.poll();
Node parent = new Node(left, right, left.freq + right.freq, '\0');
pq.add(parent);
System.out.println(pq);
}
Huffman_Tree ht = new Huffman_Tree();
String ans = "";
ht.inOrder(pq.poll(), ans);
}
}

class Node implements Comparable<Node> {

@Override
public String toString() {
return "Node [freq=" + freq + ", ch=" + ch + "]";
}

Node lptr;
Node rptr;
int freq;
char ch;

Node(Node lptr, Node rptr, int freq, char ch) {
this.freq = freq;
this.lptr = lptr;
this.rptr = rptr;
this.ch = ch;
}

public int compareTo(Node o) {

int comparedvalue = Integer.compare(this.freq, o.freq);
if (comparedvalue != 0)
return comparedvalue;
else
return Integer.compare(this.ch, o.ch);
}
}

boolean isLeaf() {
return this.lptr == null && this.rptr == null;
}
}

class Huffman_Tree {
void inOrder(Node root, String code) {
if (!root.isLeaf()) {
inOrder(root.lptr, code + '0');
inOrder(root.rptr, code + '1');

} else
System.out.println(root.ch + " : " + code);

}
}

这里,对于输入字符串abccddeeee,我收到类似的信息:

[Node [freq=1, ch=a], Node [freq=1, ch=b], Node [freq=2, ch=c], Node [freq=2, ch=d], Node [freq=4, ch=e]]
[Node [freq=2, ch= ]]

我很困惑为什么在第二步中具有“d”的节点比“e”领先。这使我在最终编码中出现错误。为什么compareTo 方法失败我无法理解。

getHashString 返回一个哈希值,其中键中包含字符,值中包含它们的频率。

最佳答案

我不明白为什么 PriorityQueue 中的元素顺序不是在轮询元素和添加新元素之后的预期顺序”合成”元素,但我认为您可以解决切换到 TreeSet 的问题,正如我已经成功完成的那样

TreeSet<Node> pq = new TreeSet<Node>((n1, n2) -> n1.compareTo(n2)); // explicit but unnecessary comparator

并将每个 pq.poll() 调用更改为 pq.pollFirst()...

希望这个解决方法可以帮助您!

编辑

正如您可以在 official PriorityQueue documentation 中读到的那样, * 方法 iterator() 中提供的迭代器不保证以任何特定顺序遍历优先级队列的元素。如果需要有序遍历,请考虑使用 Arrays.sort(pq.toArray()).*

这应该可以解释为什么 toString() 方法调用以不同于预期优先级顺序的顺序显示队列元素...

关于java - 我在霍夫曼编码 java 中遇到一些逻辑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59737317/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com