Last active
February 21, 2016 18:42
[2016-02-16] Challenge #254 [Easy] Atbash Cipher
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
# | |
# [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='') | |
} |
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
> atbash('foobar') | |
[1] "ullyzi" | |
> atbash('wizard') | |
[1] "draziw" | |
> atbash('/r/dailyprogrammer') | |
[1] "/i/wzrobkiltiznnvi" | |
> atbash('gsrh rh zm vcznkov lu gsv zgyzhs xrksvi') | |
[1] "this is an example of the atbash cipher" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment