Skip to content

Instantly share code, notes, and snippets.

@nwstephens
Last active January 18, 2023 17:21
Show Gist options
  • Select an option

  • Save nwstephens/9771d412bfc69f5b0ea724656326149f to your computer and use it in GitHub Desktop.

Select an option

Save nwstephens/9771d412bfc69f5b0ea724656326149f to your computer and use it in GitHub Desktop.
# Palindromic Numbers
# Nathan Stephens
# 1/18/2023
library(magrittr)
library(ggplot2)
# Reverse digits of an integer
f<-function(x){ x %>%
as.character %>%
strsplit("") %>%
unlist %>%
rev %>%
paste(collapse = "") %>%
as.numeric
}
# Calculate number of iterations to achieve palindrome
out<-matrix(nrow=0, ncol=3)
for(x in 1000:9999){
y<-x
i<-0
while(f(y)!=y){
y<-y+f(y)
i<-i+1
if(i==30){i<-NA; break}
}
out<-rbind(out, cbind(x,y,i))
}
# Organize data for plotting
df<-data.frame(
group=out[,1]%/%1000*1000,
increment=out[,1]%%1000,out,
iterations=out[,3],
log10_iterations=log10(out[,3]),
missing=is.na(out[,3])
)
# Plot
ggplot() +
geom_line(aes(increment, log10_iterations), df) +
facet_grid(rows = vars(group)) +
geom_vline(aes(xintercept=increment), df[df$missing,], color="tomato") +
geom_vline(aes(xintercept=increment), df[is.infinite(df$log10_iterations),], color="cyan") +
labs(title="Palindromic Number",
subtitle="https://en.wikipedia.org/wiki/Palindromic_number",
caption="(Cyan) Zero iterations; (Red) Iterations exceeded calculation")
@nwstephens
Copy link
Author

image

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