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

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

Q39: It disappears when they are next to each other.

Intermediate problem. At this point, you can't understand unless you think about what the answer code is doing.

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;
            }
        }
    }
}

Since (0,0,0) = 1 is the initial value, set it withnew ().

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