K-d tree: Difference between revisions
Content added Content deleted
(Updated second D entry) |
|||
Line 438: | Line 438: | ||
{{trans|C}} |
{{trans|C}} |
||
This version performs less lookups. Compiled with DMD this version is two times slower than the C version. Compiled with ldc2 it's a little faster than the C version compiled with gcc. |
This version performs less lookups. Compiled with DMD this version is two times slower than the C version. Compiled with ldc2 it's a little faster than the C version compiled with gcc. |
||
<lang d>import std.stdio, std.algorithm, std.math, std.random, std. |
<lang d>import std.stdio, std.algorithm, std.math, std.random, std.typecons; |
||
enum maxDim = 3; |
enum maxDim = 3; |
||
template Iota(int stop) { |
|||
static if (stop <= 0) |
|||
alias Iota = TypeTuple!(); |
|||
else |
|||
alias Iota = TypeTuple!(Iota!(stop - 1), stop - 1); |
|||
} |
|||
struct KdNode { |
struct KdNode { |
||
Line 512: | Line 505: | ||
ref const(KdNode)* best, |
ref const(KdNode)* best, |
||
ref double bestDist, |
ref double bestDist, |
||
ref size_t nVisited) pure nothrow @nogc { |
ref size_t nVisited) pure nothrow @safe @nogc { |
||
static double dist(in ref KdNode a, in ref KdNode b) |
static double dist(in ref KdNode a, in ref KdNode b) |
||
pure nothrow @nogc { |
pure nothrow @nogc { |
||
typeof(KdNode.x[0]) result = 0; |
typeof(KdNode.x[0]) result = 0; |
||
foreach (i; |
foreach (immutable i; staticIota!(0, dim)) |
||
result += (a.x[i] - b.x[i]) ^^ 2; |
result += (a.x[i] - b.x[i]) ^^ 2; |
||
return result; |
return result; |
||
Line 549: | Line 542: | ||
void randPt(size_t dim=3)(ref KdNode v, ref Xorshift rng) |
void randPt(size_t dim=3)(ref KdNode v, ref Xorshift rng) |
||
nothrow @nogc { |
pure nothrow @safe @nogc { |
||
foreach (immutable i; |
foreach (immutable i; staticIota!(0, dim)) |
||
v.x[i] = rng.uniform01; |
v.x[i] = rng.uniform01; |
||
} |
} |
||
Line 576: | Line 569: | ||
auto bigTree = new KdNode[N]; |
auto bigTree = new KdNode[N]; |
||
auto rng = |
auto rng = 1.Xorshift; |
||
foreach (ref node; bigTree) |
foreach (ref node; bigTree) |
||
randPt(node, rng); |
randPt(node, rng); |