Caesar Cipher
March 11, 2014
Here is our solution, which can be used for both enciphering and deciphering:
(define (caesar n str)
(define (char-plus c)
(let ((alpha "ABCDEFGHIJKLMNOPQRSTUVWXYZ"))
(if (not (char-alphabetic? c)) c
(let ((i (- (char->integer (char-upcase c)) 65)))
(string-ref alpha (modulo (+ i n) 26))))))
(list->string (map char-plus (string->list str))))
Deciphering is the negative of enciphering:
> (caesar 3 "PROGRAMMINGPRAXIS")
"SURJUDPPLQJSUDALV"
> (caesar -3 "SURJUDPPLQJSUDALV")
"PROGRAMMINGPRAXIS"
You can run the program at http://programmingpraxis.codepad.org/TPWgYRB9.
What should be the cipher key ?
the key is the shift distance
Here’s a solution in Julia. There’s also a one-liner, encipherOneLiner.
The Caesar cipher shows up in Graham Hutton’s *great* book on Haskell.
Here’s a version similar to @Daniel’s:
import Data.Char (chr, isAsciiUpper, ord)
shift :: Int -> Char -> Char
shift n c | isAsciiUpper c = chr $ a + ((n + (ord c – a) `mod` 26))
| otherwise = c
where
a = ord ‘A’
caesar :: Int -> String -> String
caesar n = map $ shift n
main :: IO ()
main = mapM_ putStrLn [p, c, p’]
where
p = "PROGRAMMING PRAXIS"
c = caesar 3 p
p’ = caesar (-3) c
Apologies for the crap formatting. Apparently I’m really out of practice!
Racket / Rackjure
Full writeup: jverkamp.com
python solution:
To bring the cypher up to the current century, we can use an alphabet containing all the uppercase Unicode characters.
{code}
def CeaserC(word,offset=1):
#final=[chr(ord(i)+offset) for i in word]
return (”.join([chr(ord(i)+offset) for i in word]))
def Ceaserback(word,offset=1):
#final=[chr(ord(i)-offset) for i in word]
return (”.join([chr(ord(i)-offset) for i in word]))
print (CeaserC(“thisisatest”,1))
print (Ceaserback(“uijtjtbuftu”))
{/code}
Here’s a Java solution: