In: Computer Science
Write a program in C or in Java, 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.
A unit square is a square with sides of length 1, at points (0, 0), (0, 1), (1, 0), and (1, 1).
If you wish to avoid the command-line processing, you can just assume you will generate a fixed number of points, say between 10 and 50).
C code:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main(void) {
int n;
scanf("%d",&n);
double arr[n][2];
int i=0;
while(i<n){
double x = (rand()%1001)/1000.0;
double y = (rand()%1001)/1000.0;
arr[i][0] =x;
arr[i][1] = y;
i++;
}
double mn = 2.0;
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
double dis =
sqrt((arr[i][0]-arr[j][0])*(arr[i][0]-arr[j][0]) +
(arr[j][1]-arr[i][1])*(arr[j][1]-arr[i][1]));
//printf("%f \n",dis);
if(mn>dis){
mn = dis;
}
}
}
printf("Minimum distance between two random points :
%f",mn);
return 0;
}
code screenshot: