Vigenère cipher: Difference between revisions

Content deleted Content added
Better fix for the modulus bug in the second D entry
Updated second D entry
Line 539: Line 539:
std.conv;
std.conv;


int mod(in int m, in int n) pure nothrow { return ((m % n) + n) % n; }
enum mod = (in int m, in int n) pure nothrow => ((m % n) + n) % n;


private auto _s2v(in string s) pure /*nothrow*/ {
enum _s2v = (in string s) pure /*nothrow*/ =>
return s.toUpper.removechars("^A-Z").map!(c => cast(int)c - 'A');
s.toUpper.removechars("^A-Z").map!q{ a - 'A' };
}


private string _v2s(R)(R v) /*pure nothrow*/ {
string _v2s(R)(R v) /*pure nothrow*/ {
return v.map!(x => cast(char)(x.mod(26) + 'A')).text;
return v.map!(x => uppercase[x.mod(26)]).text;
}
}


string encrypt(in string txt, in string key) /*pure nothrow*/ {
enum encrypt = (in string txt, in string key) /*pure nothrow*/ =>
return txt._s2v.zip(key._s2v.cycle).map!q{ a[0] + a[1] }._v2s;
txt._s2v.zip(key._s2v.cycle).map!q{ a[0] + a[1] }._v2s;
}


string decrypt(in string txt, in string key) /*pure nothrow*/ {
enum decrypt = (in string txt, in string key) /*pure nothrow*/ =>
return txt._s2v.zip(key._s2v.cycle).map!q{ a[0] - a[1] }._v2s;
txt._s2v.zip(key._s2v.cycle).map!q{ a[0] - a[1] }._v2s;
}


void main() {
void main() {