@math-x-ts/generix
Version:
This library tasks is to generate combinations and permutations
49 lines (48 loc) • 3.06 kB
TypeScript
/**
* Class to generate permutations with & without repetition.
*/
export default class Permutation {
/**
* Generates all possible permutations without repetition of a given array of elements,
* with the option to specify the minimum (n) and maximum (m) lengths of the generated permutations.
* The maximum must be less or equal to the number of elements.
*
* @template S - The type of the elements in the input array.
* @param {Array<S>} elements - The input array containing the elements to generate permutations for.
* @param {number} [n=elements.length] - The minimum number of elements in the generated permutations (inclusive).
* @param {number} [m=n] - The maximum number of elements in the generated permutations (inclusive).
* @param {Array<S>} [combo=[]] - An optional array to store the current combination during recursion.
* Should not be provided when calling the function initially.
*
* @returns {Array<Array<S>>} - An array of arrays, where each inner array is a permutation of the input elements.
*/
private static generateWithoutRepetition;
/**
* Generates all possible permutations without repetition of a given array of elements, with the option to specify
* the minimum (n) and maximum (m) lengths of the generated permutations.
*
* @template S - The type of the elements in the input array.
* @param {Array<S>} elements - The input array containing the elements to generate permutations for.
* @param {number} [n=elements.length] - The minimum length of the generated permutations (inclusive).
* @param {number} [m=n] - The maximum length of the generated permutations (inclusive).
* @returns {Array<Array<S>>} - An array of arrays, where each inner array is a permutation of the input elements.
*/
static withoutRepetition<S>(elements: Array<S>, n?: number, m?: number): S[][];
/**
* Generates all possible permutations with repetition of a given array of elements,
* with the option to specify the minimum (n) and maximum (m) lengths of the generated permutations.
*
* @template S The type of elements in the input array and resulting permutations.
* @param {Array<S>} elements A set of elements used during the generation process.
* @param {number} [n=elements.length] The minimum number of elements in the generated permutations (inclusive).
* @param {number} [m=n] The maximum number of elements in the generated permutations (inclusive).
*
* @returns {Array<Array<S>>} An array of arrays containing all the possible permutations.
*
* @example
* // Generate permutations with repetition for the elements 'a', 'b', and 'c', with a size between 2 and 3
* const result = Permutations.withRepetition(['a', 'b', 'c'], 2, 3);
* [['a', 'a'], ['a', 'b'], ['a', 'c'], ['b', 'b'], ['b', 'c'], ['c', 'c'], ['a', 'a', 'a'], ['a', 'a', 'b'], ...]
*/
static withRepetition<S>(elements: Array<S>, n?: number, m?: number): Array<Array<S>>;
}