20182318ハフマン符号化試験

20182318ハフマン符号化試験

1.実験の内容

文字セットで:S = {A、B、 C、D、E、F、G、H、I、J、K、L、M、nopq、R、S、T、U、V、X、W、 Y、Z}。
計算された確率構造ハフマン木に基づき、各文字の出現の統計的確率を含むファイルの26個の文字を考えます。
英語の文書とは、符号化と復号化を完了します。
要件:

  1. 英語の文書を含む26文字(またはなど、句読点を含めることはできません)、各キャラクターの統計の確率を準備
  2. ハフマンツリー構造
  3. ファイルの英語ファイルはエンコードされた後、コーディング出力
  4. デコードされたファイルを出力し、エンコードされたファイルをデコード

    2.実験の手順と結果

    プロセス:

    1、ハフマン木の設立

  5. 昇順で重量ジャンクション全ての加重値(右ここで、私たちはそれぞれの文字の代わりに表示される確率の値を使用します)。
  6. 順次左側にツリーのノードの最小重みの小さい値の下、(除去ノードに対応するノードの集合から除外)重量を選択します。
  7. 二つのノードの親ノードとして新しいノードを生成し、親ノードの重み値は、これら2つのポイントとの接合部の加重和に等しい、新しいノードは、その後、我々は戻って構成ツリーノードに必要があるのを継続されますソート;
  8. すべてのノードがツリーを形成するまで、上記3つのステップを繰り返し、ツリーはハフマン木である、最後の世代は、ルートノードです。ハフマンツリーは、すべての情報がリーフノードのノードに格納されているように構築しました。

メインコード
package hafuman;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class harfmain {
    public static void main(String[] args) throws IOException {
        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:\\", "20182318wangzhenao.txt");
        Reader reader2 = new FileReader(file);
        String result = "";
        String result1 = "";
        String result2 = "";
        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;
        }
        for(int i = 0 ; i<sum.length;i++)
        {
            System.out.println(S[i]+":"+sum[i]);
        }
        List<Node> nodes = new ArrayList<Node>();
        for (int i = 0; i < sum.length; i++) {
            nodes.add(new Node(S[i], sum[i]));
        }
        harf h = new harf();
        Node root = h.createTree(nodes);
        h.setCode(root);
        String s = h.toHufmCode(result, root);
        System.out.println(s);
        File file1 = new File("D:\\", "hello world.txt");
        Writer writer2 = new FileWriter(file1);
        BufferedWriter bufferedWriter = new BufferedWriter(writer2);
        bufferedWriter.write("编码后的哈夫曼为"+s, 0, s.length());
        bufferedWriter.flush();
        bufferedWriter.close();
        String a ="哈夫曼解码后"+h.CodeToString(s,root);
        File file2 = new File("D:\\", "hello world1.txt");
        Writer writer3 = new FileWriter(file2);
        BufferedWriter bufferedWriter1 = new BufferedWriter(writer3);
        bufferedWriter1.write(a, 0, a.length());
        bufferedWriter1.flush();
        bufferedWriter1.close();
        Reader reader3 = new FileReader(file1);
        Reader reader4 = new FileReader(file2);
        while (reader3.ready()) {
            result1 += (char) reader3.read();
        }
        System.out.println(result1);
       while (reader4.ready()) {
            result2 += (char) reader4.read();
        }
       System.out.println(result2);
    }
}
package hafuman;

    public class Node<E> {
        E data;
        public String code = "";
        double weight;
        Node leftChild;
        Node rightChild;

        public Node(E data, double weight) {
            super();
            this.data = data;
            this.weight = weight;
        }

    }
package hafuman;

import java.util.List;

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);
    }

    private static void subSort(List<Node> nodes, int start, int end) {
        if (start < end) {
            // �Ե�һ��Ԫ����Ϊ�ֽ�ֵ
            Node base = nodes.get(start);
            // i������������������ڷֽ�ֵ��Ԫ�ص�����
            int i = start;
            // j���ұ߿�ʼ����������С�ڷֽ�ֵ��Ԫ�ص�����
            int j = end + 1;
            while (true) {
                // �ҵ����ڷֽ�ֵ��Ԫ�ص�����������i�Ѿ�����end��
                while (i < end && nodes.get(++i).weight >= base.weight)
                    ;
                // �ҵ�С�ڷֽ�ֵ��Ԫ�ص�����������j�Ѿ�����start��
                while (j > start && nodes.get(--j).weight <= base.weight)
                    ;

                if (i < j) {
                    swap(nodes, i, j);
                } else {
                    break;
                }
            }

            swap(nodes, start, j);

            //�ݹ����������
            subSort(nodes, start, j - 1);
            //�ݹ��ұ�������
            subSort(nodes, j + 1, end);
        }
    }

    public static void quickSort(List<Node> nodes) {
        subSort(nodes, 0, nodes.size() - 1);
    }

    private static void swap(List<Node> nodes, int i, int j) {
        Node tmp;
        tmp = nodes.get(i);
        nodes.set(i, nodes.get(j));
        nodes.set(j, tmp);
    }

    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);
        }

    }
    public void output(Node root) {

        if (root.leftChild == null && root.rightChild == null) {
            System.out.println(root.data + ": " +root.code);
        }
        if (root.leftChild != null) {
            output(root.leftChild);
        }
        if (root.rightChild != null) {
            output(root.rightChild);
        }
    }
    private String hfmCodeStr = "";// �������������ӳɵ��ַ���

    /**
     * ����
     */
    public String toHufmCode(String str,Node root) {

        for (int i = 0; i < str.length(); i++) {
           char c = str.charAt(i) ;
            search(root, c);
        }
        return hfmCodeStr;
    }

    private void search(Node root, char c) {
        if (root.leftChild == null && root.rightChild == null) {
            if (c == (char)root.data) {
                hfmCodeStr += root.code; // �ҵ��ַ����������������ƴ�ӵ����շ��ض������ַ����ĺ���
            }
        }
        if (root.leftChild != null) {
            search(root.leftChild, c);
        }
        if (root.rightChild != null) {
            search(root.rightChild, c);
        }

    }
    String result="";
    boolean target = false; // ������
    public String CodeToString(String codeStr,Node root) {

        int start = 0;
        int end = 1;

        while(end <= codeStr.length()){
            target = false;
            String s = codeStr.substring(start, end);
            matchCode(root, s); // ����
            // ÿ����һ���ַ���start�����
            if(target){
                start = end;
            }
            end++;
        }
        return result;
    }

    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);
        }
    }

}

業績

参考資料

おすすめ

転載: www.cnblogs.com/1400694592qq/p/11923075.html