Skip to content

Latest commit

 

History

History
66 lines (47 loc) · 1.68 KB

Ex_1_1_31.md

File metadata and controls

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

1.1.31

问题:

Random connections. Write a program that takes as command-line arguments an integer N and a double value p (between 0 and 1), plots N equally spaced dots of size .05 on the circumference of a circle, and then, with probability p for each pair of points, draws a gray line connecting them.

分析:

2019-05-05-001

2019-05-05-002

  public static void drawCircleConnection(int N, double p) {

    // canvas & scale
    StdDraw.setCanvasSize(640, 640);
    StdDraw.setScale(-1.2, 1.2);

    // draw a circle at (0,0) and radius = 1
    StdDraw.circle(0,0,1);

    // pen radius
    StdDraw.setPenRadius(0.05);

    // N points on circle
    double[][] points = new double[N][2];
    for (int i = 0; i < N; i++) {
      double x_pos = Math.cos(2 * Math.PI * i / N);
      double y_pos = Math.sin(2 * Math.PI * i / N);

      StdDraw.point(x_pos, y_pos);

      // save points
      points[i][0] = x_pos;
      points[i][1] = y_pos;
    }

    StdDraw.setPenColor(StdDraw.GRAY);
    StdDraw.setPenRadius(); // default line width
    for (int i = 0; i < N; i++)
      for (int j = i+1; j < N; j++)
        if(StdRandom.bernoulli(p))
          // x_form, y_from -> x_to, y_to
          StdDraw.line(points[i][0], points[i][1], points[j][0], points[j][1]);

  }

参考:

wiki-circle

Trigonometric functions