【发布时间】:2017-09-15 22:00:00
【问题描述】:
我写了一个脚本来加密和解密 R 中的字符串,代码的第一部分定义了一个包含一组字符的向量。然后,我通过打乱向量并为每个向量分配名称来创建一个加密字典。这部分是临时的,最终我会有一个固定的加密向量。我遇到麻烦的地方是有效地编写我的加密和解密功能。我得到了想要的输出,但我觉得有一种更优雅的方式可以到达那里——一种需要更少计算的方式。想到的想法是用 lapply(或 vapply)替换 for 循环,寻找不必将字符串转换为向量的替代方法,使用正则表达式等等。但是,我是 R 新手,无法掌握它的强大功能。这是我的代码:
# Script to encode and decode strings.
# Useful for passwords, email messages
# that do not contain images, and other
# text applications.
# Steps to create a vector containing all characters
## Numeric characters
nums <- c("1","2","3", "4", "5", "6", "7",
"8", "9", "0")
## Symbols
sym <- c("!", "@", "#", "$", "%", "^",
"&", "*", "(", ")", "-", "_",
"=", "+", "[", "{", "]", "}",
"|", "\\", ":", "/", "?", ".",
">", "<", ",", "`", "~", ";",
"'", " ")
## Vector with numeric, symbols, and letters
chars <- c(LETTERS, letters, sym, nums)
# Create a code vector
## Randomly sorted 'chars' vector
code <- sample(chars)
## Assing names to facilitate coding and decoding
names(code) <- chars
# Define a string to code and decode
text <- "Hello World!"
# Function to code string
coder <- function(text, code){
# Make string into a vector to facilitate iteration
# over items
t <- unlist(strsplit(as.character(text), split=''))
# Initiate a vector to store coded vector
new <- c()
# For loop to code each element in the vector
for(i in 1:length(t)){
new <- c(new, names(code)[which( code == t[i])])
}
# Collape vector into string
paste(new, collapse = '')
}
# Function call to verify output
encoded_str <- coder(text, code)
print(encoded_str)
decoder <- function(text, code){
# Make string into a vector to facilitate iteration
# over items
t <- unlist(strsplit(as.character(text), split=''))
# Initiate a vector to store decoded vector
new <- c()
# For loop to decode each element in the vector
for(i in 1:length(t)){
new <- c(new, code[[t[i]]])
}
# Collape vector into string
paste(new, collapse = '')
}
# Function call to verify output
decoded_str <- decoder(encoded_str, code)
print(decoded_str)
【问题讨论】:
-
这只是为了教育目的,还是为了生产?
-
个人使用和(自我)教育目的
标签: r string encryption vector