gpt4 book ai didi

java - 霍夫曼编码 - 符号分组

转载 作者:行者123 更新时间:2023-12-01 11:55:57 27 4
gpt4 key购买 nike

我正在使用在互联网上找到的霍夫曼代码来获取以矩阵形式存储在二维数组中的随机整数的频率。

链接到霍夫曼代码 - 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());
}

当前程序通过将随机整数拆分为单独的数字来计算频率。我需要根据每个随机整数计算频率。

请问有什么帮助吗?

谢谢

最佳答案

使用 Java 8 流(如果可用)可以实现此目的的一种相当简单的方法:

Map<Integer, Integer> frequencies = Arrays.stream(matrix)
.flatMap(Arrays::stream)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting());

关于java - 霍夫曼编码 - 符号分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28443381/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com