I'm fairly new to java and have been stuck on this assignment in which I had to create three functions (mean, median and mode) and return and print the mean, median and mode. I completed the mean and median but am stuck on the mode. My code runs correctly if there is one mode but it doesn't print out multiple modes and I would also like it to output a blank space if there are no modes.
private static int mode(int [] arr){ // Function calculates mode
int mf = -1, maxcount = 0, i, j; // Declaring Variables
for (i = 0; i < arr.length; i ){
int count = 0; // Current count
for (j = i 1; j < arr.length; j ){
if(arr[i] == arr[j]){ // Compares indexes
count ; // Increments count by 1
}
}
if(count > maxcount){
maxcount = count;
mf = arr[i];
}
}
if(mf == -1){
return 0;
} else {
return mf;
}
}
CodePudding user response:
Here as you're using two for loops the complexity becomes O(n^2). You can do it in just O(n) as an improvement as you need.
private int[] mode(int[] arr) {
if(arr.length==0) return new int[]{};
Map<Integer, Integer> map=new HashMap<>();
int maxCount=0;
int maxVal=0;
for(int i: arr) {
int curr=map.getOrDefault(i, 0);
if(curr 1==maxVal) {
maxCount ;
} else if(curr 1>maxVal) {
maxCount=1;
maxVal=curr 1;
}
map.put(i, curr 1);
}
int[] resu=new int[maxCount];
int j=0;
Iterator<Integer> it=map.keySet().iterator();
while(it.hasNext()) {
int v=it.next();
if(map.get(v)==maxVal) {
resu[j]=v;
j ;
}
}
return resu;
}
Here, if the input array is empty, we are returning empty array. Furthermore if you have any idea on the input array range, instead of using a map, we can use an array as well (if the range is less).
private int[] mode(int[] arr) {
if(arr.length==0) return new int[]{};
int[] track=new int[100]; // range, here considering 0-99
int maxCount=0;
int maxVal=0;
for(int i: arr) {
track[i];
if(track[i]>maxVal) {
maxVal=track[i];
maxCount=1;
} else if(track[i]==maxVal) {
maxCount ;
}
}
int[] resu=new int[maxCount];
int j=0;
for(int i=0; i<track.length; i ) {
if(track[i]==maxVal) {
resu[j]=i;
j ;
}
}
return resu;
}
CodePudding user response:
Your mode()
method is right. Just you have to put condition in main method. If array return 0
then print No Mode Found
otherwise get mode
.
Here down is condition:
public static void main(String[] args) {
int arr[] = {0, 6, 7, 2, 8};
String foundOrNot = (mode(arr) == 0) ? "No Mode Found" : String.valueOf(mode(arr));
System.out.println(foundOrNot);
}