I thought that rewriting "Mathematical puzzles to train the programmer's brain" with Rust might be just right for preventing blurring.
At the time of publication of this book (2018), there are 29 stations. By 2020, the number of stations has increased to 30.
Ruby
q02.rb
N = 29
a, b = 1, 17
n = (a - b).abs
puts (1 << (n - 1)) + (1 << (N - n - 1)) - 1
Rust
main.rs
fn main() {
println!("{}", q02(29, 1, 17));
}
pub fn q02(num_of_stations: i64, entraining_point: i64, exit_station: i64) -> i64 {
let passing_stations = (entraining_point - exit_station).abs();
return (1 << (passing_stations - 1)) + (1 << (num_of_stations - passing_stations - 1)) - 1;
}
You can bit shift as it is without any trouble.
As a test, at 29 stations, 36863, but at 30 stations (q02 (30,1,17)
), the answer was 40959.
Recommended Posts