Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test if a value lies within a Range?

Tags:

rust

I'd like to be able to create a Range and then test if a variable is contained in that range. Something that looks like this:

fn main() {
    let a = 3..5;
    assert!(a.contains(4));
}

Right now, the only obvious thing I see is to use Iterator::any. This is ugly because it would take an O(1) operation and make it O(n):

fn main() {
    let mut a = 3..5;
    assert!(a.any(|v: i32| v == 4));
}
like image 597
Shepmaster Avatar asked Feb 01 '15 16:02

Shepmaster


People also ask

How do you check if a number lies in a range?

This can be done using the lower_bound function. If there is any value which is equal to the query, then the number overlaps the range. If there is no value which is equal to the query, then check if the greater element is hashed as 1 or 2. If it is hashed as 1, then the number does not overlaps, else it does overlap.

How do you check if a value lies in a range in R?

between() function in R Language is used to check that whether a numeric value falls in a specific range or not. A lower bound and an upper bound is specified and checked if the value falls in it.

How do you check if a value is in a range in Python?

You can check if a number is present or not present in a Python range() object. To check if given number is in a range, use Python if statement with in keyword as shown below. number in range() expression returns a boolean value: True if number is present in the range(), False if number is not present in the range.

How do you check if a number lies in a range in Java?

As with ValueRange's of() method, we passed lowerBound and upperBound to Range's static between() method to create Range objects. We then used the contains() method to check whether number existed within each object's range.


3 Answers

As of Rust 1.35, the original code will almost1 compile as-is using Range::contains:

fn main() {     let a = 3..5;     assert!(a.contains(&4)); } 

1 Passing &4 instead of 4 to contains().

like image 105
Shepmaster Avatar answered Sep 28 '22 11:09

Shepmaster


There is nothing on Range itself (at present, anyway), but it is not difficult to do this; after all, it just takes a couple of comparisons:

4 >= a.start && 4 < a.end
like image 29
Chris Morgan Avatar answered Sep 28 '22 12:09

Chris Morgan


You can use match too:

fn main() {
    let v = 132;
    match v {
        1...100 => println!("Inside"),
        _ => println!("Outside")
    }
}
like image 26
Ruben Kostandyan Avatar answered Sep 28 '22 11:09

Ruben Kostandyan