Advertisement
Guest User

Caesar cipher

a guest
Dec 14th, 2012
38
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 0.94 KB | None | 0 0
  1. Range1 caesarCipher(Range1, Range2)(Range1 input, Range2 output, int shift)
  2.     if (isInputRange!Range1 && isRandomAccessRange!Range2 && hasLength!Range2)
  3. {
  4.     auto rotAb = lowercase.dtext.dup; // rotated alphabet
  5.     bool changeLength;
  6.  
  7.     shift %= lowercase.length.to!int; // bring the shift within the length of the alphabet
  8.  
  9.     if (output.empty)
  10.         changeLength = true;
  11.  
  12.     if (shift < 0)
  13.         bringToFront(rotAb[0 .. $ + shift], rotAb[$ + shift .. $]);
  14.     else
  15.         bringToFront(rotAb[0 .. shift], rotAb[shift .. $]);
  16.  
  17.     foreach (i, c; input)
  18.     {
  19.         if (changeLength)
  20.             ++output.length;
  21.  
  22.         if (isAlpha(c))
  23.             if (isUpper(c))
  24.                 output[i] = toUpper(rotAb[lowercase.countUntil(toLower(c))]).to!ubyte;
  25.             else
  26.                 output[i] = rotAb[lowercase.countUntil(c)].to!ubyte;
  27.         else
  28.             output[i] = c;
  29.     }
  30.  
  31.     return cast(Range1) output;
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement