Skip to content

Instantly share code, notes, and snippets.

@primaryobjects
Last active February 21, 2016 18:42
[2016-02-16] Challenge #254 [Easy] Atbash Cipher
#
# [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='')
}
> 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