Closest-pair problem: Difference between revisions

→‎{{header|D}}: add implementation
m (fixed link)
(→‎{{header|D}}: add implementation)
Line 331:
(cp (sort (copy-list points) '< :key 'car))
(values pair distance))))</lang>
 
=={{header|D}}==
This implements the brute force method. It is currently locked to a single data type and structure, but could easily be templated to apply to other types or more dimensions.
<lang d>
import std.math;
struct point {
real x,y;
}
real distance(point p1,point p2) {
real xdiff = p1.x-p2.x,ydiff = p1.y-p2.y;
return sqrt(xdiff*xdiff+ydiff*ydiff);
}
point[]closest_pair(point[]input) {
real tmp,savedist = -1;
int savei = -1,savej = -1;
foreach(i,p1;input) foreach(j,p2;input) {
if (i==j) continue;
if (savedist == -1) {
savei = i;
savej = j;
savedist = distance(p1,p2);
continue;
}
tmp = distance(p1,p2);
if (tmp < savedist) {
savei = i;
savej = j;
savedist = tmp;
}
}
if (savedist == -1) return null;
return [input[savei],input[savej]];
}
</lang>
 
=={{header|Fortran}}==
Anonymous user