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.

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

Last updated at Posted at 2020-10-01

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

Q39:隣り合うと消えちゃうんです

中級問題。このくらいになると、解答コードが何やってるのかも考えないと、分からなくなる。

Ruby

q39_1.rb
N = 11

@memo = {[0,0,0] => 1}
def pair(unused, onetime, neighbor)
    if @memo[[unused, onetime, neighbor]]
        return @memo[[unused, onetime, neighbor]]
    end
    cnt = 0
    if unused > 0
        cnt += pair(unused - 1, onetime + neighbor, 1)
    end
    if onetime > 0
        cnt += onetime * pair(unused, onetime - 1 + neighbor, 0)
    end
    @memo[[unused, onetime, neighbor]] = cnt
end

puts pair(N, 0, 0)

Rust

main.rs
use std::collections::HashMap;

fn main() {
    let number_of_colors = 11;
    let mut q39 = Q39::new();
    println!("{}", q39.pair(number_of_colors, 0, 0));
}

struct Q39 {
    memo: HashMap<(i64, i64, i64), i64>,
}

impl Q39 {
    pub fn new() -> Q39 {
        let mut new_instance = Q39 {
            memo: HashMap::new(),
        };
        new_instance.memo.insert((0, 0, 0), 1);
        return new_instance;
    }
    pub fn pair(&mut self, unused: i64, onetime: i64, neighbor: i64) -> i64 {
        match &self.memo.get(&(unused, onetime, neighbor)) {
            Some(v) => return **v,
            _ => {
                let mut count = 0;
                if unused > 0 {
                    count += &self.pair(unused - 1, onetime + neighbor, 1);
                }
                if onetime > 0 {
                    count += onetime * &self.pair(unused, onetime - 1 + neighbor, 0);
                }
                &self.memo.insert((unused, onetime, neighbor), count);
                return count;
            }
        }
    }
}

(0,0,0) = 1は、初期値なのでnew()で設定する。

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?