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?
Infinite number of rational numbers exist between any two distinct rational numbers. We know that a rational number is a number which can be written in the form of qp where p and q are integers and q =0.
Answer. 5 and -13 are excluded because it is given that it is between those numbers. Hence 16 integers.
Generally, In an open interval ( a , b ) (a, b) (a,b), the number of integers is b − a − 1 b-a-1 b−a−1. As for the last cookie, how many integers are there in a half-open interval [ a , b ) [a, b) [a,b) or ( a , b ] (a, b] (a,b]?
In this R tutorial you’ll learn how to test whether a number is an integer (i.e. a whole number). Let’s get started. First, let’s create a data object called x, which is containing an integer value (i.e. 5): Now you might say: Easy going, I’m simply using the is.integer function: Be careful!
Difference = 0.91 Number of integers between 1.0 and 1.91 is zero! Difference = 0.91 Note that there is no pattern. How can the number of integers between two real numbers be found?
Then just subtract the smaller number from the bigger number and then subtract 1. Our answer is eleven either way. Find how many integers are between two and eight. To determine the number of integers in between 2 and 8, we can simply write out the numbers and count.
To calculate the number of integers, find subtract the integers of interest and then subtract 1. As a proof of concept, calculate the number of integers that fall between 5 and 10 on a number line. We know there are 4 (6, 7, 8, 9). How many perfect squares satisfy the inequality ?
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)
if (abs(a - b) <= 1)
return(NULL)
if (b < a)
return(seq.int(from = b + 1, length.out = abs(a - b) - 1))
return(seq.int(from = a + 1, length.out = abs(a - b) - 1))
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With