RosettaCodeData/Task/Gray-code/D/gray-code-1.d

23 lines
479 B
D
Raw Permalink Normal View History

2015-02-20 00:35:01 -05:00
uint grayEncode(in uint n) pure nothrow @nogc {
2014-01-17 05:32:22 +00:00
return n ^ (n >> 1);
2013-04-10 21:29:02 -07:00
}
2015-02-20 00:35:01 -05:00
uint grayDecode(uint n) pure nothrow @nogc {
2014-01-17 05:32:22 +00:00
auto p = n;
while (n >>= 1)
p ^= n;
return p;
2013-04-10 21:29:02 -07:00
}
void main() {
2014-01-17 05:32:22 +00:00
import std.stdio;
" N N2 enc dec2 dec".writeln;
foreach (immutable n; 0 .. 32) {
immutable g = n.grayEncode;
immutable d = g.grayDecode;
writefln("%2d: %5b => %5b => %5b: %2d", n, n, g, d, d);
assert(d == n);
2013-04-10 21:29:02 -07:00
}
}