算法(第4版本)1.1.32

参看 https://github.com/aistrate/AlgorithmsSedgewick 

直方图 假设标准输入流中含有一系列double值。编写一段程序,从命令行接受一个整数N和两个double值l和r。将(l,r)分为N段并使用StdDraw画出输入流中的值落入每段的数量的直方图。


private static void test32(){
      double[] values = {1, 2, 2.1, 2.2, 2.3, 2.4, 3.1, 3, 3.2, 3.5, 4, 4.1};
      int n = 5;
      double l = 1;
      double r = 4;
      
      double length = r - l;
      double averageLength = length / n;
      System.out.println("averageLength = " + averageLength); //每段长度
      double[] points = new double[n+1];
      points[0] = l;
      points[n] = r;
      for(int i = 1; i < n; i++){
          points[i] = points[0] + averageLength * i;
      }
      
      int[] counts = new int[n];
      int dataCount = values.length;
      for(int i = 0; i < dataCount; i++){
          int k = computeIndex(values[i], n, l, r);
          System.out.println("k = " + k);
          if(k >= 0){
              counts[k]++;
          }
      }
      
      int maxCount = StdStats.max(counts);
      StdDraw.setCanvasSize(512, 512);
      StdDraw.setXscale(l, r);
      StdDraw.setYscale(0, maxCount);
      double x;
      double y;
      double halfWidth;
      double halfHeight;
      for(int i = 0; i < n; i++){
          x = l + (i + 0.5) * averageLength;
          y = counts[i]/2.0;
          halfWidth = averageLength/2.0;
          halfHeight = counts[i]/2.0;
          System.out.println("x = " + x + ", y = " + y + ", halfWidth = " + halfWidth + ", halfHeight = " + halfHeight);
          StdDraw.filledRectangle(x, y, halfWidth, halfHeight);
      }
  }
  
  private static int computeIndex(double point, int n, double l, double r){
      if (point < l || point >= r)
          return -1;
      else
          return (int)(n * (point - l) / (r - l));  //(point-l)是l到r之间的一点,那么(point-l)除以 (r-l)肯定大于i除以N,然后如果是/的运算,会取整
  }


你可能感兴趣的:(算法第4版学习笔记,算法第4版本1.1.32)