Skip to content

Instantly share code, notes, and snippets.

@kencoba
Created September 29, 2020 01:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kencoba/b625a87c5127ff7adb435e29536eedea to your computer and use it in GitHub Desktop.
Save kencoba/b625a87c5127ff7adb435e29536eedea to your computer and use it in GitHub Desktop.
A translation from Ruby to Rust in the book :pp.013-017[「もっとプログラマ脳を鍛える数学パズル」](https://www.shoeisha.co.jp/book/detail/9784798153612)
use std::collections::HashMap;
struct Checker {
memo: HashMap<(i64, i64), i64>,
max_seat_at_one_table: i64,
}
impl Checker {
pub fn check(&mut self, remain: i64, pre: i64) -> i64 {
match &self.memo.get(&(remain, pre)) {
Some(cnt) => return **cnt,
_ => {
if remain < 0 {
return 0;
} else if remain == 0 {
return 1;
} else {
let mut count = 0;
for i in pre..=self.max_seat_at_one_table {
count += self.check(remain - i, i);
}
&self.memo.insert((remain, pre), count);
return count;
}
}
}
}
}
fn main() {
let mut chk = Checker {
memo: HashMap::new(),
max_seat_at_one_table: 10,
};
println!("{}", chk.check(100, 2));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_check() {
let number_of_people = 100;
let mut chk = Checker {
memo: HashMap::new(),
max_seat_at_one_table: 10,
};
assert_eq!(chk.check(number_of_people, 2), 437_420);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment