A-M baby
This commit is contained in:
parent
764da6cbbb
commit
db842d013d
19005 changed files with 197040 additions and 7 deletions
23
Task/Gray-code/D/gray-code-1.d
Normal file
23
Task/Gray-code/D/gray-code-1.d
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
import std.stdio;
|
||||
|
||||
T enGray(T)(in T n) pure nothrow {
|
||||
return n ^ (n >>> 1);
|
||||
}
|
||||
|
||||
T deGray(T)(in T n) pure nothrow {
|
||||
enum T MSB = (cast(T)1) << (T.sizeof * 8 - 1);
|
||||
|
||||
auto res = (n & MSB) ;
|
||||
foreach (bit; 1 .. T.sizeof * 8)
|
||||
res += (n ^ (res >>> 1)) & (MSB >>> bit);
|
||||
return res;
|
||||
}
|
||||
|
||||
void main() {
|
||||
writeln("num bits encoded decoded");
|
||||
foreach (i; 0 .. 32) {
|
||||
immutable encoded = enGray(i);
|
||||
writefln("%2d: %5b ==> %5b : %2d",
|
||||
i, i, encoded, deGray(encoded));
|
||||
}
|
||||
}
|
||||
37
Task/Gray-code/D/gray-code-2.d
Normal file
37
Task/Gray-code/D/gray-code-2.d
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
import std.stdio, std.conv, std.algorithm;
|
||||
|
||||
T[] gray(int N : 1, T)() { return [to!T(0), 1]; }
|
||||
|
||||
/// recursively generate gray encoding mapping table
|
||||
T[] gray(int N, T)() pure nothrow {
|
||||
assert(N <= T.sizeof * 8, "N exceed number of bit of T");
|
||||
enum T M = to!T(2) ^^ (N - 1);
|
||||
T[] g = gray!(N - 1, T)();
|
||||
foreach (i; 0 .. M)
|
||||
g ~= M + g[M - i - 1];
|
||||
return g;
|
||||
}
|
||||
|
||||
T[][] grayDict(int N, T)() {
|
||||
T[][] dict = [gray!(N, T)(), [0]];
|
||||
// append inversed gray encoding mapping
|
||||
foreach (i; 1 .. dict[0].length)
|
||||
dict[1] ~= countUntil(dict[0], i);
|
||||
return dict;
|
||||
}
|
||||
|
||||
enum M { Encode = 0, Decode = 1 };
|
||||
|
||||
T gray(int N, T)(in T n, in int mode=M.Encode) {
|
||||
// generated at compile time
|
||||
enum dict = grayDict!(N, T)();
|
||||
return dict[mode][n];
|
||||
}
|
||||
|
||||
void main() {
|
||||
foreach (i; 0 .. 32) {
|
||||
immutable encoded = gray!(5)(i, M.Encode);
|
||||
immutable decoded = gray!(5)(encoded, M.Decode);
|
||||
writefln("%2d: %5b => %5b : %2d", i, i, encoded, decoded);
|
||||
}
|
||||
}
|
||||
11
Task/Gray-code/D/gray-code-3.d
Normal file
11
Task/Gray-code/D/gray-code-3.d
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
import std.stdio, std.algorithm, std.range;
|
||||
|
||||
string[] g(in uint n) /*pure nothrow*/ {
|
||||
return n ? g(n - 1).map!q{'0' ~ a}().array() ~
|
||||
g(n - 1).retro().map!q{'1' ~ a}().array()
|
||||
: [""];
|
||||
}
|
||||
|
||||
void main() {
|
||||
writeln(g(4));
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue