Closest-pair problem: Difference between revisions

Updated both D versions, tags
(Updated both D versions, tags)
Line 455:
 
=={{header|D}}==
===Compact Versions===
Version designed for compactness:
<lang d>import std.stdio, std.typecons, std.math, std.algorithm,
std.array, std.random, std.traits;
Line 486:
immutable dm_pairm= dl_pairl[0]<dr_pairr[0] ? dl_pairl : dr_pairr;
immutable dm = dm_pairm[0];
const nextY= array(yP.filter!(p => abs(p.re - xDiv) < dm)(yP).array();
if (nextY.length > 1) {
auto minD = typeof(T.re).infinity;
Line 518:
 
auto rnd = Random(1); // set seed
auto points = new cdouble[10_000] points;
foreach (ref p; points)
p = uniform(0.0, 1000.0, rnd) + uniform(0.0, 1000.0, rnd) * 1i;
Line 531:
closestPair: Tuple!(double,cdouble,cdouble)(0.0947756, 643.407+788.387i, 643.463+788.31i)
</pre>
TimeAbout gave 0:044.03 elapsedseconds run-time for brute force version, and about 0:00.06 elapsedseconds for the divide & conquer one (10_000 points).
===Faster Brute-force Version===
 
<lang d>import core.stdc.stdio, core.stdc.stdlib, std.math; // for Phobos
A more efficient implementation of the brute-force algorithm, D version 1 with Tango library, LDC compiler:
<lang d>//import tango.stdc.stdio, tango.stdc.stdlib, tango.math.Math;
 
int bfClosestPair2(cdouble[] points, out size_t i1, out size_t i2) {
Line 560:
}
}
 
i1 = minI;
i2 = minJ;
return 0;
}
 
void main() {
srand(31415);
auto pts = new cdouble[10_000];
foreach (ref p; pts)
p = 1000.0 * (cast(double)rand() / (RAND_MAX + 1.0)) +
1000.0i * (cast(double)rand() / (RAND_MAX + 1.0));
 
size_t i, j;
int err = bfClosestPair2(pts, i, j);
Line 582:
d, pts[i].re, pts[i].im, pts[j].re, pts[j].im);
}</lang>
Time gaveAbout 0:00.15 elapsedseconds run-time for brute-force version 2 (10_000 points) with with LDC compiler and Tango library (D version 1).
 
=={{header|F Sharp|F#}}==