Reputation: 8047
I am looking for the most common value from the 2D array and how many times it occurs. I tried this solution but it's not working. I tried searching but not able to find a proper example. Please help me solve this problem.
Here is my code:
private void commonElevation(int[][] data) {
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
if (i + 1 < data.length) {
if (data[i][j] == data[i + 1][j]) {
System.out.println(data[i][j] + " = " + data[i + 1][j]);
}
}
}
}
}
Upvotes: 1
Views: 534
Reputation: 61910
You could use the Stream API:
int[][] data = {{1, 2, 3}, {2, 2, 2}, {4, 5, 6}};
Map<Integer, Long> counts = Arrays.stream(data).flatMapToInt(Arrays::stream).boxed()
.collect(groupingBy(Function.identity(), counting()));
Optional<Map.Entry<Integer, Long>> max = counts.entrySet().stream().max(Comparator.comparing(Map.Entry::getValue));
max.ifPresent(System.out::println);
Output
2=4
Given the new constraints a brute-force approach will work:
// find the maximum
int value = 0, max = Integer.MIN_VALUE;
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
// search for counts
int currentCount = 0;
for (int k = 0; k < data.length; k++) {
for (int l = 0; l < data[k].length; l++) {
if(data[k][l] == data[i][j]) {
currentCount++;
}
}
}
if (currentCount > max) {
value = data[i][j];
max = currentCount;
}
}
}
System.out.println(value + "=" + max);
Output
2=4
Basically iter over all values and count the appearances of each of those values. This approach (brute-force) is very inefficient.
Upvotes: 2
Reputation: 521249
One possibility would be to use a hash map to keep track of the values along with the number of times each occurs:
private void commonElevation(int[][] data) {
Map<Integer, Integer> counts = new HashMap<>();
for (int i=0; i < data.length; i++) {
for (int j=0; j < data[i].length; j++) {
int count = counts.get(data[i][j]) == null ? 0 : counts.get(data[i][j]);
counts.put(data[i][j], ++count);
}
}
int frequent = Integer.MIN_VALUE;
for (Integer value : counts.values()) {
if (value > frequent) frequent = value;
}
System.out.println("most frequent value is: " + frequent);
}
Upvotes: 0