简体   繁体   中英

Finding the mode of a randomly generated array of 10 numbers

I'm attempting to make this program

public class Statistics {

    public static void main(String[] args) {
        final int SIZE = 10;
        int sum =0;

        int[] numArray= new int [SIZE];

        for (int c=0; c < SIZE; c++)
        {
            numArray[c]=(int)(Math.random()*6+1);
            System.out.print( numArray[c]+   " ");

            sum+=numArray[c];
        }

        System.out.println("\nSum of all numbers is " + sum);
        System.out.println("\n Mean of numbers is " + (sum) / 5);
    }
}

Calculate the mode of the randomly generated array.

I've seen source codes posted where they use a seperate method called computemode, but I don't kno where to place this second method within my code. I'm sorry, I am very very green when it comes to programming. I'm being taught Java as my first language and so far its overwhelming.

If someone could post the syntax with detailed instruction/explanation I'd be so grateful.

The mode is quite easy to compute. One way, assuming your inputs are bounded, is to simply have an array that tracks the number of occurrences of each number:

int[] data; //your data bounded by 0 and MAX_VALUE
int[] occurrences = new int[MAX_VALUE+1];

for ( int datum : data ) {
    occurrences[newNumber]++;
}

Then figure out the index(es) in occurrences that has the highest value.

int maxOccurrences = Integer.MIN_VALUE;
int mode = -1;

for ( int i = 0; i < occurrences.length; i++ ) {
    if ( occurrences[i] > maxOccurrences ) {
        maxOccurrences = occurrences[i];
        mode = i;
    }
}

You would have to adjust this to handle multiple modes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM