You ara given a Vec<(u32, u32)> where the first position represents a start and the…
- User
You ara given a Vec<(u32, u32)> where the first position represents a start and the second the end. This vector is already sorted. You are also given a tuple (u32, u32), with a start and end coordinates. You will need to find the tuple in the Vec that satisfies start < x < end, where X represents the start of the second tuple given. This implementation needs to be in Rust and be the most efficient and fastest. You are free to use any crate, algorithm, trick you want.
- Assistant
To find the tuple in a sorted
Vec<(u32, u32)>that satisfiesstart < x < end, wherexis the start of a given tuple, a binary search will be efficient. Rust's standard library provides binary search functionalities for slices, which we can leverage here. - User
this is my implementation:
use std::cmp::Ordering;
fn find_range<'a>(ranges: &'a [(u32, u32)], target: (u32, u32)) -> Option<&'a (u32, u32)> { let idx = ranges .binary_search_by(|(start, end)| { if target.0 < *start { Ordering::Less } else if target.0 > *end { Ordering::Greater } else { Ordering::Equal } }) .ok()?;
codeSome(&ranges[idx])}
fn main() { let ranges = vec![(0, 10), (15, 20), (25, 30), (40, 50)]; let target = (18, 25);
codeif let Some(range) = find_range(&ranges, target) { println!("Found range: {:?}", range); } else { println!("No range found"); }}
but the main() should produce "Found range: (15,20)", because 18 is within 15-20; instead is printing "No range found"
- Assistant
- User
ok, explain me something:
since the input ranges are sorted, a binary search and the linear search would not be basically the same? If the input is sorted, both the binary search and the linear search will look up one after another until find the correct one
- Assistant
- User
then go again:
You ara given a Vec<(u32, u32)> where the first position represents a start and the second the end. This vector is already sorted. You are also given a tuple (u32, u32), with a start and end coordinates. You will need to find the tuple in the Vec that satisfies start < x < end, where X represents the start of the second tuple given. This implementation needs to be in Rust and be the most efficient and fastest. You are free to use any crate, algorithm, trick you want.
try to use the .binary_search_by functions or try to use other crates
- Assistant