I'm trying to complete an assignment where I have to find the mode of a random array. I have figured out how to get the mode for a single number, although I do not know how to find the mode for multiple numbers. For example, if I had the array [2, 2, 3, 3, 4] the mode would be 2 and 3. Here is my code so far:
//Getting our random array
Random r = new Random();
int[] arr = new int[15];
for(int i = 0; i < arr.length; i++) {
arr[i] = r.nextInt(15, 51);
System.out.print(arr[i]);
if(i < arr.length -1)
{
System.out.print(", ");
} else {
System.out.println();
}
}
//Mode
int maxnumber = -1;
int maxappearances = -1;
for (int i=0; i < arr.length; i++)
{
int count = 0;
for (int j=0; j < arr.length; j++)
{
if(arr[i] == arr[j])
{
count++;
}
}
if(count > maxappearances)
{
maxnumber = arr[i];
maxappearances = count;
count = -1;
}
}
System.out.println("The mode is "+ maxnumber);
Output:
15, 21, 21, 47, 46, 44, 49, 45, 29, 31, 16, 36, 19, 17, 20
The mode is 21
If I could get some help that would be great, thanks!
Aucun commentaire:
Enregistrer un commentaire