Skip to content

Commit

Permalink
feat(math): add factorial. permutation/combination fns
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Jan 9, 2023
1 parent e69a1c8 commit 965af0d
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 0 deletions.
3 changes: 3 additions & 0 deletions packages/math/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,9 @@
"./mix": {
"default": "./mix.js"
},
"./permutations": {
"default": "./permutations.js"
},
"./prec": {
"default": "./prec.js"
},
Expand Down
1 change: 1 addition & 0 deletions packages/math/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export * from "./interval.js";
export * from "./libc.js";
export * from "./min-error.js";
export * from "./mix.js";
export * from "./permutations.js";
export * from "./prec.js";
export * from "./prime.js";
export * from "./ratio.js";
Expand Down
53 changes: 53 additions & 0 deletions packages/math/src/permutations.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/**
* Computes factorial for `n`. Throws an error if `n < 0`.
*
* @param n
*/
export const factorial = (n: number) => {
if (n < 0) throw new Error(`illegal argument: ${n}`);
let res = 1;
for (let i = 1; i <= n; i++) res *= i;
return res;
};

/**
* Computes `n ** k`
*
* @param n number of choices
* @param k number of selected
*/
export const permutationsWithRep = (n: number, k: number) => n ** k;

/**
* Computes `n! / (n - k)!`
*
* @remarks
* Reference:
* https://en.wikipedia.org/wiki/Permutation#k-permutations_of_n
*
* @param n number of choices
* @param k number of selected
*/
export const permutationsWithoutRep = (n: number, k: number) =>
factorial(n) / factorial(n - k);

/**
* Computes `(n + k - 1)! / (k! * (n - 1)!)`
*
* @param n number of choices
* @param k number of selected
*/
export const combinationsWithRep = (n: number, k: number) =>
factorial(n + k - 1) / (factorial(k) * factorial(n - 1));

/**
* Computes `n! / (k! * (n - k)!)`
*
* @remarks
* https://en.wikipedia.org/wiki/Combination#Number_of_k-combinations
*
* @param n number of choices
* @param k number of selected
*/
export const combinationsWithoutRep = (n: number, k: number) =>
factorial(n) / (factorial(k) * factorial(n - k));

0 comments on commit 965af0d

Please sign in to comment.