"Mathematical puzzles that train the program brain more" _Q02 (code: Ruby)-> Rust

I thought that rewriting "Mathematical puzzles to train the programmer's brain" with Rust might be just right for preventing blurring.

Q02 Stamp rally on the Yamanote line

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

"Mathematical puzzles that train the program brain more" _Q39 (code: Ruby)-> Rust
"Mathematical puzzles that train the program brain more" _Q02 (code: Ruby)-> Rust
"Mathematical puzzles that train the program brain more" _Q17 (code: Ruby)-> Rust
"Mathematical puzzles that train the program brain more" _Q01 (code: Ruby)-> Rust
"Mathematical puzzles that train the program brain more" _pp.018-020 (code: Ruby)-> Rust
"Mathematical puzzles that train your program brain more" _Q61 (code: Ruby)-> Rust (& SQL)
"Math puzzles that train your program brain more" _Q41 (code: Ruby)-> Rust
"Math puzzles that train your program brain more" _Q18 (code: Ruby)-> Rust
"Mathematical puzzle to train the program brain more" _Q40 (code: Ruby)-> Rust unfinished
An attempt at "a math puzzle that trains the Rust brain more".
The languages that influenced Rust