繁体   English   中英

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

[英]Finding the mode of a randomly generated array of 10 numbers

我正在尝试制作这个程序

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);
    }
}

计算随机生成的数组的模式。

我已经看到源代码发布在它们使用称为compactmode的单独方法的地方,但是我不知道将第二个方法放置在代码中的何处。 抱歉,编程时我非常环保。 我被教为Java的第一门语言,到目前为止,它是压倒性的。

如果有人可以发布带有详细说明/解释的语法,我将非常感激。

该模式很容易计算。 假设您的输入是有界的,一种方法是简单地使用一个数组来跟踪每个数字的出现次数:

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

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

然后找出出现次数最高的索引。

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;
    }
}

您将不得不对此进行调整以处理多种模式。

暂无
暂无

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

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