我正在尝试编写凯撒密码,但只能使用大写字母数字。使用ord
或chr
使用整个ASCII表。如何做到这一点?
这是我到目前为止的内容:
alphabet = ['A'..'Z'] ++ ['0'..'9']
c2I = ord c - ord 'A'
i2C = chr (n + ord 'A')
基本思想是使用mod
环绕到开始。
现在效率不高(但是,嘿,您使用的是最不安全的密码,因此您可能不太在意),但我将仅使用字母和索引功能向您展示:
import Data.List (elemIndex)
alphabet :: [Char]
alphabet = ['A'..'Z'] ++ ['0'..'9']
ith :: Int -> Char
ith i = alphabet !! j
where j = i `mod` length alphabet
index :: Char -> Int
index c = case c `elemIndex` alphabet of
Just i -> i
Nothing -> error "not inalphabet"
encode :: Int -> String -> String
encode n xs = [ ith $ index x + n | x <- xs ]
这会给你
λ> encode 3 "ABCXYZ012789"
"DEF012345ABC"
现在您可能会想找到一种使用ord
and的方法chr
-如果您区分A-Z
和之间的大小写,那么两者都可以工作0-9
,因为范围是:
因此,如果没有太多技巧,就无法采用一个公式
您应该尝试一下,但是这里需要更多的数学知识(您可能希望像ord c - ord 'A'
字母和26 + ord c - ord '0'
数字之类的东西0-35
首先进入该范围。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句