哈夫曼编码算法实现

package juc;

import lombok.ToString;

import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

/**
 * @Author lyr
 * @create 2020/10/28 19:43
 */

public class Main {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("hello world");
        double[] p = {0.35, 0.1, 0.2, 0.2, 0.15};
        char[] q = {'a', 'b', 'c', 'd', '-'};
        PriorityQueue<Node> pq = new PriorityQueue<>((node1, node2) ->
        {
            int x = Double.compare(node1.freq,node2.freq);
            if (x!=0) return x;
            //按照字典序排序
            return Character.compare(node1.value,node2.value);
           
        });
        for (int i = 0; i < p.length; ++i) {
            double freq = p[i];
            char value = q[i];
            Node node = new Node(value, freq);
            node.isLeaf = true;
            pq.offer(node);
        }

        while (pq.size() > 1) {
            Node min1 = pq.poll();
            Node min2 = pq.poll();
            double freq = min1.freq + min2.freq;
            Node root = new Node('&', freq);
            root.left = min1;
            root.right = min2;
            pq.offer(root);
        }
        //pq.size() ==1
        Node root = pq.poll();
        Map<Node,String> map = printCode(new HashMap<>(),root,"");
        // System.out.println(map);
        map.forEach((node, code) ->{
            System.out.println(node.value +"="+code);
        });

    }

    static Map<Node, String> printCode(Map<Node, String> map, Node node, String parentCode) {
        if(node == null) return map;
        if (node.isLeaf) {
            map.put(node,parentCode);
        }
        printCode(map,node.left,parentCode+"0");
        printCode(map,node.right,parentCode+"1");
        return map;
    }

    @ToString
    static class Node {
        double freq;
        Node left;
        Node right;
        char value;
        boolean isLeaf;


        @Override
        public int hashCode() {
            int result;
            long temp;
            temp = Double.doubleToLongBits(freq);
            result = (int) (temp ^ (temp >>> 32));
            result = 31 * result + (int) value;
            return result;
        }

        Node(char value, double freq) {
            this.freq = freq;
            this.value = value;
        }


    }

}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值