If you know in advance that that the numbers are in a specified range (i.e. from 1 to 13, according to your code), you can adopt a simple solution like the one from Peter Tillemans.
Another solution is to use a Map
to store the frequencies of the numbers contained in the matrix.
public static Map<Integer, Integer> frequency(int[][] matrix) {
Map<Integer, Integer> frequencies = new HashMap<Integer, Integer>();
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
Integer frequency = 0;
if (frequencies.containsKey(matrix[i][j])) {
frequency = frequencies.get(matrix[i][j]);
}
frequencies.put(matrix[i][j], frequency + 1);
}
}
return frequencies;
}
If exposing the Map
interface to the external code is not what you want, you can also write a custom data type to hold the results. In this way, you can hide the implementation of the results (arrays, maps, or anything else) and provide only the methods you really need.
public class FrequencyResults {
private Map<Integer, Integer> frequencies;
public FrequencyResults() {
frequencies = new HashMap<Integer, Integer>();
}
public void increment(int number) {
Integer frequency = 0;
if (frequencies.containsKey(number)) {
frequency = frequencies.get(number);
}
frequencies.put(number, frequency + 1);
}
public int get(int number) {
Integer frequency = 0;
if (frequencies.containsKey(number)) {
frequency = frequencies.get(number);
}
return frequency;
}
}
Using this data type, the frequency
function evolves in the following code. I think that, with this small rewriting, you can express more effectively what your code does.
public static FrequencyResults frequency(int[][] matrix) {
FrequencyResults results = new FrequencyResults();
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
results.increment(matrix[i][j]);
}
}
return results;
}