Java直方图阵列

时间:2015-11-22 21:12:17

标签: java

我必须编写一个方法,该方法接受30个随机整数的数组并返回一个新的直方图数组。直方图应包含11个元素,其中包含以下内容:

元素0 - 数组中< = 0

的元素数

1 - 数组中== 1

的元素数量

2 - 数组中== 2

的元素数量

...

9 - 数组中== 9

的元素数量

10 - 数组中的元素数>> = 10

我不确定如何使用随机数制作直方图。我有一个制作直方图的方法,以及一个制作随机数的方法,但我不知道如何将它们组合起来。

public static int[] arrayHist(int n) {
    int[] a = new int[n];
    for (int i = 0; i<a.length; i++) {
        a[i] = randomInt (0, 100);
    }
    return a; 
}

public static void printHist() {
    int[] scores = new int[30];
    int[] counts = new int [100];
    for (int i = 0; i<100; i++) {
        counts[i] = arrayHist (scores, i, i+1);
    }
}

1 个答案:

答案 0 :(得分:0)

这是我尝试根据您的规范计算任何给定正整数的直方图:

public static int[] histogram(int[] scores) {
    int[] counts = new int [11];
    for (int i = 0; i < scores.length; i++) {
        int hist = scores[i] / 10;
        if(hist == 0) {
            counts[scores[i]]++;
        } else {
            counts[10] ++;
        }
    }
    return counts;
}

您可以将随机数组传递给此函数。按顺序打印结果。

基本上,您必须将实现拆分为函数。

  1. 创建随机整数数组
  2. 计算直方图(请参阅我的方法作为示例)
  3. 打印直方图
  4. 你不能混淆这个想法;)