I am using a Huffman code found on the Internet to get the frequencies of random integers stored in a 2D array as a matrix.
Link to Huffman code - Java: http://rosettacode.org/wiki/Huffman_coding
Method Q1 asks the user to set the matrix size. The matrix is filled with random integers [0, 255].
public void q1(){
System.out.println();
System.out.println("Question 1 - Creating Random Matrix");
Scanner in = new Scanner(System.in);
//Matrix number of rows
System.out.print("Insert size of rows M: ");
rows = in.nextInt();
//Matrix number of columns
System.out.print("Insert size of columns N: ");
columns = in.nextInt();
System.out.println();
matrix = new int[rows][columns];
//Initialising randomisation
Random r = new Random();
//Filling matrix and printing values
for (int m = 0; m < rows; m++){
for (int n = 0; n < columns; n++){
matrix[m][n] = r.nextInt(256);
System.out.print("[" + matrix[m][n] + "] \t");
}
System.out.print("\n");
}
System.out.println();
}
Method Q2 needs to re-display all random integers found in the matrix and their frequency.
public void q2() {
// we will assume that all our characters will have code less than 256, for simplicity
int[] charFreqs = new int[256];
StringBuilder sb = new StringBuilder();
String [] st = new String[5];
System.out.println();
System.out.println("Alphabet " + "\t" + "Frequency" + "\t" + "Probability");
for (int m = 0; m < rows; m++){
for (int n = 0; n < columns; n++){
String sentence = String.valueOf(matrix[m][n]);
System.out.print(matrix[m][n] + "\n");
//read each character and record the frequencies
for (int i = 0; i < sentence.length(); i++){
char c = sb.append(sentence[i]);
}
for (char c : sentence.toCharArray()){
charFreqs[c]++;
}
}
}
// build tree
HuffmanTree tree = buildTree(charFreqs);
// print out results
System.out.println("SYMBOL\tWEIGHT\tHUFFMAN CODE");
printCodes(tree, new StringBuffer());
}
The current program calculates the frequency by splitting the random integers into seperate digits. I need the frequency to be calculated upon each of the random integers.
Any help please?
Thank you