SlideShare a Scribd company logo
please navigate to cs112 webpage and go to assignments --> Trees. This will give you the
directions for the assignment. Please do the last 2 methods in huffman.java called encode() and
decode()
Code is provided below:
HuffmanCoding.java
package huffman;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Collections;
/**
* This class contains methods which, when used together, perform the
* entire Huffman Coding encoding and decoding process
*
* @author Ishaan Ivaturi
* @author Prince Rawal
*/
public class HuffmanCoding {
private String fileName;
private ArrayList sortedCharFreqList;
private TreeNode huffmanRoot;
private String[] encodings;
/**
* Constructor used by the driver, sets filename
* DO NOT EDIT
* @param f The file we want to encode
*/
public HuffmanCoding(String f) {
fileName = f;
}
/**
* Reads from filename character by character, and sets sortedCharFreqList
* to a new ArrayList of CharFreq objects with frequency > 0, sorted by frequency
*/
public void makeSortedList() {
StdIn.setFile(fileName);
/* Your code goes here */
}
/**
* Uses sortedCharFreqList to build a huffman coding tree, and stores its root
* in huffmanRoot
*/
public void makeTree() {
/* Your code goes here */
}
/**
* Uses huffmanRoot to create a string array of size 128, where each
* index in the array contains that ASCII character's bitstring encoding. Characters not
* present in the huffman coding tree should have their spots in the array left null.
* Set encodings to this array.
*/
public void makeEncodings() {
/* Your code goes here */
}
/**
* Using encodings and filename, this method makes use of the writeBitString method
* to write the final encoding of 1's and 0's to the encoded file.
*
* @param encodedFile The file name into which the text file is to be encoded
*/
public void encode(String encodedFile) {
StdIn.setFile(fileName);
/* Your code goes here */
}
/**
* Writes a given string of 1's and 0's to the given file byte by byte
* and NOT as characters of 1 and 0 which take up 8 bits each
* DO NOT EDIT
*
* @param filename The file to write to (doesn't need to exist yet)
* @param bitString The string of 1's and 0's to write to the file in bits
*/
public static void writeBitString(String filename, String bitString) {
byte[] bytes = new byte[bitString.length() / 8 + 1];
int bytesIndex = 0, byteIndex = 0, currentByte = 0;
// Pad the string with initial zeroes and then a one in order to bring
// its length to a multiple of 8. When reading, the 1 signifies the
// end of padding.
int padding = 8 - (bitString.length() % 8);
String pad = "";
for (int i = 0; i < padding-1; i++) pad = pad + "0";
pad = pad + "1";
bitString = pad + bitString;
// For every bit, add it to the right spot in the corresponding byte,
// and store bytes in the array when finished
for (char c : bitString.toCharArray()) {
if (c != '1' && c != '0') {
System.out.println("Invalid characters in bitstring");
return;
}
if (c == '1') currentByte += 1 << (7-byteIndex);
byteIndex++;
if (byteIndex == 8) {
bytes[bytesIndex] = (byte) currentByte;
bytesIndex++;
currentByte = 0;
byteIndex = 0;
}
}
// Write the array of bytes to the provided file
try {
FileOutputStream out = new FileOutputStream(filename);
out.write(bytes);
out.close();
}
catch(Exception e) {
System.err.println("Error when writing to file!");
}
}
/**
* Using a given encoded file name, this method makes use of the readBitString method
* to convert the file into a bit string, then decodes the bit string using the
* tree, and writes it to a decoded file.
*
* @param encodedFile The file which has already been encoded by encode()
* @param decodedFile The name of the new file we want to decode into
*/
public void decode(String encodedFile, String decodedFile) {
StdOut.setFile(decodedFile);
/* Your code goes here */
}
/**
* Reads a given file byte by byte, and returns a string of 1's and 0's
* representing the bits in the file
* DO NOT EDIT
*
* @param filename The encoded file to read from
* @return String of 1's and 0's representing the bits in the file
*/
public static String readBitString(String filename) {
String bitString = "";
try {
FileInputStream in = new FileInputStream(filename);
File file = new File(filename);
byte bytes[] = new byte[(int) file.length()];
in.read(bytes);
in.close();
// For each byte read, convert it to a binary string of length 8 and add it
// to the bit string
for (byte b : bytes) {
bitString = bitString +
String.format("%8s", Integer.toBinaryString(b & 0xFF)).replace(' ', '0');
}
// Detect the first 1 signifying the end of padding, then remove the first few
// characters, including the 1
for (int i = 0; i < 8; i++) {
if (bitString.charAt(i) == '1') return bitString.substring(i+1);
}
return bitString.substring(8);
}
catch(Exception e) {
System.out.println("Error while reading file!");
return "";
}
}
/*
* Getters used by the driver.
* DO NOT EDIT or REMOVE
*/
public String getFileName() {
return fileName;
}
public ArrayList getSortedCharFreqList() {
return sortedCharFreqList;
}
public TreeNode getHuffmanRoot() {
return huffmanRoot;
}
public String[] getEncodings() {
return encodings;
}
}
TreeNode.java
package huffman;
/**
* This class represents a node of a huffman coding tree,
* and contains a CharFreq object as its data
*
* @author Ishaan Ivaturi
*/
public class TreeNode {
private CharFreq data;
private TreeNode left;
private TreeNode right;
public TreeNode() {
data = null;
left = null;
right = null;
}
public TreeNode(CharFreq d, TreeNode l, TreeNode r) {
data = d;
left = l;
right = r;
}
public CharFreq getData () {
return data;
}
public void setData (CharFreq data) {
this.data = data;
}
public TreeNode getLeft() {
return left;
}
public void setLeft (TreeNode left) {
this.left = left;
}
public TreeNode getRight() {
return right;
}
public void setRight (TreeNode right) {
this.right = right;
}
}
Queue.java
package huffman;
/**
* This class contains a generic queue class which supports
* isEmpty, size, enqueue, dequeue, and peek. It is implemented
* using a circular linked list.
*
* @author Ishaan Ivaturi
*/
public class Queue {
private Node back;
private int size;
private class Node {
T data;
Node next;
public Node(T d, Node n) {
data = d;
next = n;
}
}
public boolean isEmpty() { return size == 0; }
public int size() { return size; }
public void enqueue(T item) {
size++; // Enqueueing increases the size by 1
// If there were no elements before, make a node that points to itself
if (size == 1) {
back = new Node<>(item, null);
back.next = back;
return;
}
// Otherwise, add a node after back and update back
// Represents adding at the end
back.next = new Node<>(item, back.next);
back = back.next;
}
public T dequeue() {
T item = back.next.data;
size--; // Dequeueing decreases the size by 1
// If there are no elements left, just make back null
if (size == 0) {
back = null;
return item;
}
// Otherwise, remove the front of the list (back.next)
back.next = back.next.next;
return item;
}
public T peek() {
// Just return the data of the front of the queue
return back.next.data;
}
}
CharFreq.java
package huffman;
/**
* This class contains a character object, and a double representing
* its probability of occurrence
*
* @author Ishaan Ivaturi
* @author Prince Rawal
*/
public class CharFreq implements Comparable {
private Character character;
private double probOcc;
// We can set both the Character and double at once
public CharFreq(Character c, double p) {
character = c;
probOcc = p;
}
// No arguments makes a null character and prob 0
public CharFreq() { this(null, 0); }
// Allows us to use Collections.sort() to sort by probOcc
public int compareTo(CharFreq cf) {
Double d1 = probOcc, d2 = cf.probOcc;
if (d1.compareTo(d2) != 0) return d1.compareTo(d2);
return character.compareTo(cf.character);
}
// Getters and setters
public Character getCharacter() { return character; }
public double getProbOcc() { return probOcc; }
public void setCharacter(Character c) { character = c; }
public void setProbOcc(double p) { probOcc = p; }
}
Implementation Notes
YOU MAY only update the methods makeSortedList(), makeTree(), makeEncodings(), encode()
and decode().
DO NOT add any instance variables to the HuffmanCoding class.
DO NOT add any public methods to the HuffmanCoding class.
DO NOT use System.exit() in your code.
DO NOT remove the package statement from HuffmanCoding.java
YOU MAY add private methods to the HuffmanCoding class.

More Related Content

PDF
I need help with the last 2 methods only in Huffman.java file the me.pdf
PDF
#include iostream #include cstring #include vector #i.pdf
PDF
Main issues with the following code-Im not sure if its reading the fil.pdf
DOCX
import org-jsoup-Jsoup- import org-jsoup-nodes-Document- import java-.docx
PPT
Java căn bản - Chapter12
PPT
Chapter 12 - File Input and Output
PDF
Frequency .java Word frequency counter package frequ.pdf
PDF
C Programming Project
I need help with the last 2 methods only in Huffman.java file the me.pdf
#include iostream #include cstring #include vector #i.pdf
Main issues with the following code-Im not sure if its reading the fil.pdf
import org-jsoup-Jsoup- import org-jsoup-nodes-Document- import java-.docx
Java căn bản - Chapter12
Chapter 12 - File Input and Output
Frequency .java Word frequency counter package frequ.pdf
C Programming Project

Similar to please navigate to cs112 webpage and go to assignments -- Trees. Th.pdf (20)

PDF
In this lab, we will write an application to store a deck of cards i.pdf
PDF
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
PPTX
Programming in C
PDF
Object Oriented Programming (OOP) using C++ - Lecture 4
PDF
We will be making 4 classes Main - for testing the code Hi.pdf
PDF
I need hlep I have posted this proble 4 times have gotten no help can.pdf
PDF
in c languageTo determine the maximum string length, we need to .pdf
PDF
golang_refcard.pdf
PDF
Create a text file named lnfo.txt. Enter the following informatio.pdf
PDF
Java I/o streams
PDF
5. Ввод-вывод, доступ к файловой системе
DOCX
source code which create file and write into it
PDF
PLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdf
PDF
java question Fill the add statement areaProject is to wo.pdf
DOCX
PDF
For this lab, you will write the following filesAbstractDataCalc.pdf
PPTX
object oriented programming in PHP & Functions
PPT
Jedi Slides Intro2 Chapter12 Advanced Io Streams
PPT
Oop lecture9 11
In this lab, we will write an application to store a deck of cards i.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Programming in C
Object Oriented Programming (OOP) using C++ - Lecture 4
We will be making 4 classes Main - for testing the code Hi.pdf
I need hlep I have posted this proble 4 times have gotten no help can.pdf
in c languageTo determine the maximum string length, we need to .pdf
golang_refcard.pdf
Create a text file named lnfo.txt. Enter the following informatio.pdf
Java I/o streams
5. Ввод-вывод, доступ к файловой системе
source code which create file and write into it
PLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdf
java question Fill the add statement areaProject is to wo.pdf
For this lab, you will write the following filesAbstractDataCalc.pdf
object oriented programming in PHP & Functions
Jedi Slides Intro2 Chapter12 Advanced Io Streams
Oop lecture9 11

More from aioils (20)

PDF
Please help solve! Suppose that X is an exponential random variable .pdf
PDF
Please help me with a UML class diagram for the following code im.pdf
PDF
Please help me i will give good rating a) A wheel has 37 numbers 0.pdf
PDF
Please help me answer this question.Explain how oxygen content acc.pdf
PDF
PLEASE HELP IN C++For this test, you will need to create the follo.pdf
PDF
please help and thank you ! Experiments by Murphy et al. (2014) on t.pdf
PDF
PLEASE HELP (also please dont answer with path because there is no .pdf
PDF
please explain these topics if possible How companies account for.pdf
PDF
Pls introduced to various themes and theoretical issues pertaining t.pdf
PDF
please! 1. Match and pair the following basic genetic conce.pdf
PDF
Please write out steps )You have genotyped an entire population o.pdf
PDF
Please write out the steps )_You have genotyped an entire populat.pdf
PDF
Please Use The Code Provided below. Thanks Study the Python code .pdf
PDF
Please Use the Code Provided below. Thanks Visit LL Queue ; add.pdf
PDF
Please this is very important Im on a deadline The joint probabilit.pdf
PDF
Please solve. In the Assembly Department of Martinez Company, budget.pdf
PDF
Please do parts labeled TODO LinkedList.java Replace.pdf
PDF
Please do Part A, Ill be really gratefulThe main.c is the skeleto.pdf
PDF
Please do number 1 as its my choice for this project but, if there.pdf
PDF
Please show workstepsYou have genotyped an entire population of l.pdf
Please help solve! Suppose that X is an exponential random variable .pdf
Please help me with a UML class diagram for the following code im.pdf
Please help me i will give good rating a) A wheel has 37 numbers 0.pdf
Please help me answer this question.Explain how oxygen content acc.pdf
PLEASE HELP IN C++For this test, you will need to create the follo.pdf
please help and thank you ! Experiments by Murphy et al. (2014) on t.pdf
PLEASE HELP (also please dont answer with path because there is no .pdf
please explain these topics if possible How companies account for.pdf
Pls introduced to various themes and theoretical issues pertaining t.pdf
please! 1. Match and pair the following basic genetic conce.pdf
Please write out steps )You have genotyped an entire population o.pdf
Please write out the steps )_You have genotyped an entire populat.pdf
Please Use The Code Provided below. Thanks Study the Python code .pdf
Please Use the Code Provided below. Thanks Visit LL Queue ; add.pdf
Please this is very important Im on a deadline The joint probabilit.pdf
Please solve. In the Assembly Department of Martinez Company, budget.pdf
Please do parts labeled TODO LinkedList.java Replace.pdf
Please do Part A, Ill be really gratefulThe main.c is the skeleto.pdf
Please do number 1 as its my choice for this project but, if there.pdf
Please show workstepsYou have genotyped an entire population of l.pdf

Recently uploaded (20)

PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
Computing-Curriculum for Schools in Ghana
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
Pre independence Education in Inndia.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
TR - Agricultural Crops Production NC III.pdf
PPTX
Institutional Correction lecture only . . .
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
Insiders guide to clinical Medicine.pdf
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
Cell Structure & Organelles in detailed.
PDF
Classroom Observation Tools for Teachers
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Final Presentation General Medicine 03-08-2024.pptx
Microbial disease of the cardiovascular and lymphatic systems
Computing-Curriculum for Schools in Ghana
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
O5-L3 Freight Transport Ops (International) V1.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Anesthesia in Laparoscopic Surgery in India
Pre independence Education in Inndia.pdf
human mycosis Human fungal infections are called human mycosis..pptx
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
TR - Agricultural Crops Production NC III.pdf
Institutional Correction lecture only . . .
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Insiders guide to clinical Medicine.pdf
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
STATICS OF THE RIGID BODIES Hibbelers.pdf
Cell Structure & Organelles in detailed.
Classroom Observation Tools for Teachers

please navigate to cs112 webpage and go to assignments -- Trees. Th.pdf

  • 1. please navigate to cs112 webpage and go to assignments --> Trees. This will give you the directions for the assignment. Please do the last 2 methods in huffman.java called encode() and decode() Code is provided below: HuffmanCoding.java package huffman; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.Collections; /** * This class contains methods which, when used together, perform the * entire Huffman Coding encoding and decoding process * * @author Ishaan Ivaturi * @author Prince Rawal */ public class HuffmanCoding { private String fileName; private ArrayList sortedCharFreqList; private TreeNode huffmanRoot; private String[] encodings; /** * Constructor used by the driver, sets filename * DO NOT EDIT * @param f The file we want to encode */ public HuffmanCoding(String f) { fileName = f; } /** * Reads from filename character by character, and sets sortedCharFreqList * to a new ArrayList of CharFreq objects with frequency > 0, sorted by frequency */
  • 2. public void makeSortedList() { StdIn.setFile(fileName); /* Your code goes here */ } /** * Uses sortedCharFreqList to build a huffman coding tree, and stores its root * in huffmanRoot */ public void makeTree() { /* Your code goes here */ } /** * Uses huffmanRoot to create a string array of size 128, where each * index in the array contains that ASCII character's bitstring encoding. Characters not * present in the huffman coding tree should have their spots in the array left null. * Set encodings to this array. */ public void makeEncodings() { /* Your code goes here */ } /** * Using encodings and filename, this method makes use of the writeBitString method * to write the final encoding of 1's and 0's to the encoded file. * * @param encodedFile The file name into which the text file is to be encoded */ public void encode(String encodedFile) { StdIn.setFile(fileName); /* Your code goes here */ } /** * Writes a given string of 1's and 0's to the given file byte by byte * and NOT as characters of 1 and 0 which take up 8 bits each * DO NOT EDIT *
  • 3. * @param filename The file to write to (doesn't need to exist yet) * @param bitString The string of 1's and 0's to write to the file in bits */ public static void writeBitString(String filename, String bitString) { byte[] bytes = new byte[bitString.length() / 8 + 1]; int bytesIndex = 0, byteIndex = 0, currentByte = 0; // Pad the string with initial zeroes and then a one in order to bring // its length to a multiple of 8. When reading, the 1 signifies the // end of padding. int padding = 8 - (bitString.length() % 8); String pad = ""; for (int i = 0; i < padding-1; i++) pad = pad + "0"; pad = pad + "1"; bitString = pad + bitString; // For every bit, add it to the right spot in the corresponding byte, // and store bytes in the array when finished for (char c : bitString.toCharArray()) { if (c != '1' && c != '0') { System.out.println("Invalid characters in bitstring"); return; } if (c == '1') currentByte += 1 << (7-byteIndex); byteIndex++; if (byteIndex == 8) { bytes[bytesIndex] = (byte) currentByte; bytesIndex++; currentByte = 0; byteIndex = 0; } } // Write the array of bytes to the provided file try { FileOutputStream out = new FileOutputStream(filename); out.write(bytes);
  • 4. out.close(); } catch(Exception e) { System.err.println("Error when writing to file!"); } } /** * Using a given encoded file name, this method makes use of the readBitString method * to convert the file into a bit string, then decodes the bit string using the * tree, and writes it to a decoded file. * * @param encodedFile The file which has already been encoded by encode() * @param decodedFile The name of the new file we want to decode into */ public void decode(String encodedFile, String decodedFile) { StdOut.setFile(decodedFile); /* Your code goes here */ } /** * Reads a given file byte by byte, and returns a string of 1's and 0's * representing the bits in the file * DO NOT EDIT * * @param filename The encoded file to read from * @return String of 1's and 0's representing the bits in the file */ public static String readBitString(String filename) { String bitString = ""; try { FileInputStream in = new FileInputStream(filename); File file = new File(filename); byte bytes[] = new byte[(int) file.length()]; in.read(bytes); in.close();
  • 5. // For each byte read, convert it to a binary string of length 8 and add it // to the bit string for (byte b : bytes) { bitString = bitString + String.format("%8s", Integer.toBinaryString(b & 0xFF)).replace(' ', '0'); } // Detect the first 1 signifying the end of padding, then remove the first few // characters, including the 1 for (int i = 0; i < 8; i++) { if (bitString.charAt(i) == '1') return bitString.substring(i+1); } return bitString.substring(8); } catch(Exception e) { System.out.println("Error while reading file!"); return ""; } } /* * Getters used by the driver. * DO NOT EDIT or REMOVE */ public String getFileName() { return fileName; } public ArrayList getSortedCharFreqList() { return sortedCharFreqList; } public TreeNode getHuffmanRoot() { return huffmanRoot; } public String[] getEncodings() { return encodings; } }
  • 6. TreeNode.java package huffman; /** * This class represents a node of a huffman coding tree, * and contains a CharFreq object as its data * * @author Ishaan Ivaturi */ public class TreeNode { private CharFreq data; private TreeNode left; private TreeNode right; public TreeNode() { data = null; left = null; right = null; } public TreeNode(CharFreq d, TreeNode l, TreeNode r) { data = d; left = l; right = r; } public CharFreq getData () { return data; } public void setData (CharFreq data) { this.data = data; } public TreeNode getLeft() {
  • 7. return left; } public void setLeft (TreeNode left) { this.left = left; } public TreeNode getRight() { return right; } public void setRight (TreeNode right) { this.right = right; } } Queue.java package huffman; /** * This class contains a generic queue class which supports * isEmpty, size, enqueue, dequeue, and peek. It is implemented * using a circular linked list. * * @author Ishaan Ivaturi */ public class Queue { private Node back; private int size; private class Node { T data; Node next; public Node(T d, Node n) { data = d;
  • 8. next = n; } } public boolean isEmpty() { return size == 0; } public int size() { return size; } public void enqueue(T item) { size++; // Enqueueing increases the size by 1 // If there were no elements before, make a node that points to itself if (size == 1) { back = new Node<>(item, null); back.next = back; return; } // Otherwise, add a node after back and update back // Represents adding at the end back.next = new Node<>(item, back.next); back = back.next; } public T dequeue() { T item = back.next.data; size--; // Dequeueing decreases the size by 1 // If there are no elements left, just make back null if (size == 0) { back = null; return item; } // Otherwise, remove the front of the list (back.next) back.next = back.next.next; return item; } public T peek() { // Just return the data of the front of the queue
  • 9. return back.next.data; } } CharFreq.java package huffman; /** * This class contains a character object, and a double representing * its probability of occurrence * * @author Ishaan Ivaturi * @author Prince Rawal */ public class CharFreq implements Comparable { private Character character; private double probOcc; // We can set both the Character and double at once public CharFreq(Character c, double p) { character = c; probOcc = p; } // No arguments makes a null character and prob 0 public CharFreq() { this(null, 0); } // Allows us to use Collections.sort() to sort by probOcc public int compareTo(CharFreq cf) { Double d1 = probOcc, d2 = cf.probOcc; if (d1.compareTo(d2) != 0) return d1.compareTo(d2); return character.compareTo(cf.character); } // Getters and setters public Character getCharacter() { return character; } public double getProbOcc() { return probOcc; }
  • 10. public void setCharacter(Character c) { character = c; } public void setProbOcc(double p) { probOcc = p; } } Implementation Notes YOU MAY only update the methods makeSortedList(), makeTree(), makeEncodings(), encode() and decode(). DO NOT add any instance variables to the HuffmanCoding class. DO NOT add any public methods to the HuffmanCoding class. DO NOT use System.exit() in your code. DO NOT remove the package statement from HuffmanCoding.java YOU MAY add private methods to the HuffmanCoding class.