Skip to content

Instantly share code, notes, and snippets.

@run-dlang
Created June 22, 2018 21:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save run-dlang/d023233104927e61ba69e79c03d266e4 to your computer and use it in GitHub Desktop.
Save run-dlang/d023233104927e61ba69e79c03d266e4 to your computer and use it in GitHub Desktop.
Code shared from run.dlang.io.
size_t[] indexsort(T)(T[] orig...)
{
auto idx = new size_t[orig.length];
foreach(i; 0 .. orig.length) idx[i] = i;
size_t sorted = 1;
auto target = new size_t[orig.length];
while(sorted < orig.length)
{
for(size_t istart = 0; istart < orig.length; istart += sorted * 2)
{
size_t i = istart;
size_t jstart = i + sorted;
if(jstart > orig.length)
jstart = orig.length;
size_t j = jstart;
size_t end = jstart + sorted;
if(end > orig.length)
end = orig.length;
foreach(t; istart .. end)
{
if(i < jstart)
{
if(j < end)
{
// compare based on the original array
if(orig[idx[i]] > orig[idx[j]])
{
target[t] = idx[j];
++j;
}
else
{
target[t] = idx[i];
++i;
}
}
else
{
// no more j
target[t] = idx[i];
++i;
}
}
else
{
// no more i
target[t] = idx[j];
++j;
}
}
}
sorted *= 2;
auto tmp = idx;
idx = target;
target = tmp;
}
return idx;
}
enum foo
{
a,
b,
c,
b_ = b
}
enum EnumMember(E, size_t idx) = __traits(getMember, E, __traits(allMembers, E)[idx]);
string toString(T)(T value)
{
import std.traits;
enum sorted = indexsort(EnumMembers!foo);
switch(value)
{
static foreach(i; 0 .. sorted.length)
{
static if(i == 0 || EnumMember!(foo, sorted[i - 1]) != EnumMember!(foo, sorted[i]))
{
case EnumMember!(foo, sorted[i]):
return __traits(allMembers, T)[sorted[i]];
}
}
default:
assert(0);
}
}
void main()
{
import std.stdio;
writeln(foo.a.toString);
writeln(foo.b.toString);
writeln(foo.c.toString);
writeln(foo.b_.toString);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment