Skip to content

Instantly share code, notes, and snippets.

@jakeybob
Created December 18, 2019 12:16
Show Gist options
  • Save jakeybob/5bfa4d5098aedcb28e697b8cc71edb3c to your computer and use it in GitHub Desktop.
Save jakeybob/5bfa4d5098aedcb28e697b8cc71edb3c to your computer and use it in GitHub Desktop.
N Days of Christmas
xmas_gifts <- function(days=12, pear_tree=FALSE){
days <- abs(as.integer(days))
gifts <- 0
# for(i in 1:days){gifts <- gifts + i*(days + 1 - i)} # general case: does N=days total summations
# can ~half the number of summations because...
# if days = even, summation is symmetric and reduces to e.g. 2*[12x1 + 11x2 + 10x3 + 9x4 + 8x5 + 7x6] for 12 total days
for(i in 1:(days/2 - .5* days %% 2)){
gifts <- gifts + i*(days + 1 - i)}
gifts <- 2*gifts + ( ((days+1)/2)^2 * (days %% 2)) # and if days = odd, add the additional squared term in the middle
# total hack to deal with days = 1
gifts <- ifelse(days == 1, 1, gifts)
# does a partridge in a pear tree count as two gifts? Who honestly cares at this point?
if(pear_tree == TRUE){gifts <- gifts + days}
return(gifts) # gimme those gifts back
}
xmas_gifts() # 12 days by default
xmas_gifts(98172)
library(tidyverse)
tibble(days = 1:100) %>%
mutate(gifts = sapply(days, xmas_gifts)) %>%
ggplot(aes(x=days, y=gifts)) +
geom_point(color="darkgreen", size=3) + geom_line(color="red") + theme_bw() + ggtitle("ALL THE GIFTS")
@jakeybob
Copy link
Author

snap

@jakeybob
Copy link
Author

IMG_0328

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment