Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find the number of 5 digit numbers that contain four 5s

I want to find 5 digit numbers that have four 5s. I do the following:

data <- str_split(as.character(x = 10000:99999), pattern = "")

but when I try to find the number of lists that contain four 5s

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

sapply(data, function(x) c("5", "5", "5", "5") %in% data[[x]])
it gives me an error "Error in data[[x]] : no such index at level 1":

What am I doing wrong? any other more elegant solution?

>Solution :

Try this?

> x <- 10000:99999

> x[nchar(gsub("[^5]", "", x)) == 4 & nchar(x)==5]
 [1] 15555 25555 35555 45555 50555 51555 52555 53555 54555 55055 55155 55255
[13] 55355 55455 55505 55515 55525 55535 55545 55550 55551 55552 55553 55554
[25] 55556 55557 55558 55559 55565 55575 55585 55595 55655 55755 55855 55955
[37] 56555 57555 58555 59555 65555 75555 85555 95555

Or, you can generalize it like below

# number of digits
n <- 5 
# number of 5s
m <- 4
# output
(x <- 10^(n - 1):(10^n - 1))[nchar(gsub("[^5]", "", x)) == m]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading