Question

I have almost done with this code to Implement Huffman Coding. However I have an error...

I have almost done with this code to Implement Huffman Coding. However I have an error at the "Heap<Tree>". Could anyone help with solving this issue, really appreciated. Thank you!!

import java.util.Scanner;

public class HuffmanEncoding {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a text: ");
String text = input.nextLine();
  
int[] counts = getCharacterFrequency(text); // Count frequency

System.out.printf("%-15s%-15s%-15s%-15s\n",
"ASCII Code", "Character", "Frequency", "Code");
  
Tree tree = getHuffmanTree(counts); // Create a Huffman tree
String[] codes = getCode(tree.root); // Get codes
  
for (int i = 0; i < codes.length; i++)
if (counts[i] != 0) // (char)i is not in text if counts[i] is 0
System.out.printf("%-15d%-15s%-15d%-15s\n",
i, (char)i + "", counts[i], codes[i]);
}
  
/** Get Huffman codes for the characters
* This method is called once after a Huffman tree is built
*/
public static String[] getCode(Tree.Node root) {
if (root == null) return null;
String[] codes = new String[2 * 128];
assignCode(root, codes);
return codes;
}
  
/* Recursively get codes to the leaf node */
private static void assignCode(Tree.Node root, String[] codes) {
if (root.left != null) {
root.left.code = root.code + "0";
assignCode(root.left, codes);
  
root.right.code = root.code + "1";
assignCode(root.right, codes);
}
else {
codes[(int)root.element] = root.code;
}
}
  
/** Get a Huffman tree from the codes */
public static Tree getHuffmanTree(int[] counts) {
// Create a heap to hold trees
Heap<Tree> heap = new Heap<Tree>(); // Defined in Listing 24.10
for (int i = 0; i < counts.length; i++) {
if (counts[i] > 0)
heap.add(new Tree(counts[i], (char)i)); // A leaf node tree
}
  
while (heap.getSize() > 1) {
Tree t1 = heap.remove(); // Remove the smallest weight tree
Tree t2 = heap.remove(); // Remove the next smallest weight
heap.add(new Tree(t1, t2)); // Combine two trees
}

return heap.remove(); // The final tree
}
  
/** Get the frequency of the characters */
public static int[] getCharacterFrequency(String text) {
int[] counts = new int[256]; // 256 ASCII characters
  
for (int i = 0; i < text.length(); i++)
counts[(int)text.charAt(i)]++; // Count the character in text
  
return counts;
}
  
/** Define a Huffman coding tree */
public static class Tree implements Comparable<Tree> {
Node root; // The root of the tree

/** Create a tree with two subtrees */
public Tree(Tree t1, Tree t2) {
root = new Node();
root.left = t1.root;
root.right = t2.root;
root.weight = t1.root.weight + t2.root.weight;
}
  
/** Create a tree containing a leaf node */
public Tree(int weight, char element) {
root = new Node(weight, element);
}
  
@Override /** Compare trees based on their weights */
public int compareTo(Tree t) {
if (root.weight < t.root.weight) // Purposely reverse the order
return 1;
else if (root.weight == t.root.weight)
return 0;
else
return -1;
}

public class Node {
char element; // Stores the character for a leaf node
int weight; // weight of the subtree rooted at this node
Node left; // Reference to the left subtree
Node right; // Reference to the right subtree
String code = ""; // The code of this node from the root

/** Create an empty node */
public Node() {
}
  
/** Create a node with the specified weight and character */
public Node(int weight, char element) {
this.weight = weight;
this.element = element;
}
}
}
}

0 0
Add a comment Improve this question Transcribed image text
Request Professional Answer

Request Answer!

We need at least 10 more requests to produce the answer.

0 / 10 have requested this problem solution

The more requests, the faster the answer.

Request! (Login Required)


All students who have requested the answer will be notified once they are available.
Know the answer?
Add Answer to:
I have almost done with this code to Implement Huffman Coding. However I have an error...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Similar Homework Help Questions
  • For this assignment, you will write a program to work with Huffman encoding. Huffman code is...

    For this assignment, you will write a program to work with Huffman encoding. Huffman code is an optimal prefix code, which means no code is the prefix of another code. Most of the code is included. You will need to extend the code to complete three additional methods. In particular, code to actually build the Huffman tree is provided. It uses a data file containing the frequency of occurrence of characters. You will write the following three methods in the...

  • Please I need help ASAP Java Programing: Binary Search Tree Fully implement the BST class in Listing 25.4 (on page 961 of the 11th Edition of the text). Design and write a (main) driver program to com...

    Please I need help ASAP Java Programing: Binary Search Tree Fully implement the BST class in Listing 25.4 (on page 961 of the 11th Edition of the text). Design and write a (main) driver program to completely test every method in the BST class to ensure the class meets all its requirements. You should read the Listing 25.5: TestBST.java for an idea of what your program should look like. Listing 25.4 BST.java public class BST> extends AbstractTree { protected TreeNode...

  • I am getting a seg fault with my huffman tree. I'm not sure if it's my...

    I am getting a seg fault with my huffman tree. I'm not sure if it's my deconstructors but also getting some memory leaks. Can some one help me find my seg fault? It's in c++, thanks! //#ifndef HUFFMAN_HPP //#define HUFFMAN_HPP #include<queue> #include<vector> #include<algorithm> #include<iostream> #include <string> #include <iostream> using namespace std; class Node { public:     // constructor with left and right NULL nodes     Node(char charTemp, int c) {       ch = charTemp;       count = c;       left...

  • Add a non-recursive inorder() method to class LinkedBinaryTree<E> to traverse binary tree. Test inorder() method. Implementation...

    Add a non-recursive inorder() method to class LinkedBinaryTree<E> to traverse binary tree. Test inorder() method. Implementation in Java #########LinkedBinary Tree class######### public class LinkedBinaryTree<E> extends AbstractBinaryTree<E> { //---------------- nested Node class ---------------- /** Nested static class for a binary tree node. */ protected static class Node<E> implements Position<E> { private E element; // an element stored at this node private Node<E> parent; // a reference to the parent node (if any) private Node<E> left; // a reference to the left...

  • Return a method as an expression tree Hi guys. I need to return a method as...

    Return a method as an expression tree Hi guys. I need to return a method as an expression tree, it's currently returning null. public static ExpressionTree getExpressionTree(String expression) throws Exception {       char[] charArray = expression.toCharArray(); Node root = et.constructTree(charArray); System.out.println("infix expression is"); et.inorder(root); return et; } In the above method, et needs to have a value. -- Take a look at the complete class below. Kindly assist. ; public class ExpressionTree extends BinaryTree { private static final String DELIMITERS...

  • Since we do not want to have to rewrite this code when the element type changes,...

    Since we do not want to have to rewrite this code when the element type changes, this classes uses a Comparator to assist in ordering the elements. You will need to complete the siftUpComparator() and siftDownComparator() methods in the LinkedHeap Class. siftUp §Added element may violate heap-order property §siftUp() restores order starting at added node §Processing will continue working up the tree until: úFinds properly ordered node & parent úReaches the root (reaches node without parent) siftDown §Restores heap’s order...

  • Complete HeapPriorityQueue (7 points). In lecture we implemented HeapPriorityQueue using an array-based representation of a heap...

    Complete HeapPriorityQueue (7 points). In lecture we implemented HeapPriorityQueue using an array-based representation of a heap (a complete binary tree whose entries satisfy the heap-order property). For this problem, complete the included HeapPriorityQueue class by using the LinkedBinaryTree class to represent a heap. Hint: the most challenging part of this problem is identifying the last Position in the heap and the next available Position in the heap. It is suggested that you review the array-based heap to better understand how...

  • write a new test program called RemoveDuplicates.java. The program reads text input from keyboard or a text file and adds the words to a BST. The program then traverses the BST and prints out the word...

    write a new test program called RemoveDuplicates.java. The program reads text input from keyboard or a text file and adds the words to a BST. The program then traverses the BST and prints out the words in order (based on ASCII/UNICODE order) on the screen (or to output text file). Note that you may need to make some changes to BST.java. Sample test: ----jGRASP exec: java -ea removeDuplicates Original Text: a B 2 n w C q K l 0...

  • Hello. I have written the following function to remove a value from a Binary Search Tree using re...

    Hello. I have written the following function to remove a value from a Binary Search Tree using resources my professors gave and stuff I found online. The problem is I don't know how it works and I need to know how it works to finish the rest of the project. public boolean remove(T value){ if(value == null) return false; class RemoveBSTObj{ private boolean found = false; private Node removeBST(Node root, T value){ if(root == null) return root; //IF there is...

  • Can you take a look at my code that why the maxDepth function is not working?...

    Can you take a look at my code that why the maxDepth function is not working? public class BinaryTree {          class Node{        int key;        Node left,right;               public Node(int item) {            key = item;            left = right = null;        }    }       Node root;       public void BinaryTree(){        root = null;    }           void...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT