0

I am using a Huffman code found on the Internet to get the frequencies of random integers stored in a 2D array as a matrix.

Link to Huffman code - Java: http://rosettacode.org/wiki/Huffman_coding

Method Q1 asks the user to set the matrix size. The matrix is filled with random integers [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();
}

Method Q2 needs to re-display all random integers found in the matrix and their frequency.

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());
}

The current program calculates the frequency by splitting the random integers into seperate digits. I need the frequency to be calculated upon each of the random integers.

Any help please?

Thank you

CMM29
  • 1
  • Welcome to StackOverflow. It's not entirely clear what your question is. What is the expected result and how is that different from the result you're getting? – genisage Feb 10 '15 at 23:04

1 Answers1

1

A fairly simple way you can do this using Java 8 streams (if they are available to you):

Map<Integer, Integer> frequencies = Arrays.stream(matrix)
    .flatMap(Arrays::stream)
    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting());
sprinter
  • 27,148
  • 6
  • 47
  • 78