霍曼转移计算java代码
时间: 2024-06-05 09:03:43 浏览: 160
Hohmann转移计算
霍尔曼(Huffman)编码是一种数据压缩算法,其基本思路是将出现频率高的字符用短的编码表示,出现频率低的字符用长的编码表示,从而达到压缩数据的目的。以下是一个简单的霍尔曼编码的Java实现:
```
import java.util.*;
public class HuffmanCoding {
private static Map<Character, String> charCodeMap = new HashMap<>();
public static void main(String[] args) {
String input = "Hello, World!";
System.out.println("Original Input: " + input);
Map<Character, Integer> charFrequencyMap = new HashMap<>();
for (char c : input.toCharArray()) {
charFrequencyMap.put(c, charFrequencyMap.getOrDefault(c, 0) + 1);
}
PriorityQueue<Node> pq = new PriorityQueue<>();
for (Map.Entry<Character, Integer> entry : charFrequencyMap.entrySet()) {
pq.offer(new Node(entry.getKey(), entry.getValue()));
}
while (pq.size() > 1) {
Node left = pq.poll();
Node right = pq.poll();
pq.offer(new Node(left, right));
}
generateCharCode(pq.poll(), "");
StringBuilder sb = new StringBuilder();
for (char c : input.toCharArray()) {
sb.append(charCodeMap.get(c));
}
String encoded = sb.toString();
System.out.println("Encoded Output: " + encoded);
sb = new StringBuilder();
int index = 0;
while (index < encoded.length()) {
for (Map.Entry<Character, String> entry : charCodeMap.entrySet()) {
String code = entry.getValue();
if (encoded.startsWith(code, index)) {
sb.append(entry.getKey());
index += code.length();
break;
}
}
}
String decoded = sb.toString();
System.out.println("Decoded Output: " + decoded);
}
private static void generateCharCode(Node node, String code) {
if (node.isLeafNode()) {
charCodeMap.put(node.character, code);
return;
}
generateCharCode(node.left, code + "0");
generateCharCode(node.right, code + "1");
}
private static class Node implements Comparable<Node> {
char character;
int frequency;
Node left;
Node right;
public Node(char character, int frequency) {
this.character = character;
this.frequency = frequency;
}
public Node(Node left, Node right) {
this.frequency = left.frequency + right.frequency;
this.left = left;
this.right = right;
}
public boolean isLeafNode() {
return left == null && right == null;
}
@Override
public int compareTo(Node other) {
return Integer.compare(this.frequency, other.frequency);
}
}
}
```
阅读全文