首页 > 学院 > 开发设计 > 正文

随机连接

2019-11-08 00:52:59
字体:
来源:转载
供稿:网友

题目描述:

编写一段程序,从命令行接收一个整数N和double值p(0到1之间)作为参数,在一个圆上画出大小为0.01且间距相等的N个点,然后将每对点按照概率p用灰线连接。

代码实现:

import edu.PRinceton.cs.algs4.*;public class fly {	public static void paint(int N, double p) {		if (p > 1 || p < 0)			StdOut.println("p值应介于0、1间");		// 存储N个点的x,y坐标,为根据概率连线做准备		double[] xa = new double[N];		double[] ya = new double[N];		// 设置圆的半径为30		int r = 30;		// 画点前的准备(不设置x,y的范围比例无法DrawPoint)		StdDraw.setPenRadius(0.01);		StdDraw.setXscale(0, 80);		StdDraw.setYscale(0, 80);		// 角度转化为弧度		double angle = Math.toRadians(360 / N);		double start = 0.0;		for (int i = 0; i < N; i++) {			// 圆点圆心为(40,40)			double x = 40 + r * Math.cos(start);			double y = 40 + r * Math.sin(start);			xa[i] = x;			ya[i] = y;			StdDraw.point(x, y);			start += angle;		}		StdDraw.setPenColor(StdDraw.GRAY);		for (int i = 0; i < N - 1; i++)			for (int j = i + 1; j < N; j++) {				if (StdRandom.uniform(0.0, 1.0) <= p)					StdDraw.line(xa[i], ya[i], xa[j], ya[j]);			}	}	public static void main(String[] args) {		paint(StdIn.readInt(), StdIn.readDouble());	}}

输入参数10,0.3测试:


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表