View Source FastMath.Combinatorics (fastmath_combinatorics v0.1.0)
FastMath.Combinatorics
provides fast and efficient combinatorics functions.
It includes implementations for factorials, permutations, combinations, and other fundamental combinatorics operations.
Summary
Functions
Calculates combinations ( C(n, r) = rac{n!}{r!(n-r)!} ).
Calculates the factorial of n
. Uses permutations
Efficiently generates all combinations of size r
from the given list.
Calculates the number of permutations ( P(n, r) = n! / (n-r)! ) using an iterative approach.
Calculates variations ( V(n, r) = n^r ).
Functions
Calculates combinations ( C(n, r) = rac{n!}{r!(n-r)!} ).
Parameters
n
- An integer representing the total number of items.r
- An integer representing the number of selected items, ( r leq n ).
Returns
The number of combinations.
Examples
iex> FastMath.Combinatorics.combinations(5, 3)
10
Calculates the factorial of n
. Uses permutations
Parameters
n
- A non-negative integer.
Returns
The factorial of n
.
Examples
iex> FastMath.Combinatorics.factorial(5)
120
Efficiently generates all combinations of size r
from the given list.
Uses symmetry to optimize generation when r
is close to n
.
Parameters
list
- A list of items.r
- The size of each combination.
Returns
A list of all possible combinations of size r
.
Examples
iex> FastMath.Combinatorics.generate_combinations([1, 2, 3, 4], 3)
[[2, 3, 4], [1, 3, 4], [1, 2, 4], [1, 2, 3]]
iex> FastMath.Combinatorics.generate_combinations([1, 2, 3, 4], 1)
[[1], [2], [3], [4]]
iex> FastMath.Combinatorics.generate_combinations([1, 2, 3, 4], 0)
[[]]
iex> FastMath.Combinatorics.generate_combinations([1, 2, 3, 4], 4)
[[1, 2, 3, 4]]
Calculates the number of permutations ( P(n, r) = n! / (n-r)! ) using an iterative approach.
This method avoids the computation of full factorials by directly calculating the product of the necessary range ( n cdot (n-1) cdot ... cdot (n-r+1) ), making it more efficient for larger values of ( n ) and ( r ).
Parameters
n
- The total number of items (integer).r
- The number of selected items (integer, ( r leq n )).
Returns
The number of permutations as an integer.
Examples
iex> FastMath.Combinatorics.permutations(5, 3)
60
iex> FastMath.Combinatorics.permutations(6, 2)
30
Calculates variations ( V(n, r) = n^r ).
Parameters
n
- An integer representing the total number of items.r
- An integer representing the number of selected items.
Returns
The number of variations.
Examples
iex> FastMath.Combinatorics.variations(2, 3)
8