Excel BI’s Excel Challenge #311 — solved in R
In puzzles and riddles from ExcelBI we usually play with numbers or words, why not both at once. Lets dive into the newest one.
We need to sort digits in numbers written by numerals
Sort the digits of given numbers in column A in descending order.
Ex. TwoThreeOne which is 231. Sorting in descending order will make it 321. Hence asnwer would be ThreeTwoOne.
Lets start loading data and libraries:
library(tidyverse) library(data.table) library(readxl) input = read_excel(“Sort Text Numbers.xlsx”, range = “A1:A10”) test = read_excel(“Sort Text Numbers.xlsx”, range = “B1:B10”)
I realized that not everything can be written each way and that is why I’m taking some functions that will work in all 3 cases into earlier chunk.
number_mappings <- function() { c(“Zero” = 0, “One” = 1, “Two” = 2, “Three” = 3, “Four” = 4, “Five” = 5, “Six” = 6, “Seven” = 7, “Eight” = 8, “Nine” = 9) } word_to_number <- function(word) { numbers <- number_mappings() numbers[word] } number_to_word <- function(number) { words <- names(number_mappings()) name_mapping <- setNames(names(number_mappings()), number_mappings()) name_mapping[as.character(number)] }
process_number_string <- function(num_string) { words <- str_extract_all(num_string, “[A-Z][a-z]*”)[[1]] digits <- map_int(words, word_to_number) sorted_digits <- sort(digits, decreasing = TRUE) sorted_words <- map(sorted_digits, number_to_word) result_string <- paste0(unlist(sorted_words), collapse = “”) return(result_string) } result = input %>% rowwise() %>% mutate(remapped = map_chr(Number, process_number_string)) %>% ungroup()
process_number_string_base<- function(num_string) { words <- regmatches(num_string, gregexpr(“[A-Z][a-z]*”, num_string))[[1]] digits <- sapply(words, word_to_number) sorted_digits <- sort(digits, decreasing = TRUE) sorted_words <- sapply(sorted_digits, number_to_word) result_string <- paste(sorted_words, collapse = “”) return(result_string) } result_base <- data.frame(remapped = sapply(input$Number, process_number_string_base))
And again I will call ready function using DT syntax.
setDT(input) input[, remapped := sapply(Number, process_number_string)]
identical(test$`Expected Answer`, result$remapped) #> [1] TRUE identical(test$`Expected Answer`, result_base$remapped) #> [1] TRUE identical(test$`Expected Answer`, input$remapped) #> [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.
Sort Text Numbers was originally published in Numbers around us on Medium, where people are continuing the conversation by highlighting and responding to this story.