[R] Lowest number in a numeric string

Petr Savicky savicky at cs.cas.cz
Thu Jun 14 12:25:46 CEST 2012


On Thu, Jun 14, 2012 at 01:08:53AM -0700, mogwai84 wrote:
> Hi all,
> 
> I've got a very long numeric string. I want to find the lowest number that
> isn't in that string.
> 
> E.G
> 
> String = 123456
> Therefore 7 is the lowest number not in that string
> 
> E.G.2
> 
> String = 1234567891011
> Therefore 13 is the lowest number not in that string.

Hi.

If the string is very long, like the first 1000 digits of pi, then
try the following, which uses a better bound on the necessary
number of digits than what i sent in a previous email.

  String <- paste(1:350, collapse="")
  s <- rev(as.numeric(strsplit(String, "")[[1]]))
  n <- length(s)
  for (dig in 1:9) {
      if (n*dig < (10^dig - 1)) break
  }
  x <- NULL
  for (d in 1:dig) {
      x <- c(x, embed(s, d) %*% 10^((d-1):0))
  }
  x <- unique(x)
  for (i in 1:(10^dig - 1)) {
      if (! i %in% x) {
          print(i)
          break
      }
  }
 
  [1] 355 

The result seems to be correct. The numbers 351, 352, 353, 354 do occur in
the sequence.

351 is in "135 136",
352 in "235 236",
353 in "335 336",
354 in "53 54".

Hope this helps.

Petr Savicky.



More information about the R-help mailing list