Ich schrieb ein Skript zum Verschlüsseln und Entschlüsseln von Strings in R, der erste Teil des Codes definiert einen Vektor mit einer Reihe von Zeichen. Dann erstelle ich ein Verschlüsselungswörterbuch, indem ich den Vektor mische und jedem Namen zuweise. Dieser Teil ist temporär, ich werde einen festen Verschlüsselungsvektor haben. Wo ich Probleme habe, schreibe ich meine Verschlüsselungs- und Entschlüsselungsfunktionen effizient. Ich bekomme die gewünschte Ausgabe, aber ich habe das Gefühl, dass es einen eleganteren Weg dorthin gibt, der weniger Rechenleistung benötigt. Ideen, die Ihnen einfallen, ersetzen die for-Schleifen durch lapply (oder vapply), indem Sie eine Alternative finden, um die Zeichenfolge nicht in einen Vektor konvertieren zu müssen, indem Sie reguläre Ausdrücke verwenden usw. Ich bin jedoch neu für R und konnte seine Kraft nicht beherrschen. Hier ist mein Code:R - effiziente Verschlüsselung eines Strings in 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)
Ist dies nur für Bildungszwecke oder Produktion? – zaph
Persönlicher Gebrauch und (selbst) pädagogische Zwecke – Agarp