Green University of Bangladesh
Department of Computer Science and Engineering (CSE)
Faculty of Sciences and Engineering
Semester: (Fall, Year:2024), B.Sc. in CSE (Day)
CLP – 07
Course Title: Algorithms Lab
Course Code: CSE 206 Section: 223 D2
Task: Huffman Coding
Student Details
Name ID
1. Majedul Islam Shakib 222902025
Lab Date : 29-11-2024 AD
Submission Date : 29-11-2024 AD
Course Teacher’s Name : Md. Abu Rumman Refat
Report Status
Marks: ………………………………… Signature:.....................
Comments:.............................................. Date:..............................
Java Code for the given Assignment on Huffman coding:
import java.util.PriorityQueue;
import java.util.Comparator;
import java.util.Scanner;
class HuffmanNode {
int item;
char c;
HuffmanNode left;
HuffmanNode right;
}
class ImplementComparator implements Comparator<HuffmanNode> {
public int compare(HuffmanNode x, HuffmanNode y) {
return x.item - y.item;
}
}
public class Main {
private static int totalBits = 0;
public static void printCode(HuffmanNode root, String s) {
if (root.left == null && root.right == null && Character.isLetter(root.c)) {
totalBits += s.length() * root.item;
System.out.println(root.c + " | " + s);
return;
}
printCode(root.left, s + "0");
printCode(root.right, s + "1");
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of characters: ");
int n = scanner.nextInt();
char[] charArray = new char[n];
int[] charfreq = new int[n];
System.out.println("Enter the characters:");
for (int i = 0; i < n; i++) {
charArray[i] = scanner.next().charAt(0);
}
System.out.println("Enter the corresponding frequencies for the characters:");
for (int i = 0; i < n; i++) {
charfreq[i] = scanner.nextInt();
}
PriorityQueue<HuffmanNode> q = new PriorityQueue<HuffmanNode>(n, new ImplementComparator());
for (int i = 0; i < n; i++) {
HuffmanNode hn = new HuffmanNode();
hn.c = charArray[i];
hn.item = charfreq[i];
hn.left = null;
hn.right = null;
q.add(hn);
}
HuffmanNode root = null;
while (q.size() > 1) {
HuffmanNode x = q.peek();
q.poll();
HuffmanNode y = q.peek();
q.poll();
HuffmanNode f = new HuffmanNode();
f.item = x.item + y.item;
f.c = '-';
f.left = x;
f.right = y;
root = f;
q.add(f);
}
System.out.println("Char | Code");
System.out.println("-------------");
printCode(root, "");
double averageLength = (double) totalBits / n;
System.out.println("\nAverage Code Length: " + averageLength);
System.out.println("Total Huffman Encoded Message Length (in decimal): " + totalBits);
System.out.println("Total Huffman Encoded Message Length (in binary): " + Integer.toBinaryString(totalBits));
scanner.close();
}
}
Output:
Figure: Huffman Output