霍夫曼编码 - 分组符号

时间:2015-02-10 22:48:17

标签: java symbols huffman-code frequency-distribution

我正在使用互联网上的霍夫曼代码来获取存储在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());
}

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

请帮忙吗?

谢谢

1 个答案:

答案 0 :(得分:1)

使用Java 8流(如果它们可用),您可以使用相当简单的方法:

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