1.设有字符集:S={a,b,c,d,e,f,g,h,i,j,k,l,m,n.o.p.q,r,s,t,u,v,w,x,y,z},给定一个包含26个英文字母的文件,统计每个字符出现的概率。
char[] S = new char[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
double[] sum = new double[26];
int count = 0;
for (int i = 0; i < 26; i++) {
sum[i] = 0;
}
File file = new File("D:\\test", "HelloWorld.txt");
Reader reader2 = new FileReader(file);
String result = "";
while (reader2.ready()) {
result += (char) reader2.read();
}
char[] text = result.toCharArray();
for (int j = 0; j < text.length; j++) {
for (int k = 0; k < S.length; k++) {
if (text[j] == S[k] || text[j] == (S[k] - 32)) {
sum[k]++;
count++;
}
}
}
for (int i = 0; i < sum.length; i++) {
sum[i] = sum[i] / count;
}
2.根据计算的概率构造一颗哈夫曼树
harf h = new harf();
Node root = h.createTree(nodes);
h.setCode(root);
public class harf {
Node createTree(List<Node> nodes) {
// 只要nodes数组中还有2个以上的节点
while (nodes.size() > 1) {
quickSort(nodes);
//获取权值最小的两个节点
Node left = nodes.get(nodes.size() - 1);
Node right = nodes.get(nodes.size() - 2);
//生成新节点,新节点的权值为两个子节点的权值之和
Node parent = new Node(null, left.weight + right.weight);
//让新节点作为两个权值最小节点的父节点
parent.leftChild = left;
parent.rightChild = right;
//删除权值最小的两个节点
nodes.remove(nodes.size() - 1);
nodes.remove(nodes.size() - 1);
//将新节点加入到集合中
nodes.add(parent);
}
return nodes.get(0);
}
3.对英文文件进行编码,输出一个编码后的文件。
public void setCode(Node root) {
if (root.leftChild != null) {
root.leftChild.code = root.code + "0";
setCode(root.leftChild);
}
if (root.rightChild != null) {
root.rightChild.code = root.code + "1";
setCode(root.rightChild);
}
4.对编码文件进行解码,输出一个解码后的文件。
private void matchCode(Node root, String code){
if (root.leftChild == null && root.rightChild == null) {
if (code.equals(root.code)) {
result += root.data; // 找到对应的字符,拼接到解码字符穿后
target = true; // 标志置为true
}
}
if (root.leftChild != null) {
matchCode(root.leftChild, code);
}
if (root.rightChild != null) {
matchCode(root.rightChild, code);
}
}
public void BuildTree(){
Linked l=new Linked(sum,S);
Number Head=l.Sort();
Number temp=Head;
LinkedBinaryTree branch = null;
while (temp.next!=null){
int he=temp.num+temp.next.num;
LinkedBinaryTree a=new LinkedBinaryTree(temp);
LinkedBinaryTree b=new LinkedBinaryTree(temp.next);
branch=new LinkedBinaryTree(temp.num+temp.next.num,a,b);
temp=l.Delete2();
Number node=new Number(he,'1');
temp=l.InsertNode2(node);
}
root=branch;
}
原文:https://www.cnblogs.com/hp12138/p/11915553.html