I need to write my own function that returns the most repeated value of the array.
I have an array, and I need to count statistical fashion (mode, which is the most repeated value in array) and I don’t know why it’s not working.
I create 2 arrays:
The first contains the values, and the second array I want to insert how many times each value from first array are repeated, then by my function, findmax, I search for the biggest index of repeated value, and then finally show a message with the mode.
public int findmax(Integer [] somearray) {
int max = somearray[0];
int z=0;
for (int i = 0; i < somearray.length; i++) {
if (somearray[i]>max){
max = somearray[i];
z = i;
}
}
return z;
}
private void myModaActionPerformed(java.awt.event.ActionEvent evt) {
Double [] myarray = new Double[dsTable.getRowCount()];
Integer [] myarray2 = new Integer[dsTable.getRowCount()];
for (int i=0; i < myarray.length; i++){
myarray[i] = (Double)dsTable.getModel().getValueAt(i, 0);
}
java.util.Arrays.sort(myarray);
for (int i = 0; i < myarray.length; i++){
JOptionPane.showMessageDialog(this.mainPanel,((Double)myarray[i]));
}
for (int i = 0; i < myarray2.length; i++){
myarray2[i]=0;
}
for (int i = 0; i < myarray.length; i++){
for (int j = 0; j < myarray.length; j++){
if (myarray[i] == myarray[j]){
myarray2[i]++;
}
}
}
JOptionPane.showMessageDialog(this.mainPanel,myarray[findmax(myarray2)]);
}
The result of program is first value of the first array.
Seems like your homework, so I’ll give you some pointers to help you out.
Consider using a HashMap. Here the key would be numbers in your first array and value would be count for each value that you encounter. So the first time you encounter a number, add it to the map, and for every subsequent time, you just increment the value
Once you’ve this map, it would be trivial to find out the key which has the maximum value. Also note that there might be more than one key that can have that maximal value, so you might want to handle that case as well.
One more hint: The way you’re incrementing your second array seems incorrect. You might want to revisit your logic over there as well.