Skip to content

Instantly share code, notes, and snippets.

@trinker
Last active September 15, 2022 15:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trinker/545574b9c45514d866d1770a969e3498 to your computer and use it in GitHub Desktop.
Save trinker/545574b9c45514d866d1770a969e3498 to your computer and use it in GitHub Desktop.
look and say sequence
# https://mathworld.wolfram.com/LookandSaySequence.html
library(ggplot2)
library(stringi)
tic <- Sys.time()
len <- 68
s <- rep(NA, len)
s[1] <- 1
tm <- rep(NA, len)
for (i in seq_len(len)) {
sp <- rle(strsplit(as.character(s[i]), '')[[1]])
s[i+1] <- paste(sp[[1]], sp[[2]], sep = '', collapse = '')
#cat(s[i+1], '\n')
t <- table(unlist(stringi::stri_extract_all_regex(s, "[0-9]")))
tm[i] <- as.numeric(difftime(Sys.time(), tic, units = 'secs'))
cat(i, '. ', paste0(round(100*t/sum(t), 1), '%', collapse = ' '), ' ', round(tm[i], 1), 's\n', sep =''); flush.console()
}
#nchar(s)
#t <- table(unlist(stringi::stri_extract_all_regex(s, "[0-9]"))); paste0(round(100*t/sum(t), 1), '%\n')
data = data.frame(i=seq_len(len), t=tm)
ggplot2::ggplot(data, ggplot2::aes(x=i, y=t)) +
#ggplot2::geom_line() +
ggplot2::geom_point() +
#ggplot2::geom_smooth(method =stats::loess) +
ggformula::geom_spline()
data.frame(i=seq_len(len), t=tm)
#mod <- lm(t~i, data=data)
mod <-loess(t~i, data=data, control=loess.control(surface="direct"))
mod <- with(data, smooth.spline(i, t))
new <- data.frame(i = (len + 1):(len + 20), t=NA)
new$t <- predict(mod, new$i)$y
rbind(data, new)
chars <- nchar(s)
datac = data.frame(i=seq_len(len), c = chars)[-70,]
modc <-loess(c~i, data=datac, control=loess.control(surface="direct"))
modc <- with(datac, smooth.spline(i, c))
new <- data.frame(i = (len + 1):(len + 20), c=NA)
new$c <- predict(modc, new$i)$y
rbind(datac, new)
library(pryr)
object_size(s)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment