2017-09-15 180 views
0

我編寫了一個腳本來加密和解密R中的字符串,代碼的第一部分定義了一個包含一組字符的向量。然後,我通過對矢量進行混洗併爲每個指定名稱來創建一個加密字典。這部分是暫時的,最終我將擁有一個固定的加密向量。我遇到麻煩的地方是高效地編寫我的加密和解密函數。我得到了期望的輸出結果,但我覺得有一種更加優雅的方式可以實現這一目標 - 這需要較少的計算量。想到的想法是用lapply(或vapply)替換for循環,找到一種替代方案,無需使用正則表達式將字符串轉換爲矢量,等等。不過,我是R新手,無法掌握其權力。這裏是我的代碼:R - 高效地對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) 
+0

這是僅供教育目的,或者生產嗎? – zaph

+0

個人使用和(自我)教育目的 – Agarp

回答

1

我一個解決方案,試圖用簡單的匹配向量之間的元素,並重新安排他們:

coder2 <- function(text, code){ 
    textSplit <- unlist(strsplit(text, "")) 
    codeAsText <- code[code %in% textSplit] 
    paste(names(codeAsText[match(textSplit, codeAsText)]), collapse = "") 
} 
decoder2 <- function(text, code) { 
    textSplit <- unlist(strsplit(text, "")) 
    textAsCode <- code[names(code) %in% textSplit] 
    paste(textAsCode[match(textSplit, names(textAsCode))], collapse = "") 
} 

enter image description here

PS:不要使用t的名字tbase轉置功能。

+0

@AlejandroGarciadeParedes這不是一個整潔的解決方案,但可能是最快的一個,因爲沒有使用循環 – PoGibas

+0

沒有看到循環,循環在較低的水平。 zaph