binomial_coefficient.nbt 923 B

1234567891011121314151617181920212223242526
  1. # Binomial coefficient using Pascal's rule
  2. #
  3. # Adapted from the Python version here:
  4. # https://en.wikipedia.org/wiki/Binomial_coefficient
  5. #
  6. # TODO: This could really benefit from logical and/or operators
  7. fn binomial_coefficient(n: Scalar, k: Scalar) -> Scalar =
  8. if k < 0
  9. then 0
  10. else if k > n
  11. then 0
  12. else if k > n - k # Take advantage of symmetry
  13. then binomial_coefficient(n, n - k)
  14. else if k == 0
  15. then 1
  16. else if n <= 1
  17. then 1
  18. else binomial_coefficient(n - 1, k) + binomial_coefficient(n - 1, k - 1)
  19. assert_eq(binomial_coefficient(10, 0), 1)
  20. assert_eq(binomial_coefficient(10, 1), 10)
  21. assert_eq(binomial_coefficient(10, 2), 45)
  22. assert_eq(binomial_coefficient(10, 6), 210)
  23. assert_eq(binomial_coefficient(10, 9), 10)
  24. assert_eq(binomial_coefficient(10, 10), 1)