fn floor_ceil(arr: &[i32], target: i32) -> (Option<i32>, Option<i32>) {
let mut floor = None;
let mut ceil = None;
for &num in arr {
if num <= target {
floor = Some(num);
}
if num >= target && ceil.is_none() {
ceil = Some(num);
}
}
(floor, ceil)
}
fn main() {
let arr = [1, 3, 5, 7, 9];
let target = 6;
let (floor, ceil) = floor_ceil(&arr, target);
println!("Floor: {:?}, Ceil: {:?}", floor, ceil);
}The code iterates through the sorted array. It updates floor whenever it finds a number less than or equal to the target, so floor ends at 5. It sets ceil the first time it finds a number greater than or equal to the target, which is 7.
Floor is defined as the greatest element in the array that is less than or equal to the target value.
fn floor_ceil_binary_search(arr: &[i32], target: i32) -> (Option<i32>, Option<i32>) {
let mut left = 0;
let mut right = arr.len();
while left < right {
let mid = left + (right - left) / 2;
if arr[mid] == target {
return (Some(arr[mid]), Some(arr[mid]));
} else if arr[mid] < target {
left = mid + 1;
} else {
right = mid;
}
}
let floor = if left > 0 { Some(arr[left - 1]) } else { None };
let ceil = if left < arr.len() { Some(arr[left]) } else { None };
(floor, ceil)
}
fn main() {
let arr = [2, 4, 6, 8, 10];
let target = 5;
let (floor, ceil) = floor_ceil_binary_search(&arr, target);
println!("Floor: {:?}, Ceil: {:?}", floor, ceil);
}The binary search finds the position where 5 would be inserted. The floor is the element before that position (4), and the ceil is the element at that position (6).
fn floor_ceil_bug(arr: &[i32], target: i32) -> (Option<i32>, Option<i32>) {
let mut floor = None;
let mut ceil = None;
for &num in arr {
if num < target {
floor = Some(num);
}
if num > target {
ceil = Some(num);
break;
}
}
(floor, ceil)
}
fn main() {
let arr = [1, 3, 5, 7];
let target = 3;
let (floor, ceil) = floor_ceil_bug(&arr, target);
println!("Floor: {:?}, Ceil: {:?}", floor, ceil);
}The code only updates floor if num < target, so it skips 3 for floor. It sets ceil at first num > target, which is 5. So floor is 1, ceil is 5.
fn count_between_floor_ceil(arr: &[i32], target: i32) -> usize {
let mut floor_idx = None;
let mut ceil_idx = None;
for (i, &num) in arr.iter().enumerate() {
if num <= target {
floor_idx = Some(i);
}
if num >= target && ceil_idx.is_none() {
ceil_idx = Some(i);
}
}
match (floor_idx, ceil_idx) {
(Some(f), Some(c)) => c - f + 1,
_ => 0,
}
}
fn main() {
let arr = [1, 2, 4, 6, 8];
let target = 5;
let count = count_between_floor_ceil(&arr, target);
println!("Count: {}", count);
}Floor is 4 at index 2, ceil is 6 at index 3, so count is 3 - 2 + 1 = 2 elements. But check carefully: elements are 4 and 6 only, so count is 2.
Wait, the code counts inclusive indices, so 3 - 2 + 1 = 2 elements.
Re-examining the code and array: floor index = 2 (value 4), ceil index = 3 (value 6), count = 2.
