【问题标题】:Huffman Coding - Grouping Symbols霍夫曼编码 - 分组符号
【发布时间】:2015-04-11 04:14:11
【问题描述】:

我正在使用在 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());
}

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

有什么帮助吗?

谢谢

【问题讨论】:

  • 欢迎来到 StackOverflow。目前尚不完全清楚你的问题是什么。预期结果是什么?这与您得到的结果有何不同?

标签: java symbols huffman-code frequency-distribution


【解决方案1】:

一种相当简单的方法,您可以使用 Java 8 流(如果您可以使用它们)来做到这一点:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多