rs_stats/utils/combinatorics.rs
1//! Provides functions for combinatorial calculations.
2
3/// Calculate the factorial of a number n.
4///
5/// # Arguments
6/// * `n` - The number to compute the factorial of.
7///
8/// # Returns
9/// * `u64` - The factorial of n.
10pub fn factorial(n: u64) -> u64 {
11 match n {
12 0 => 1,
13 1 => 1,
14 _ => (2..=n).product::<u64>(),
15 }
16}
17
18/// Calculate the number of permutations of n items taken k at a time.
19///
20/// # Arguments
21/// * `n` - The total number of items.
22/// * `k` - The number of items to choose.
23///
24/// # Panics
25/// If `k` is greater than `n`, this function will panic.
26///
27/// # Returns
28/// * `u64` - The number of permutations.
29pub fn permutation(n: u64, k: u64) -> u64 {
30 if k > n {
31 panic!("k cannot be greater than n");
32 }
33 ((n - k + 1)..=n).product::<u64>()
34}
35
36/// Calculate the number of combinations of n items taken k at a time.
37///
38/// # Arguments
39/// * `n` - The total number of items.
40/// * `k` - The number of items to choose.
41///
42/// # Panics
43/// If `k` is greater than `n`, this function will panic.
44///
45/// # Returns
46/// * `u64` - The number of combinations.
47pub fn combination(n: u64, k: u64) -> u64 {
48 if k > n {
49 panic!("k cannot be greater than n");
50 }
51 let k = if k > n - k { n - k } else { k };
52 (1..=k).fold(1, |acc, x| acc * (n - x + 1) / x)
53}