Skip to content

Commit

Permalink
Test checked_binomial
Browse files Browse the repository at this point in the history
Only test for `n <= 500` but only a few values of the last row do not already have overflow on a 64 bits computer.
NOTE: Not faster with an array updated in-place.
  • Loading branch information
Philippe-Cholet committed Aug 18, 2023
1 parent cfb2ec9 commit 65e08d4
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/combinations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,25 @@ pub(crate) fn checked_binomial(mut n: usize, mut k: usize) -> Option<usize> {
Some(c)
}

#[test]
fn test_checked_binomial() {
// With the first row: [1, 0, 0, ...] and the first column full of 1s, we check
// row by row the recurrence relation of binomials (which is an equivalent definition).
// For n >= 1 and k >= 1 we have:
// binomial(n, k) == binomial(n - 1, k - 1) + binomial(n - 1, k)
const LIMIT: usize = 500;
let mut row = vec![Some(0); LIMIT + 1];
row[0] = Some(1);
for n in 0..=LIMIT {
for k in 0..=LIMIT {
assert_eq!(row[k], checked_binomial(n, k));
}
row = std::iter::once(Some(1))
.chain((1..=LIMIT).map(|k| row[k - 1]?.checked_add(row[k]?)))
.collect();
}
}

/// For a given size `n`, return the count of remaining combinations or None if it would overflow.
fn remaining_for(n: usize, first: bool, indices: &[usize]) -> Option<usize> {
let k = indices.len();
Expand Down

0 comments on commit 65e08d4

Please sign in to comment.