Sum of Series
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Excel BI’s Excel Challenge #318 — solved in R
Defining the Puzzle:
Now we are asked to find sum of small series which value and number depends on input number itself. Sounds weird but it was suprisingly easy and nice.
Find the Sum of the Series — 1*2*3 + 2*3*4 + 3*4*5+…..+N*(N+1)*(N+2)
Hence, if N = 4
Then 1*2*3 + 2*3*4 + 3*4*5 + 4*5*6 = 210
For N = 8
1*2*3 + 2*3*4 + 3*4*5 + 4*5*6 + 5*6*7 + 6*7*8 + 7*8*9 + 8*9*10 = 1980
Loading Data from Excel:
Lets start loading data and libraries:
library(tidyverse) library(readxl) input = read_excel(“Sum of Series.xlsx”, range = “A1:A10”) test = read_excel(“Sum of Series.xlsx”, range = “B1:B10”)
Approach 1: Tidyverse with purrr
sum_of_products = function(N) { sum(map_dbl(1:N, ~ .x * (.x + 1) * (.x + 2))) } result = input %>% mutate(result = map_dbl(.$N,sum_of_products))
Approach 2: Base R
sum_of_products <- function(N) { sum(sapply(1:N, function(x) x * (x + 1) * (x + 2))) } input$result <- sapply(input$N, sum_of_products)
Approach 3: Data.table
As long as Base R and data.table will only differ in way of applying it on data.frame, I’ll drop DT. Sorry guys.
Validation:
identical(test$`Expected Answer`, result$result) # [1] TRUE identical(test$`Expected Answer`, input$result) # [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.
Sum of Series was originally published in Numbers around us on Medium, where people are continuing the conversation by highlighting and responding to this story.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.