Java – find integer patterns in arrays
For this problem, I will write a method called mode, which returns the most common element in an integer array Suppose that the array has at least one element, and each element in the array has a value between 0 and 100 (including 0 and 100) Break the relationship by choosing a lower value
For example, if the array passed contains the value {27,15,11,27}, your method should return 15 (Note: you may want to check the tally program earlier in this chapter to find out how to solve this problem.)
I'm having trouble viewing errors for specific inputs For example:
The mode ({27,27,14,16,19,99100,27}) returns 15, which is correct, but the mode ({1,1,2,3,3}} returns 3 when it should be 1
This is the code:
public static int mode(int[] input) { int returnVal = input[0]; // stores element to be returned int repeatCount = 0; // counts the record number of repeats int prevRepCnt = 0; // temporary count for repeats for (int i=0; i<input.length; i++) { // goes through each elem for (int j=i; j<input.length; j++) { // compares to each elem after the first elem if (i != j && input[i] == input[j]) { // if matching values repeatCount++; // gets the repeat count if (repeatCount>=prevRepCnt) { // a higher count of repeats than before returnVal=input[i]; // return that element } prevRepCnt = repeatCount; // Keeps the highest repeat record } repeatCount=0; // resets repeat Count for next comparison } } return returnVal; }
Solution
This is a simpler way to solve this problem Create a 101 - size array named count The index (0-100) represents the number you calculated Traverse the input array and count the number of occurrences of each number Finally, compare the counts to find the most (the tie becomes a lower number):
public static int mode(int[] input) { int[] count = new int[101]; //count the occurrences for (int i=0; i < input.length; i++) { count[input[i]]++; } //go backwards and find the count with the most occurrences int index = count.length-1; for (int i=count.length-2; i >=0; i--) { if (count[i] >= count[index]) index = i; } return index; }