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

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

Q17: Lifts for groups

Ruby

An example of the answer on p.092.

q17.rb


MEMBER, LIFT = 32, 6

@memo = {0 => 1, 1 => 1}
def board(remain)
    return @memo[remain] if @memo[remain]
    cnt = 0
    1.upto(LIFT) do |i|
        cnt += board(remain - i) if remain - i >= 0
    end
    @memo[remain] = cnt
end
puts board(MEMBER)

Rust

main.rs


use std::collections::HashMap;

fn main() {
    let mut q17 = Q17::new();
    println!("{}", q17.board(6, 32));
}

type PassengersWaitingForBoarding = i64;
type Patterns = i64;

struct Q17 {
    memo: HashMap<PassengersWaitingForBoarding, Patterns>,
}

impl Q17 {
    pub fn new() -> Q17 {
        let mut q17 = Q17 {
            memo: HashMap::new(),
        };
        q17.memo.insert(0, 1);
        q17.memo.insert(1, 1);
        return q17;
    }

    pub fn board(&mut self, number_of_seats: i64, passengers_waiting_for_boarding: i64) -> i64 {
        match self.memo.get(&passengers_waiting_for_boarding) {
            Some(pat) => return *pat,
            _ => {
                let patterns = (1..=number_of_seats).fold(0, |cnt, passengers| {
                    if passengers_waiting_for_boarding - passengers >= 0 {
                        cnt + &self.board(number_of_seats, passengers_waiting_for_boarding - passengers)
                    } else {
                        cnt
                    }
                });
                &self.memo.insert(passengers_waiting_for_boarding, patterns);
                return patterns;
            }
        }
    }
}

I implemented aggregation with fold (). It's okay that let mut cnt = 0; disappears, but it doesn't look good.

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