This is my Rust implementation of the rabbit searching algorithm I found yesterday in this video. The problem statement is as follows.
There are 100 holes in a line. A rabbit is in one of the holes. You need to catch the rabbit. However, you can only look at one hole at a time. If the rabbit is in the hole that you looked, you catch the rabbit. If the rabbit is not in the hole, the rabbit will move to an adjacent hole.
The algorithm works as intended. You need to search two times. First, do a whole pass, and then do another pass but starting at index 1. However, I'm not familiar with Rust yet, so there are some awkward code snippets in my implementation. How can I improve the code according to Rust's best practices? Thanks.
use rand::Rng;
const N: i32 = 100;
fn main() {
let mut rabbit_pos: i32 = rand::thread_rng().gen_range(0..N);
println!("Rabbit is at {}", rabbit_pos);
let searched = search(&mut rabbit_pos);
println!("Rabbit is at {}", rabbit_pos);
}
fn search(rabbit_pos: &mut i32) -> i32 {
let mut found = false;
let mut found_pos = 0;
for i in 0..N {
if lookup(i, rabbit_pos) {
println!("Found {}", i);
found = true;
found_pos = i;
break;
}
}
if found {
return found_pos;
}
for i in 1..N {
if lookup(i, rabbit_pos) {
println!("Found {}", i);
found = true;
found_pos = i;
break;
}
}
found_pos
}
fn lookup(n: i32, rabbit_pos: &mut i32) -> bool {
println!("Searching for {}", n);
if *rabbit_pos == n {
return true;
} else {
move_rabbit(rabbit_pos);
return false;
}
}
fn move_rabbit(prev: &mut i32) {
let new_pos = match *prev {
0 => 1,
i if i == (N-1) => N-2,
_ => *prev + (rand::thread_rng().gen_range(0..2) * 2 - 1),
};
println!("Rabbit moved from {} to {}", *prev, new_pos);
*prev = new_pos;
}