Last active
April 8, 2018 23:39
[2018-03-26] Challenge #355 [Easy] Alphabet Cipher https://www.reddit.com/r/dailyprogrammer/comments/879u8b/20180326_challenge_355_easy_alphabet_cipher/. Demo at http://rextester.com/ZZIN40507
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
getEncoding <- function(letter1, letter2) { | |
# Find the number for each letter. | |
index1 <- match(letter1, letters) | |
index2 <- match(letter2, letters) | |
# Find the index number within the shifted letters by adding the two indices and taking the remainder from the number of letters. | |
index <- (index1 + index2 - 1) %% length(letters) | |
index <- ifelse(index == 0, 26, index) | |
letters[index] | |
} | |
encode <- function(str, secret) { | |
index <- 1 | |
keys <- unlist(strsplit(secret, '')) | |
len <- length(keys) | |
result <- sapply(unlist(strsplit(str, '')), function(ch) { | |
e <- getEncoding(ch, keys[index]) | |
index <<- index + 1 | |
if (index > len) { | |
index <<- 1 | |
} | |
e | |
}) | |
paste(result, collapse='') | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
lumicjcnoxjhkomxpkwyqogywq | |
uvrufrsryherugdxjsgozogpjralhvg | |
flrlrkfnbuxfrqrgkefckvsa | |
zhvpsyksjqypqiewsgnexdvqkncdwgtixkx |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
print(encode('thepackagehasbeendelivered', 'snitch')) | |
print(encode('theredfoxtrotsquietlyatmidnight', 'bond')) | |
print(encode('murderontheorientexpress', 'train')) | |
print(encode('themolessnuckintothegardenlastnight', 'garden')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment