# # [2016-02-16] Challenge #254 [Easy] Atbash Cipher # https://www.reddit.com/r/dailyprogrammer/comments/45w6ad/20160216_challenge_254_easy_atbash_cipher/ # Demo: http://www.r-fiddle.org/#/fiddle?id=OBWeefV6&version=1 # # Atbash encodes a string by reversing the alphabet and then substituting the letters in the string with the reversed form alphabet. # Example # Plain: abcdefghijklmnopqrstuvwxyz # Cipher: zyxwvutsrqponmlkjihgfedcba # foobar -> ullyzi # gsrh rh zm vcznkov lu gsv zgyzhs xrksvi -> this is an example of the atbash cipher # # Kory Becker 2/16/2016 # http://primaryobjects.com # atbash <- function(str) { cipher <- rev(letters) result <- sapply(unlist(strsplit(str, NULL)), function(ch) { result <- ch # Get index of letter in cipher. index <- which(letters == tolower(ch)) if (length(index) > 0) { # Found a match (otherwise, just append the letter as-is). result <- cipher[index] if (grepl("^[[:upper:]]+$", ch)) { # Retain upper-case. result <- toupper(result) } } result }) paste(result, collapse='') }