A JavaScript implementation of descriptive, regression, and inference statistics
—
Functions for calculating combinations and permutations of datasets.
import {
combinations,
combinationsReplacement,
permutationsHeap
} from "simple-statistics";/**
* Generates all combinations of k elements from an array
* @param x - Array of elements to choose from
* @param k - Number of elements to choose
* @returns Array of all possible combinations
*/
function combinations<T>(x: T[], k: number): T[][];Usage Example:
import { combinations } from "simple-statistics";
const letters = ['A', 'B', 'C', 'D'];
const pairs = combinations(letters, 2);
// [['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'C'], ['B', 'D'], ['C', 'D']]
const numbers = [1, 2, 3];
const singles = combinations(numbers, 1);
// [[1], [2], [3]]/**
* Generates all combinations with replacement of k elements from an array
* @param x - Array of elements to choose from
* @param k - Number of elements to choose
* @returns Array of all possible combinations with replacement
*/
function combinationsReplacement<T>(x: T[], k: number): T[][];Usage Example:
import { combinationsReplacement } from "simple-statistics";
const dice = [1, 2, 3];
const rollTwice = combinationsReplacement(dice, 2);
// [[1, 1], [1, 2], [1, 3], [2, 2], [2, 3], [3, 3]]/**
* Generates all permutations of an array using Heap's algorithm
* @param x - Array of elements to permute
* @returns Array of all possible permutations
*/
function permutationsHeap<T>(x: T[]): T[][];Usage Example:
import { permutationsHeap } from "simple-statistics";
const colors = ['red', 'green', 'blue'];
const arrangements = permutationsHeap(colors);
// [
// ['red', 'green', 'blue'],
// ['green', 'red', 'blue'],
// ['blue', 'red', 'green'],
// ['red', 'blue', 'green'],
// ['green', 'blue', 'red'],
// ['blue', 'green', 'red']
// ]
// Small example
const abc = ['A', 'B'];
const perms = permutationsHeap(abc);
// [['A', 'B'], ['B', 'A']]Combinations calculate the number of ways to choose k items from n items where order doesn't matter: C(n,k) = n! / (k!(n-k)!)
Combinations with Replacement allow the same item to be chosen multiple times: C(n+k-1,k)
Permutations calculate arrangements where order matters: P(n,k) = n! / (n-k)!
The permutationsHeap function implements Heap's algorithm, which generates all permutations with minimal changes between consecutive permutations, making it efficient for large datasets.
Install with Tessl CLI
npx tessl i tessl/npm-simple-statistics