RosettaCodeData/Task/Vigen-re-cipher/D/vigen-re-cipher-2.d

27 lines
945 B
D
Raw Permalink Normal View History

2013-10-27 22:24:23 +00:00
import std.stdio, std.range, std.ascii, std.string, std.algorithm,
std.conv;
2015-11-18 06:14:39 +00:00
immutable mod = (in int m, in int n) pure nothrow @safe @nogc =>
2015-02-20 00:35:01 -05:00
((m % n) + n) % n;
2013-10-27 22:24:23 +00:00
2015-11-18 06:14:39 +00:00
immutable _s2v = (in string s) pure /*nothrow*/ @safe =>
2013-10-27 22:24:23 +00:00
s.toUpper.removechars("^A-Z").map!q{ a - 'A' };
2015-02-20 00:35:01 -05:00
string _v2s(R)(R v) pure /*nothrow*/ @safe {
2013-10-27 22:24:23 +00:00
return v.map!(x => uppercase[x.mod(26)]).text;
}
2015-11-18 06:14:39 +00:00
immutable encrypt = (in string txt, in string key) pure /*nothrow*/ @safe =>
2013-10-27 22:24:23 +00:00
txt._s2v.zip(key._s2v.cycle).map!q{ a[0] + a[1] }._v2s;
2015-11-18 06:14:39 +00:00
immutable decrypt = (in string txt, in string key) pure /*nothrow*/ @safe =>
2013-10-27 22:24:23 +00:00
txt._s2v.zip(key._s2v.cycle).map!q{ a[0] - a[1] }._v2s;
void main() {
immutable key = "Vigenere Cipher!!!";
immutable original = "Beware the Jabberwock, my son!" ~
" The jaws that bite, the claws that catch!";
immutable encoded = original.encrypt(key);
writeln(encoded, "\n", encoded.decrypt(key));
}