0
我使用互聯網上發現的霍夫曼編碼來獲取作爲矩陣存儲在二維數組中的隨機整數的頻率。霍夫曼編碼 - 分組符號
鏈接霍夫曼碼 - Java的:http://rosettacode.org/wiki/Huffman_coding
方法Q1要求用戶設置的矩陣大小。該矩陣填充隨機整數[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();
}
方法Q2需要重新顯示在矩陣中找到的所有隨機整數及其頻率。
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());
}
當前程序通過將隨機整數分成單獨的數字來計算頻率。我需要計算每個隨機整數的頻率。
請幫忙嗎?
謝謝
歡迎StackOverflow上。目前還不完全清楚你的問題是什麼。預期的結果是什麼,它與你得到的結果有什麼不同? – genisage 2015-02-10 23:04:56