Write the following in Java: Write a program which implements Huffman Encoding a
ID: 3934570 • Letter: W
Question
Write the following in Java: Write a program which implements Huffman Encoding assuming a code alphabet of Z2, ie, binary codewords. You should start with a class called HuffmanNode.java, which contains the required fields S, P, C, L, as well as a left and a right child HuffmanNode. The algorithm should proceed as follows: First, the user selects a text file, which is read into your program. Each line of the text file will have a symbol, sk S, and a probability, pk P. Each line should be written to a distinct HuffmanNode, (leaving Ck and lk blank for later). The newly semi-filled HuffmanNodes should be added, in increasing order of pk into a HuffmanNode list: an ArrayList of HuffmanNodes. Then the Huffman tree is created by following the Huffman Algorithm. After the tree is created, the tree is traversed recursively in order that the codewords and lengths may be added to the HuffmanNodes. Finally, print your symbols and codes to the screen or to a file for verification. Also, you should traverse your Huffman Tree in order to compute the average codeword length of your new code, (the ACWL(C)).
Explanation / Answer
import java.util.Scanner; public class createHuffmanCode { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("firstly please Enter a text: "); String texthere = input.nextLine(); int[] totalcounts = togetCharacterFrequency(texthere ); // This is used to count frequency System.out.printf("%-15s%-15s%-15s%-15s ", "The ASCII Code", "The Character", "The Frequency", "Code"); Tree tree = togetHuffmanTree(totalcounts); // This ise used to create a Huffman tree String[] totalcoded = togenerateCode(tree.root); // we will get totalcoded for (int i = 0; i 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 } /** This function is used to get the frequency of the characters */ public static int[] togetCharacterFrequency(String texthere) { int[] totalcounts = new int[256]; // 256 ASCII characters for (int i = 0; iRelated Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.