如何从 Java 数字重复数组创建星号直方图?

How to create an histogram of asteriks from a Java array of number repetitions?

我有一个包含重复数字的数组,我需要在“*”制作的 "histogram" 中显示它们。直方图应如下所示:

            *
        *   *
  *     *   *
  *     * * *
* * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
1 2 3 4 5 6 7 8 9 10

我有这个数组

int[] repetition = new int[] {4,6,4,4,6,5,7,4,3,3};

而且我能够像这样水平打印它:

1*****
2******
3****
4****
5******
6*****
7*******
8****
9***
10***

如何创建垂直直方图?

首先计算直方图的最大高度。

max=0;
for(int i: repetition)
    if(i>max)
        max=i;

然后,你这样打印,从上到下:

for(j=max;j>=1;j--){                  //For each possible height of the histogram.
    for(k=0;k<repetition.length;k++)  //Check height of each element
        if(repetition[k]>=j)
            System.out.print("*");    //Print * if the k-th element has at least a height j.
        else
            System.out.print(" ");    //Else, do print blank space
    System.out.println();             //Newline after every row.
}

PS: 这只是一个想法,不是完整的工作代码,它只适用于正高度值!

听起来您有 "bin" 数据的代码,可以有效地创建直方图。添加一些代码来跟踪所有 bin 的最大计数。因此,在您上面的示例中,最大值为 8(来自 bin 7)。

然后,设置一个阈值,从最大值开始,倒数到一。在每次迭代中,在对应于达到或超过阈值的 bin 的列中打印带星号的行。因此在第一行,只有第 7 列会获得星号,因为它是唯一满足当前阈值 8 的 bin。下一行(阈值 7)的第 5 列和第 7 列将获得星号。等等。

希望这足以帮助您自己编写代码。

整数用于使用Collections max函数。

public static void main(String[] args) {
        Integer[] repetition = new Integer[] { 4, 6, 4, 4, 6, 5, 7, 4, 3, 3 };
        int maxValue = Collections.max(Arrays.asList(repetition));
        System.out.println("Maximum: " + maxValue);
        for (int i = maxValue; i > 0; i--) {
            for (int j = 0; j < repetition.length; j++) {
                if (repetition[j] >= i) {
                    System.out.print(" * ");
                } else {
                    System.out.print("   ");
                }
            }
            System.out.println();
        }
        for (int j = 0; j < repetition.length; j++) {
            System.out.print(" " + (j + 1) + " ");
        }
    }

我不会给你任何代码,但我可以给你一个开始的想法。

对于垂直直方图,即使它看起来是从上到下打印的,但它不是;你只是不能垂直打印。使用循环(数组中的最高值是起始值,0 是标记值,每次迭代递减 1),其中每次迭代代表直方图上的水平线,您应该确定哪个 x 标签的星号需要打印在该行上,对于那些在该行上没有星号的标签,请在此处放置一个 space (用于格式化)。然后,创建另一个循环并使用它列出所有 x -底部的标签。

希望对您有所帮助!

public static final void printHistogram(int[] coll) {
        int max = coll[0];
        for (int i : coll)
            max = i > max ? i : max;
        boolean[][] array = new boolean[max][coll.length];
        for (int i = coll.length - 1; i >= 0; i--) {
            for (int j = 0; j < coll[i]; j++) {
                array[j][i] = true;
            }
        }
        for (int i = array.length - 1; i >= 0; i--) {
            boolean[] booleans = array[i];
            for (boolean b : booleans) {
                System.out.print(b ? '*' : ' ');
            }
            System.out.println();
        }

        for (int i = 1; i <= array.length; i++) {
            System.out.print(i);
        }
    }

这按预期工作。