Associative arrays, symetrical algorithm, CTFE
I want to implement something like a 开发者_Python百科Vigenère cipher, and I chose to use D's associative arrays. I use the
struct Codes
{
int[char] enc;
char[int] dec;
}
and then i populate the AA's with
foreach(immutable char c; letters ~ whitespace ~ digits)
{
codes.enc[c] = codes.enc.length;
codes.dec[codes.enc.length] = c;
}
It works as it is suppose to work in my [en/de]crypting functions, but I have two questions:
- How can I, if I can, use just one AA. Or is it some other data structure that is as easy to use, more efficient or jut fits better with point 2.
- How am I suppose to use CTFE to generate some data structure at compile time and use the output at runtime.
(I'm using the dmd v2.053 compiler if that matter whatsoever this days).
the dec can be a normal array (it's equal to letters ~ whitespace ~ digits
btw)
in enc you can also use a normal array if you only allow ASCII as characters (with length 255 and casting c to int for the index)
edit
you can create a mixin string from the letters ~ whitespace ~ digits
string like so
string createSwitch(string seq,string inp){
string out = "switch("~inp~"){";
int i=0;
foreach(ch;seq){
out~="case "~ch~":return "~i";";
}
out~="default: return -1;";
return out;
}
which you can then use as
int intFromChar(char ch){
mixin(createSwitch(letters ~ whitespace ~ digits,"ch"));
}
精彩评论