I thought that rewriting "Mathematical puzzles to train the programmer's brain" with Rust might be just right for preventing blurring.
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