我正在使用Internet上的霍夫曼代码来获取以矩阵形式存储在2D数组中的随机整数的频率。

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

10-08 19:22