0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

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

Posted at

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

Q01:一発で決まる多数決

本筋ではないけれど、このクイズの設定の微妙なところは、「じゃんけんの勝ち負け」は「多数決の勝ち負け」と関係ないところ。「チョキ2でパー2なら、チョキの勝ちじゃん」と、本筋でないところで混乱した・・・

Ruby

q01_2.rb
N = 100

cnt = 0
0.upto(N) do |left|
    left.upto(N) do |right|
        all = [left, right - left, N - right]
        cnt += 1 if all.count(all.max) == 1
    end
end
puts cnt

Rust

main.rs
fn main() {
    let mut q01 = Q01{ num_of_people:100,};
    let answer = q01.solve();

    println!("{}", answer);
}

struct Q01 {
    num_of_people:i64,
}

impl Q01 {
    pub fn solve(&mut self) -> i64 {
        let mut count = 0;
        for left in 0..=self.num_of_people {
            for right in left..=self.num_of_people {
                let all = vec![left, right - left, self.num_of_people - right];
                let max_value = all.iter().max().unwrap();
                let c = all.iter().filter(|&v| *v == *max_value).count();
                if c == 1 {
                    count += 1;
                }
            }
        }
        return count;
    }
}

こんな感じか。Vecに対する最大値や走査は一旦iter()を通す必要がある。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?