2021-11-27

Is it possible to have two different Huffman encoding scheme yielding different number of bits?

I made a solution for Huffman encoding but my code is not yielding expected output.

I cannot figure out what is wrong.

Any help is appreciated.

abcdef
1 2 3 3 5 5

Your Output: 
00 01 10 110 1110 1111 

Expected Output: 
000 001 01 10 110 111 

It can be seen clearly that number of bits are different expected one being 16 mine being 17. Is it possible to have different output for different huffman schemes?

class Solution {

    class HuffmanNode {
        char c;
        int freq;
        HuffmanNode left;
        HuffmanNode right;

        public HuffmanNode(char c, int freq) {
            this.c = c;
            this.freq = freq;
            this.left = null;
            this.right = null;
        }
    }

    class HuffmanNodeComparator implements Comparator<HuffmanNode> {
        public int compare(HuffmanNode a, HuffmanNode b) {
            return a.freq - b.freq;
        }
    }

    ArrayList<String> res = new ArrayList<>();

    public ArrayList<String> huffmanCodes(String S, int f[], int N) {
        Queue<HuffmanNode> pq = new PriorityQueue<HuffmanNode>(new HuffmanNodeComparator());

        for (int i = 0; i < N; i++) {
            pq.offer(new HuffmanNode(S.charAt(i), f[i]));
        }

        while (pq.size() > 1) {
            HuffmanNode a = pq.poll();
            HuffmanNode b = pq.poll();
            HuffmanNode newNode = new HuffmanNode('-', a.freq + b.freq);

            newNode.left = a;
            newNode.right = b;

            pq.offer(newNode);
        }

        dfs(pq.poll(), "");

        return res;
    }

    public void dfs(HuffmanNode root, String HuffmanCode) {
        if (root == null) return;
        if (root.c != '-') {
            res.add(HuffmanCode);
            return;
        }

        dfs(root.left, HuffmanCode + "0");
        dfs(root.right, HuffmanCode + "1");
    }
}


from Recent Questions - Stack Overflow https://ift.tt/3cOxM7k
https://ift.tt/eA8V8J

No comments:

Post a Comment