gpt4 book ai didi

用密文替换字母

转载 作者:行者123 更新时间:2023-12-04 22:14:23 25 4
gpt4 key购买 nike

我一直在玩 R 的 gsub2 函数 R: replace characters using gsub, how to create a function? 来创建一个密文:

from<-c('s','l','k','u','m','i','x','j','o','p','n','q','b','v','w','z','f','y','t','g','h','a','e','d','c','r')
to<-c('z','e','b','r','a','s','c','d','f','g','h','i','j','k','l','m','n','o','p','q','t','u','v','w','x','y')

例如:

original text: the who's 1973

ciphertext: ptv ltn'm 1973



问题是,gsub2 将某些字母替换了两次(o->f->n 和 s->z->n),这弄乱了我的密文,几乎无法解码。有人能指出我犯的错误吗?谢谢!

最佳答案

一种方法是使用命名向量作为编码密码。创建此类命名向量的一种简单方法是使用 setNames :

cipher <- setNames(to, from)
cipher
s l k u m i x j o p n q b v w z f y t g h a e d c r
"z" "e" "b" "r" "a" "s" "c" "d" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "t" "u" "v" "w" "x" "y"

对于编码功能,您可以使用 strsplitpaste :
encode <- function(x){
splitx <- strsplit(x, "")[[1]]
xx <- cipher[splitx]
xx[is.na(xx)] <- splitx[is.na(xx)]
paste(xx, collapse="")
}

encode("the who's 1973")
[1] "ptv ltf'z 1973"

关于用密文替换字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13503848/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com