5

Problem: how can I write a function that receives a and b as inputs and returns all integers inbetween them. So, assuming we have a function called integers_inbetween that behaves like this, we should expect the following examples:

# Returns an array of integers in between a and b
integers_inbetween(1, 4)
[1] 2 3

and

# Returns an array of integers in between a and b
integers_inbetween(4, 1)
[1] 2 3

And

# Returns NULL if there are no integers inbetween a and b
integers_inbetween(3.5, 4)
[1] NULL

How can one implement that logic in R?

cigien
  • 57,834
  • 11
  • 73
  • 112
Jake Parker
  • 241
  • 1
  • 7

3 Answers3

3

This solution should work. I'm assuming the function should work if a > b and also if not. The way I wrote it, if after rounded a == b, the function returns NULL.

inbetween_integers <- function(a, b) {
    a <- round(a)
    b <- round(b)
    dist_ab <- abs(a-b)
    if (dist_ab <= 1)
        return(NULL)
    if (b < a)
        return(seq.int(from = b + 1, length.out = dist_ab - 1))
    return(seq.int(from = a + 1, length.out = dist_ab - 1))
}
eduardokapp
  • 1,612
  • 1
  • 6
  • 28
2

You can try the code below

inbetween_integers <- function(a, b) {
  u <- sort(c(a, b))
  res <- setdiff(ceiling(u[1]):floor(u[2]), c(a, b))
  if (!length(res)) {
    NULL
  } else {
    res
  }
}

and you will see

> inbetween_integers(1, 4)
[1] 2 3

> inbetween_integers(4, 1)
[1] 2 3

> inbetween_integers(3.5, 4)
NULL
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
1

This works regardless of the order of arguments. First this function sorts the arguments, then determines the minimum and maximum values in the sequence (exclusive of integer boundaries), then returns the sequence as requested.

integers_in_between<-function(x,y){
        values<-sort(c(x,y))
        minimum<-ifelse(ceiling(values[1])==values[1], ceiling(values[1])+1, ceiling(values[1]))
        maximum<-ifelse(floor(values[2])==values[2], floor(values[2])-1, floor(values[2]))
        if(maximum-minimum<0){
                NULL
        }else{
                minimum:maximum
        }
}
GuedesBF
  • 8,409
  • 5
  • 19
  • 37