Caesar cipher in f#
I have a project where I have to code a Caesar cipher that takes in a string and a shift amount and then encrypts the string into cipher text. I easily did this in JavaScript but now I have to do it in F#. Also no loops allowed only recursion. I'm completely stressed an开发者_开发百科d confused and running out of time so im posting here as a last resort. This is all I have so far and I feel like I'm heading in a completely wrong direction...
let rec encrypt str shiftAmount =
if str.length > 0 then
strChar = str.ToUpper().Chars(0)
strUni = int strChar
strCoded = (((strUni + shiftAmount - 65) %26) +65)
else
In this case it makes more sense to use a mapping function (in this case Array.Map()
) and pipelining instead of recursion since you have to apply a function (character shifting) to each character in your string. Below should work for uppercase characters:
let shift(c, shiftAmount) =
let num = int(c) - int('A')
let offsetNum = (num+shiftAmount)%26
let result = offsetNum + int('A')
if offsetNum < 0 then
char(int('Z') + offsetNum + 1)
else
char(offsetNum + int('A'))
let encrypt(str:string, shiftAmount) =
str.ToCharArray()
|> Array.map (fun c -> shift( int(c), shiftAmount))
|> String.Concat
There might be a much more elegant solution (especially to cover both clock-wise and counter-clock wise shifting), still learning myself.
Here's a naive Caesar encoding:
let encode (str:string) shift =
let inline flipzip a b = b, a
str
|> String.map (fun ch ->
ch
|> int
|> flipzip (int 'A')
||> (-)
|> (+) shift
|> flipzip 26
||> (%)
|> (+) (int 'A')
|> char)
Beyond that, it's not clear to me what you're asking for other than for someone else to do all the work for you...
精彩评论