Is there a similar construct like" if a ? b : c" in rust?

hello,

I want to write a binary search for a vector of tuples (start,end). (start,end) are pairs and they cover a single continuous range. I get error after error when trying to fix it. Can someone link a helpful resource or give an opinion how to best program this?
I check if the tuple at position mid+1 covers my offset, if yes I return this tuple if not I recurse with the side that has the offset in its intervals.
Is there something equivalent to "if a ? b : c" like in java or c++?

pub fn tuple_matches(tuple:&(usize,usize), offset:usize) -> bool {
	if offset > tuple.0 && offset < tuple.1 {
		return true;
	} else {
		false
	}
}

pub fn binary_search_get_index(vector:&[(usize,usize)], offset:usize) -> &(usize,usize) {
	let low = 0;
	let high = vector.len();
	let mid = high/2;
	let tuple = vector.get(mid+1).unwrap();

	if tuple_matches(tuple, offset) {
		return tuple;
	} else {
		let tuple = vector.get(mid).unwrap();
		let tuple2 = if tuple.0 > offset {
			binary_search_get_index(&vector[0..mid], offset)}
		} else {
			binary_search_get_index(&vector[mid+1..high], offset)
			};
	tuple2
}

Yes, just use if else. In Rust, everything is an expression.

To literally answer the title, that would be if a { b } else { c }.

But if you having other errors, it might be helpful to post what those are.

Instead of tuples you can use std::ops::Range<usize> instead, which has .contains().

The standard library already has an implementation of binary search. To find the interval that contains a given number, you could do something like this:

use std::cmp::Ordering;

fn tuple_cmp(tuple: &(usize, usize), offset: usize) -> Ordering {
    if offset < tuple.0 {
        Ordering::Greater
    } else if offset > tuple.1 {
        Ordering::Less
    } else {
        Ordering::Equal
    }
}

pub fn binary_search_get_index(vector:&[(usize,usize)], offset:usize) -> (usize,usize) {
	match vector.binary_search_by(|tuple| tuple_cmp(tuple, offset)) {
	    Ok(idx) => vector[idx],
	    Err(_) => panic!("No tuple contains {offset}"),
	}
}

fn main() {
    let ranges = [(0, 2), (3, 7), (8, 10)];
    
    for i in 0..=10 {
        println!("{} {:?}", i, binary_search_get_index(&ranges, i));
    }
}
0 (0, 2)
1 (0, 2)
2 (0, 2)
3 (3, 7)
4 (3, 7)
5 (3, 7)
6 (3, 7)
7 (3, 7)
8 (8, 10)
9 (8, 10)
10 (8, 10)
2 Likes

thanks all of you!

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.