LoginSignup
0
0

More than 3 years have passed since last update.

「もっとプログラム脳を鍛える数学パズル」_Q02 (code:Ruby) -> Rust

Posted at

「もっとプログラマ脳を鍛える数学パズル」をRustで書き直すのは、ボケ防止にちょうど良いかもしれない、と思った。

Q02山手線でスタンプラリー

本書出版時(2018年)は29駅。2020年になって、駅の数が増えて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;
}

何の苦労もなく、そのままビットシフトできる。

試しに、29駅では36863のところ、30駅にしてみたら(q02(30,1,17))答えは40959と出た。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0