• Algs4-1.2.1编写一个Point2D的用例


     1.2.1编写一个Point2D的用例,从命令行接受一个整数N。在单位正方形中生成N个随机点,然后计算两点之间的最近距离。
    解:
    图片

    public class Test
    {
        public static void main(String[] args)
        {
            int N=Integer.parseInt(args[0]);
            //
            double x0=0.0;
            double x1=200.0;
            double y0=0.0;
            double y1=200.0;
            //
            StdDraw.setXscale(x0,x1);
            StdDraw.setYscale(y0,y1);
            StdDraw.setPenRadius(0.005);
            //generate points and draw point.
            Point2D[] pointArray=new Point2D[N];
            for(int i=0;i<N;i++)
            {
                Point2D p=new Point2D(StdRandom.uniform(x0,x1),StdRandom.uniform(y0,y1));
                pointArray[i]=p;
                pointArray[i].draw();
            }
            //
            if (N<2) return;
            if (N==2) {StdOut.printf("The two point is shortes.");return;}
            //find the shortest two point.
            Point2D p1=pointArray[0];
            Point2D p2=pointArray[0];
            double shortestDist=Math.sqrt(200*200+200*200)+1.0;
            double dist;
            for(int i=0;i<N;i++)
            {
                 for(int j=i+1;j<N;j++)
                {
                    dist=pointArray[i].distanceTo(pointArray[j]);
                    if (shortestDist>dist)
                    {
                        shortestDist=dist;
                        p1=pointArray[i];
                        p2=pointArray[j];
                    }//end if
                }//end for j
            }//end for i
           StdDraw.setPenColor(StdDraw.RED);
           p1.draw();
           p2.draw();
        }//end main
     }//end class Test

    附加说明:
    这个Point2D用的是:http://algs4.cs.princeton.edu/code/ 中的代码,同时将代码的第一行package edu.princeton.cs.algs4;有注释掉。
    另外在获取点间距时使用的是Point2D.distanceTo  而不是教材中的Point2D.distTo

  • 相关阅读:
    实现对象属性的lazy-loading(延迟加载)
    Scikit-Learn机器学习入门
    实现后门程序以及相应的rootkits,实现对后门程序的隐藏
    关于iptables命令
    基于netfilter和LVM的密码窃取
    实验一:网络嗅探器
    实验二:ICMP重定向攻击
    第八节课、第九节
    第六、七课
    python读取excel文件
  • 原文地址:https://www.cnblogs.com/longjin2018/p/9848788.html
Copyright © 2020-2023  润新知