I have the following program which looks up an array "a" and then output the value in the array which appears the most frequently. However one other condition that I would like to implement is that in the case of a tie where two different values appear an equal amount of times, the lowest value gets output.
So for the following code with an array:
int a[] = {34, 34, 20, 20, 15};
It outputs 34 however I want it to output 20 instead, since that is a lower value and appears just as many times in the array.
public class Arrays3 {
public static void main(String[] args){
int a[] = {34, 34, 20, 20, 15};
mode(a);
}
public static int mode(int[] a) {
int[] counts = new int[101];
int maxCount = 0;
int maxKey = 0;
for(int i = 0; i < a.length; i++) {
counts[a[i]]++;
if(counts[a[i]] > maxCount) {
maxCount = counts[a[i]];
maxKey = a[i];
}
}
System.out.println(maxKey);
return maxKey;
}
}
You could check against maxKey
and then do something along the lines of:
if(counts[a[i]] == maxCount && counts[a[i]] < maxKey) {
maxKey = counts[a[i]];
}
So that if there is ever a tie, the maxKey
will be set to the smaller element. Then if count[a[i]]
is ever greater than maxCount
, maxKey
will be overridden and become the element that occurs most often:
for(int i = 0; i < a.length; i++) {
counts[a[i]]++;
if(counts[a[i]] > maxCount) {
maxCount = counts[a[i]];
maxKey = a[i];
}
if(counts[a[i]] == maxCount && counts[a[i]] < maxKey) {
maxKey = a[i];
}
}
System.out.println(a[maxKey]);
Output
20