Skip to content

Latest commit

 

History

History
49 lines (37 loc) · 1.29 KB

Ex_1_1_32.md

File metadata and controls

49 lines (37 loc) · 1.29 KB
title date draft tags categories
算法4 Java解答 1.1.32
2019-03-02 19:38:48 +0800
false
JAVA
技术
归档

1.1.32

问题:

Histogram. Suppose that the standard input stream is a sequence of double values. Write a program that takes an integer N and two double values l and r from the command line and uses StdDraw to plot a histogram of the count of the numbers in the standard input stream that fall in each of the N intervals defined by dividing (l , r) into N equal-sized intervals.

分析:

public static void histogram(int N, double l, double r, double[] vals) {
    StdDraw.setCanvasSize(512, 256);
    StdDraw.setXscale(l, r);
    StdDraw.setYscale(0, vals.length * 2 / 3);
    int[] freq = new int[N];
    double w = (r - l) / N;
    for (int i = 0; i < vals.length; i++) {
      int occurIdx = (int) ((vals[i] - l) / (r - l) * N);
      freq[occurIdx]++;
    }
    for (int i = 0; i < N; i++) {
      double x = l + w / 2.0 + w * i; //rectangle center (x)
      double y = freq[i] / 2.0;
      double rw = w / 4.0;
      double rh = freq[i] / 2.0;
      StdDraw.filledRectangle(x, y, rw, rh);
      StdDraw.text(x, 2 * y + 10, freq[i] + "");
    }

  }

2019-05-07-001

参考: