I need a help in making a method that will Input a text that will be converted to Huffman code and Input a Huffman code that will be converted to its text equivalent.
I need a help in making a method that will Input a text that will be converted to Huffman code and Input a Huffman code that will be converted to its text equivalent.
You can try this sample Character input: HAAHAABAAACACAAAABABABEBEBBAABEEBBCCCCCAAAAAAACCCDDDDDDAAADDDDDEEEEEEDDADDDADDEEEEEEEECCCEEEEEEEEEEDDEEEEEEEEEEBBEEEEEFFGGHAHHEEHHA
Huffman.java
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.Comparator;
import java.util.ArrayList;
class HuffmanNode {
int data;
char c;
HuffmanNode left;
HuffmanNode right;
}
class MyComparator implements Comparator<HuffmanNode> {
public int compare(HuffmanNode x, HuffmanNode y) {
return x.data - y.data;
}
}
public class Huffman {
public static void printCode(HuffmanNode root, String s) {
if (root.left == null && root.right == null && Character.isLetter(root.c)) {
System.out.println(s + "tttt"+ s.length());
return;
}
printCode(root.left, s + "0");
printCode(root.right, s + "1");
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Input a series of characters to be converted into Huffman code");
System.out.print("Input text: ");
String str = keyboard.nextLine();
char[] ch = str.toCharArray();
ArrayList<Character> characters = new ArrayList<Character>();
for (int i = 0; i < ch.length; i++) {
if (!(characters.contains(ch[i]))) {
characters.add(ch[i]);
}
}
int[] countOfChar = new int[characters.size()];
for (int x = 0; x < countOfChar.length; x++) {
countOfChar[x] = 0;
}
for (int i = 0; i < characters.size(); i++) {
char checker = characters.get(i);
for (int x = 0; x < ch.length; x++) {
if (checker == ch[x]) {
countOfChar[i]++;
}
}
}
int n = countOfChar.length;
System.out.println("Characters Number of occurrence of the character in the text");
for (int x = 0; x < countOfChar.length; x++) {
System.out.println(characters.get(x) + "ttt" + countOfChar[x]);
}
System.out.println("nHuffman Node Number of Bits");
PriorityQueue<HuffmanNode> q = new PriorityQueue<HuffmanNode>(n, new MyComparator());
for (int i = 0; i < n; i++) {
HuffmanNode hn = new HuffmanNode();
hn.c =characters.get(i);
hn.data=countOfChar[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.data = x.data + y.data;
f.c = '-';
f.left = x;
f.right = y;
root = f;
q.add(f);
}
printCode(root, "");
}
}
Step by step
Solved in 2 steps