1.2.1 Write a Point2D client that takes an integer value N from the command line, generates N random points in the unit square, and computes the distance separating the closest pair of points.
图片来源:《Algorithms 4 Edition》
import edu. princeton. cs. algs4. Point2D ;
import edu. princeton. cs. algs4. StdDraw ;
import edu. princeton. cs. algs4. StdRandom ;
public class E121 {
public static void main ( String [ ] args) {
int N = Integer . parseInt ( args[ 0 ] ) ;
StdDraw . setCanvasSize ( 400 , 400 ) ;
StdDraw . setXscale ( 0 , 100 ) ;
StdDraw . setYscale ( 0 , 100 ) ;
StdDraw . setPenRadius ( 0.01 ) ;
StdDraw . enableDoubleBuffering ( ) ;
Point2D [ ] points = new Point2D [ N ] ;
for ( int i = 0 ; i < N ; i++ )
{
points[ i] = new Point2D ( StdRandom . uniform ( 100 ) , StdRandom . uniform ( 100 ) ) ;
points[ i] . draw ( ) ;
}
double minDistance = points[ 0 ] . distanceTo ( points[ 1 ] ) ;
int [ ] twoPoint = new int [ 2 ] ;
twoPoint[ 0 ] = 0 ; twoPoint[ 1 ] = 1 ;
for ( int i = 0 ; i < N ; i++ )
{
for ( int j = i + 1 ; j < N ; j++ )
{
double tempDistance = points[ i] . distanceTo ( points[ j] ) ;
if ( tempDistance < minDistance)
{
minDistance = tempDistance;
twoPoint[ 0 ] = i;
twoPoint[ 1 ] = j;
}
}
}
StdDraw . setPenColor ( StdDraw . RED) ;
points[ twoPoint[ 0 ] ] . draw ( ) ;
points[ twoPoint[ 1 ] ] . draw ( ) ;
points[ twoPoint[ 0 ] ] . drawTo ( points[ twoPoint[ 1 ] ] ) ;
StdDraw . show ( ) ;
System . out. printf ( "距离最小的两个点是:%d,%d,其距离为%f" , twoPoint[ 0 ] , twoPoint[ 1 ] , minDistance) ;
}
}
距离为% f", twoPoint[ 0 ] , twoPoint[ 1 ] , minDistance) ;
}
}