Last active
January 18, 2023 17:21
-
-
Save nwstephens/9771d412bfc69f5b0ea724656326149f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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") |
Author
nwstephens
commented
Jan 18, 2023

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