Skip to content

Instantly share code, notes, and snippets.

@tareq-si-salem
Created August 5, 2016 17:31
Show Gist options
  • Save tareq-si-salem/840780e6a8f94d744ba2f74a83c22486 to your computer and use it in GitHub Desktop.
Save tareq-si-salem/840780e6a8f94d744ba2f74a83c22486 to your computer and use it in GitHub Desktop.
Huffman code algorithm implementation
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// create a new file
File file = new File("testFile.txt");
// handel the checked exception "FileNotFoundException"
try {
// A scanner to get file content Text I/O
Scanner in = new Scanner(file);
// string builder is preferable than
// appending a string whereas a string creates
// a new instance each time we append
StringBuilder builder = new StringBuilder();
// while we haven't reached the end of the stream
while (in.hasNext()) {
// append the line read from file
builder.append(in.nextLine());
}
// obtain file content as an array of characters
char[] charContent = builder.toString().toCharArray();
ArrayList<Character> charactersList = new ArrayList<>();
ArrayList<Integer> weightsList = new ArrayList<>();
// to lists to store both distinct character and their weights
int index;
for (int i = 0; i < charContent.length; i++) {
if ((index = charactersList.indexOf(charContent[i])) >= 0) {
// the character exists in the list
// increment its weight
weightsList.set(index, weightsList.get(index) + 1);
} else {
// character doesn't exist in the list
// add it
// and assign weight 1
charactersList.add(charContent[i]);
weightsList.add(1);
}
}
char[] characters = new char[charactersList.size()];
int[] weights = new int[weightsList.size()];
for (int i = 0; i < charactersList.size(); i++) {
characters[i] = charactersList.get(i);
weights[i] = weightsList.get(i);
// obtain a fixed size array from the two array lists
}
// start the huffman generatir
HuffmanCodeGenerator generator = new HuffmanCodeGenerator(characters, weights);
generator.printResult(charContent);
} catch (FileNotFoundException ex) {
System.out.println("File not found");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment