[This article was first published on Xi'an's Og » R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
The mathematical puzzle from the weekend edition of Le Monde from a few weeks ago was not too hard to solve by induction but my R code failed miserably! The puzzle was as follows:
A calculator is broken in such a way that it starts by exhibiting 0, then pressing 4, 6 or 0 keeps adding this figure to the right of the current number (if not zero), while pressing 2 divides the current number by 2. For instance, a possible sequence is
0 4 [press 4] 46 [press 6] 23 [press 2] 230 [press 0]Is it possible to exhibit any integer?
I thus wrote the simple R code
library(gsubfn) digitBase=function(n){ strapply(as.character(n), ".", as.numeric)[[1]] } check=function(x){ step=0 xdigits=digitBase(x) ok=sum(xdigits==0)+sum(xdigits==4)+sum(xdigits==6) if (ok<length(xdigits)){ y=2*x step=1+check(y) } step }
which unfortunately runs very quickly into problems as can be seen by calling
> check(7) Error in if (ok < length(xdigits)) { : missing value where TRUE/FALSE needed In addition: Warning messages: 1: In do.call(FUN, as.list(s[, j])) : NAs introduced by coercion 2: In do.call(FUN, as.list(s[, j])) : NAs introduced by coercion 3: In do.call(FUN, as.list(s[, j])) : NAs introduced by coercion
because the 2x…x2x7 value gets out of bounds…
Filed under: R, Statistics Tagged: Le Monde, mathematical puzzle
To leave a comment for the author, please follow the link and comment on their blog: Xi'an's Og » R.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.