算法第四版习题1.1.32,直方图

import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdDraw;
import edu.princeton.cs.algs4.StdRandom;
public class e1_1_32
{

    public static void main(String[] args)
    {
        int N = Integer.parseInt(args[0]);
        int a[] = new int[N];
        int j = 0;
        double l0 = Double.parseDouble(args[1]);
        double r0 = Double.parseDouble(args[2]);
        double x = r0 - l0;
        double t0 = (r0 - l0) / N;
        while(!StdIn.isEmpty()) {

            j++;
            double l = l0, r = r0, t = t0;
            double num = StdIn.readDouble();
            for(int i = 0; l < r; i++) {                
                if(num > l && num <= l + t)
                    a[i]++;         
                l += t;
            }           
        }
        StdDraw.setXscale(l0,r0);
        StdDraw.setYscale(0,j);
        for(int i = 0; i < N; i++) {
            StdDraw.line(l0,a[i],l0+t0,a[i]);
            l0 += t0;
        }
        l0 = r0 - x;
        for(int i = 0; i < N; i++) {
            StdDraw.line(l0,0,l0,a[i]);
            if( i > 0)  StdDraw.line(l0,0,l0,a[i-1]);
            l0 += t0;
        }
        StdDraw.line(r0,0,r0,a[N-1]);
    }
}

这里写图片描述

算法第四版习题1.1.32,直方图_第1张图片

你可能感兴趣的:(算法第四版)