简体   繁体   English

查找随机生成的10个数字数组的模式

[英]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. 我已经看到源代码发布在它们使用称为compactmode的单独方法的地方,但是我不知道将第二个方法放置在代码中的何处。 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. 我被教为Java的第一门语言,到目前为止,它是压倒性的。

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. 您将不得不对此进行调整以处理多种模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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