Ich dachte, dass das Umschreiben von "Mathe-Rätseln, die das Gehirn des Programmierers mehr trainieren" mit Rust genau richtig sein könnte, um Unschärfe zu verhindern.
Zwischenproblem. Zu diesem Zeitpunkt können Sie nur verstehen, was der Antwortcode bewirkt.
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;
}
}
}
}
Da (0,0,0) = 1
der Anfangswert ist, setzen Sie ihn mit new ()
.
Recommended Posts