Created
October 26, 2018 20:08
-
-
Save WinstonCampeau/f6057afebb43f3249be40b8aa0d31ac9 to your computer and use it in GitHub Desktop.
R - Middle Square Method
This file contains 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
# seed requires an even length number, no restrictions on length | |
# number is the number of numbers you wish to be generated | |
# raw=1 returns raw data, aka "0429" instead of 429 | |
# this method is horrible, but still often used as a teaching method | |
MSM <- function(seed, number, raw) { | |
options("scipen" = 2*nchar(seed)) | |
if(missing(number)) { | |
number <- 15 | |
} | |
if(missing(raw)) { | |
raw <- 1 | |
} | |
if(nchar(seed)%%2 != 0){ | |
cat("Please enter a seed with an even number of digits") | |
cat("\n") | |
stop | |
} else | |
while_char <- seed | |
library(stringi) | |
MSM_LIST <- c() | |
for(i in 1:number){ | |
seed_sqr <- seed^2 | |
#this while loop adds trailing zeros | |
while(nchar(seed_sqr) < 2*nchar(while_char)) { | |
seed_sqr<- stri_pad_left(seed_sqr, 2*nchar(while_char), 0) | |
} | |
#this section identifies the middle number | |
left_digit <- nchar(seed_sqr)/4 + 1 | |
right_digit <- nchar(seed_sqr) - (nchar(seed_sqr)/4) | |
ran_num <- as.numeric(substr(seed_sqr, left_digit, right_digit)) | |
while(nchar(ran_num) < nchar(while_char)){ | |
ran_num <- stri_pad_left(ran_num, nchar(while_char), 0) | |
} | |
MSM_LIST[i] <- ran_num | |
ran_num <- as.numeric(ran_num) | |
seed <- ran_num | |
while_char <- substr(seed_sqr, left_digit, right_digit) | |
} | |
ifelse(raw==1, MSM_LIST, | |
ifelse(raw==0, MSM_LIST <- as.numeric(MSM_LIST)) | |
) | |
MSM_LIST | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment