RosettaCodeData/Task/Closest-pair-problem/D/closest-pair-problem-2.d

40 lines
1.2 KiB
D
Raw Permalink Normal View History

2014-01-17 05:32:22 +00:00
import std.stdio, std.random, std.math, std.typecons, std.complex,
std.traits;
2013-04-10 16:57:12 -07:00
2014-01-17 05:32:22 +00:00
Nullable!(Tuple!(size_t, size_t))
2015-02-20 00:35:01 -05:00
bfClosestPair2(T)(in Complex!T[] points) pure nothrow @nogc {
2014-01-17 05:32:22 +00:00
auto minD = Unqual!(typeof(points[0].re)).infinity;
if (points.length < 2)
return typeof(return)();
size_t minI, minJ;
foreach (immutable i; 0 .. points.length - 1)
foreach (immutable j; i + 1 .. points.length) {
auto dist = (points[i].re - points[j].re) ^^ 2;
if (dist < minD) {
dist += (points[i].im - points[j].im) ^^ 2;
if (dist < minD) {
minD = dist;
minI = i;
minJ = j;
}
}
2013-04-10 16:57:12 -07:00
}
2014-01-17 05:32:22 +00:00
return typeof(return)(tuple(minI, minJ));
2013-04-10 16:57:12 -07:00
}
void main() {
2014-01-17 05:32:22 +00:00
alias C = Complex!double;
auto rng = 31415.Xorshift;
C[10_000] pts;
2013-04-10 16:57:12 -07:00
foreach (ref p; pts)
2014-01-17 05:32:22 +00:00
p = C(uniform(0.0, 1000.0, rng), uniform(0.0, 1000.0, rng));
2013-04-10 16:57:12 -07:00
2014-01-17 05:32:22 +00:00
immutable ij = pts.bfClosestPair2;
if (ij.isNull)
2013-04-10 16:57:12 -07:00
return;
2014-01-17 05:32:22 +00:00
writefln("Closest pair: Distance: %f p1, p2: %f, %f",
abs(pts[ij[0]] - pts[ij[1]]), pts[ij[0]], pts[ij[1]]);
2013-04-10 16:57:12 -07:00
}