0

我正在使用在 Internet 上找到的 Huffman 代码来获取以矩阵形式存储在 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());
}

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

请问有什么帮助吗?

谢谢

4

1 回答 1

1

一种相当简单的方法,您可以使用 Java 8 流(如果您可以使用它们)来执行此操作:

Map<Integer, Integer> frequencies = Arrays.stream(matrix)
    .flatMap(Arrays::stream)
    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting());
于 2015-02-10T23:12:17.793 回答