Skip to content

Instantly share code, notes, and snippets.

@kencoba
Created September 29, 2020 01:36
Show Gist options
  • Save kencoba/e30e6a18cd2804f9c4a7ce2ea0f6a605 to your computer and use it in GitHub Desktop.
Save kencoba/e30e6a18cd2804f9c4a7ce2ea0f6a605 to your computer and use it in GitHub Desktop.
A translation from Ruby to Rust in the book :pp.018-020[「もっとプログラマ脳を鍛える数学パズル」](https://www.shoeisha.co.jp/book/detail/9784798153612)
fn main() {
println!("{n}P{r} = {x}", n = 5, r = 2, x = permutation(5, 2));
println!("{n}C{r} = {x}", n = 5, r = 2, x = combination(5, 2));
}
pub fn permutation(n: i64, r: i64) -> i64 {
let mut result = 1;
for i in (n - r + 1)..=n {
result *= i;
}
return result;
}
pub fn combination(n: i64, r: i64) -> i64 {
let mut result = 1;
for i in 1..=r {
result = result * (n - i + 1) / i;
}
return result;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_permutation() {
assert_eq!(permutation(1, 1), 1);
assert_eq!(permutation(6, 6), 720);
assert_eq!(permutation(5, 2), 20);
}
#[test]
fn test_combination() {
assert_eq!(combination(1, 1), 1);
assert_eq!(combination(6, 6), 1);
assert_eq!(combination(5, 2), 10);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment