Closest-pair problem: Difference between revisions
Content added Content deleted
Line 211: | Line 211: | ||
=={{header|D}}== |
=={{header|D}}== |
||
This (for D version 1) 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> |
|||
D version 2 implementation, adapted from the Python version. This code is designed for compactness instead of performance. |
D version 2 implementation, adapted from the Python version. This code is designed for compactness instead of performance. |
||
<lang d>import std.stdio,std.typecons,std.math,std.algorithm,std.array,std.random; |
<lang d>import std.stdio,std.typecons,std.math,std.algorithm,std.array,std.random; |