Cypher and turn around- Atbash palindrome
Excel BI’s Excel Challenge #314 — solved in R
Defining the Puzzle:
This puzzle is searching Atbash Palindrome.
ATBASH Palindrome — In ATBASH cipher, we replace a with z, b with y, c with x…..y with b, z with a.
Find those texts which are palindrome after doing ATBASH cipher and reversing it.
Ex. AMNZ
Reversing it gives ZNMA and after applying ATBASH cipher, it becomes AMNZ which is equal to original text i.e. it is a palindrome..
Loading Data from Excel:
Lets start loading data and libraries:
library(tidyverse)
library(readxl)
library(stringi)
library(data.table)
input = read_excel(“Atbash Palindromes.xlsx”, range = “A1:A10”)
test = read_excel(“Atbash Palindromes.xlsx”, range = “B1:B4”)
Approach 1: Tidyverse with purrr
atbash_cipher_palindrome = function(word) {
atbash_code = rev(LETTERS)
vec = str_split(word, “”)[[1]]
atbashed = map_chr(vec, function(x) {
if (x %in% LETTERS) {
index = which(LETTERS == x)
return(atbash_code[index])
} else {
return(x)
}
})
result = all(vec == rev(atbashed))
return(result)
}
result = input %>%
mutate(check = map_lgl(Text, atbash_cipher_palindrome)) %>%
filter(check == TRUE) %>%
select(`Answer Expected` = Text)
Approach 2: Base R
atbash_cipher_palindrome_base <- function(word) {
atbash_code <- rev(LETTERS)
vec <- strsplit(word, ‘’)[[1]]
atbashed <- sapply(vec, function(x) {
if (x %in% LETTERS) {
index <- which(LETTERS == x)
return(atbash_code[index])
} else {
return(x)
}
})
result <- all(vec == rev(atbashed))
return(result)
}
result_base <- input[apply(input, 1, function(row) { atbash_cipher_palindrome_base(row[“Text”])
}), , drop=FALSE]
Approach 3: Data.table
atbash_cipher_palindrome_dt <- function(word) {
atbash_code <- rev(LETTERS)
vec <- strsplit(word, ‘’)[[1]]
atbashed <- sapply(vec, function(x) {
if (x %in% LETTERS) {
index <- which(LETTERS == x)
return(atbash_code[index])
} else {
return(x)
}
})
result <- all(vec == rev(atbashed))
return(result)
}
setDT(input)
atbash_cipher_palindrome_dtv <- Vectorize(atbash_cipher_palindrome_dt)
result_dt <- input[atbash_cipher_palindrome_dtv(Text), .(Answer_Expected = Text)]
Validating Our Solutions:
identical(result, test)
# [1] TRUE
identical(test$`Answer Expected`, result_base$Text)
# [1] TRUE
identical(test$`Answer Expected`, result_dt$Answer_Expected)
# [1] TRUE
If you like my publications or have your own ways to solve those puzzles in R, Python or whatever tool you choose, let me know.