repo
stringlengths
5
106
file_url
stringlengths
78
301
file_path
stringlengths
4
211
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:56:49
2026-01-05 02:23:25
truncated
bool
2 classes
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/string/rabin-karp/rabinKarp.js
src/algorithms/string/rabin-karp/rabinKarp.js
import PolynomialHash from '../../cryptography/polynomial-hash/PolynomialHash'; /** * @param {string} text - Text that may contain the searchable word. * @param {string} word - Word that is being searched in text. * @return {number} - Position of the word in text. */ export default function rabinKarp(text, word) {...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/string/rabin-karp/__test__/rabinKarp.test.js
src/algorithms/string/rabin-karp/__test__/rabinKarp.test.js
import rabinKarp from '../rabinKarp'; describe('rabinKarp', () => { it('should find substring in a string', () => { expect(rabinKarp('', '')).toBe(0); expect(rabinKarp('a', '')).toBe(0); expect(rabinKarp('a', 'a')).toBe(0); expect(rabinKarp('ab', 'b')).toBe(1); expect(rabinKarp('abcbcglx', 'abca'...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/string/regular-expression-matching/regularExpressionMatching.js
src/algorithms/string/regular-expression-matching/regularExpressionMatching.js
const ZERO_OR_MORE_CHARS = '*'; const ANY_CHAR = '.'; /** * Dynamic programming approach. * * @param {string} string * @param {string} pattern * @return {boolean} */ export default function regularExpressionMatching(string, pattern) { /* * Let's initiate dynamic programming matrix for this string and patte...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/string/regular-expression-matching/__test__/regularExpressionMatching.test.js
src/algorithms/string/regular-expression-matching/__test__/regularExpressionMatching.test.js
import regularExpressionMatching from '../regularExpressionMatching'; describe('regularExpressionMatching', () => { it('should match regular expressions in a string', () => { expect(regularExpressionMatching('', '')).toBe(true); expect(regularExpressionMatching('a', 'a')).toBe(true); expect(regularExpres...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/string/z-algorithm/zAlgorithm.js
src/algorithms/string/z-algorithm/zAlgorithm.js
// The string separator that is being used for "word" and "text" concatenation. const SEPARATOR = '$'; /** * @param {string} zString * @return {number[]} */ function buildZArray(zString) { // Initiate zArray and fill it with zeros. const zArray = new Array(zString.length).fill(null).map(() => 0); // Z box bo...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/string/z-algorithm/__test__/zAlgorithm.test.js
src/algorithms/string/z-algorithm/__test__/zAlgorithm.test.js
import zAlgorithm from '../zAlgorithm'; describe('zAlgorithm', () => { it('should find word positions in given text', () => { expect(zAlgorithm('abcbcglx', 'abca')).toEqual([]); expect(zAlgorithm('abca', 'abca')).toEqual([0]); expect(zAlgorithm('abca', 'abcadfd')).toEqual([]); expect(zAlgorithm('abcb...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/ml/knn/kNN.js
src/algorithms/ml/knn/kNN.js
/** * Classifies the point in space based on k-nearest neighbors algorithm. * * @param {number[][]} dataSet - array of data points, i.e. [[0, 1], [3, 4], [5, 7]] * @param {number[]} labels - array of classes (labels), i.e. [1, 1, 2] * @param {number[]} toClassify - the point in space that needs to be classified, i...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/ml/knn/__test__/knn.test.js
src/algorithms/ml/knn/__test__/knn.test.js
import kNN from '../kNN'; describe('kNN', () => { it('should throw an error on invalid data', () => { expect(() => { kNN(); }).toThrowError('Either dataSet or labels or toClassify were not set'); }); it('should throw an error on invalid labels', () => { const noLabels = () => { kNN([[1, ...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/ml/k-means/kMeans.js
src/algorithms/ml/k-means/kMeans.js
import * as mtrx from '../../math/matrix/Matrix'; import euclideanDistance from '../../math/euclidean-distance/euclideanDistance'; /** * Classifies the point in space based on k-Means algorithm. * * @param {number[][]} data - array of dataSet points, i.e. [[0, 1], [3, 4], [5, 7]] * @param {number} k - number of cl...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/ml/k-means/__test__/kMeans.test.js
src/algorithms/ml/k-means/__test__/kMeans.test.js
import KMeans from '../kMeans'; describe('kMeans', () => { it('should throw an error on invalid data', () => { expect(() => { KMeans(); }).toThrowError('The data is empty'); }); it('should throw an error on inconsistent data', () => { expect(() => { KMeans([[1, 2], [1]], 2); }).toThr...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/image-processing/utils/imageData.js
src/algorithms/image-processing/utils/imageData.js
/** * @typedef {ArrayLike<number> | Uint8ClampedArray} PixelColor */ /** * @typedef {Object} PixelCoordinate * @property {number} x - horizontal coordinate. * @property {number} y - vertical coordinate. */ /** * Helper function that returns the color of the pixel. * @param {ImageData} img * @param {PixelCoor...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/image-processing/seam-carving/resizeImageWidth.js
src/algorithms/image-processing/seam-carving/resizeImageWidth.js
import { getPixel, setPixel } from '../utils/imageData'; /** * The seam is a sequence of pixels (coordinates). * @typedef {PixelCoordinate[]} Seam */ /** * Energy map is a 2D array that has the same width and height * as the image the map is being calculated for. * @typedef {number[][]} EnergyMap */ /** * Th...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/image-processing/seam-carving/__tests__/resizeImageWidth.node.js
src/algorithms/image-processing/seam-carving/__tests__/resizeImageWidth.node.js
import fs from 'fs'; import { PNG } from 'pngjs'; import resizeImageWidth from '../resizeImageWidth'; const testImageBeforePath = './src/algorithms/image-processing/seam-carving/__tests__/test-image-before.png'; const testImageAfterPath = './src/algorithms/image-processing/seam-carving/__tests__/test-image-after.png'...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/graph/kruskal/kruskal.js
src/algorithms/graph/kruskal/kruskal.js
import Graph from '../../../data-structures/graph/Graph'; import QuickSort from '../../sorting/quick-sort/QuickSort'; import DisjointSet from '../../../data-structures/disjoint-set/DisjointSet'; /** * @param {Graph} graph * @return {Graph} */ export default function kruskal(graph) { // It should fire error if gra...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/graph/kruskal/__test__/kruskal.test.js
src/algorithms/graph/kruskal/__test__/kruskal.test.js
import GraphVertex from '../../../../data-structures/graph/GraphVertex'; import GraphEdge from '../../../../data-structures/graph/GraphEdge'; import Graph from '../../../../data-structures/graph/Graph'; import kruskal from '../kruskal'; describe('kruskal', () => { it('should fire an error for directed graph', () => ...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/graph/topological-sorting/topologicalSort.js
src/algorithms/graph/topological-sorting/topologicalSort.js
import Stack from '../../../data-structures/stack/Stack'; import depthFirstSearch from '../depth-first-search/depthFirstSearch'; /** * @param {Graph} graph */ export default function topologicalSort(graph) { // Create a set of all vertices we want to visit. const unvisitedSet = {}; graph.getAllVertices().forEa...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/graph/topological-sorting/__test__/topologicalSort.test.js
src/algorithms/graph/topological-sorting/__test__/topologicalSort.test.js
import GraphVertex from '../../../../data-structures/graph/GraphVertex'; import GraphEdge from '../../../../data-structures/graph/GraphEdge'; import Graph from '../../../../data-structures/graph/Graph'; import topologicalSort from '../topologicalSort'; describe('topologicalSort', () => { it('should do topological so...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/graph/breadth-first-search/breadthFirstSearch.js
src/algorithms/graph/breadth-first-search/breadthFirstSearch.js
import Queue from '../../../data-structures/queue/Queue'; /** * @typedef {Object} Callbacks * * @property {function(vertices: Object): boolean} [allowTraversal] - * Determines whether DFS should traverse from the vertex to its neighbor * (along the edge). By default prohibits visiting the same vertex again. ...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/graph/breadth-first-search/__test__/breadthFirstSearch.test.js
src/algorithms/graph/breadth-first-search/__test__/breadthFirstSearch.test.js
import Graph from '../../../../data-structures/graph/Graph'; import GraphVertex from '../../../../data-structures/graph/GraphVertex'; import GraphEdge from '../../../../data-structures/graph/GraphEdge'; import breadthFirstSearch from '../breadthFirstSearch'; describe('breadthFirstSearch', () => { it('should perform ...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/graph/floyd-warshall/floydWarshall.js
src/algorithms/graph/floyd-warshall/floydWarshall.js
/** * @param {Graph} graph * @return {{distances: number[][], nextVertices: GraphVertex[][]}} */ export default function floydWarshall(graph) { // Get all graph vertices. const vertices = graph.getAllVertices(); // Init previous vertices matrix with nulls meaning that there are no // previous vertices exist...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/graph/floyd-warshall/__test__/floydWarshall.test.js
src/algorithms/graph/floyd-warshall/__test__/floydWarshall.test.js
import GraphVertex from '../../../../data-structures/graph/GraphVertex'; import GraphEdge from '../../../../data-structures/graph/GraphEdge'; import Graph from '../../../../data-structures/graph/Graph'; import floydWarshall from '../floydWarshall'; describe('floydWarshall', () => { it('should find minimum paths to a...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/graph/travelling-salesman/bfTravellingSalesman.js
src/algorithms/graph/travelling-salesman/bfTravellingSalesman.js
/** * Get all possible paths * @param {GraphVertex} startVertex * @param {GraphVertex[][]} [paths] * @param {GraphVertex[]} [path] */ function findAllPaths(startVertex, paths = [], path = []) { // Clone path. const currentPath = [...path]; // Add startVertex to the path. currentPath.push(startVertex); ...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/graph/travelling-salesman/__test__/bfTravellingSalesman.test.js
src/algorithms/graph/travelling-salesman/__test__/bfTravellingSalesman.test.js
import GraphVertex from '../../../../data-structures/graph/GraphVertex'; import GraphEdge from '../../../../data-structures/graph/GraphEdge'; import Graph from '../../../../data-structures/graph/Graph'; import bfTravellingSalesman from '../bfTravellingSalesman'; describe('bfTravellingSalesman', () => { it('should so...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/graph/dijkstra/dijkstra.js
src/algorithms/graph/dijkstra/dijkstra.js
import PriorityQueue from '../../../data-structures/priority-queue/PriorityQueue'; /** * @typedef {Object} ShortestPaths * @property {Object} distances - shortest distances to all vertices * @property {Object} previousVertices - shortest paths to all vertices. */ /** * Implementation of Dijkstra algorithm of fin...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/graph/dijkstra/__test__/dijkstra.test.js
src/algorithms/graph/dijkstra/__test__/dijkstra.test.js
import GraphVertex from '../../../../data-structures/graph/GraphVertex'; import GraphEdge from '../../../../data-structures/graph/GraphEdge'; import Graph from '../../../../data-structures/graph/Graph'; import dijkstra from '../dijkstra'; describe('dijkstra', () => { it('should find minimum paths to all vertices for...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/graph/eulerian-path/eulerianPath.js
src/algorithms/graph/eulerian-path/eulerianPath.js
import graphBridges from '../bridges/graphBridges'; /** * Fleury's algorithm of finding Eulerian Path (visit all graph edges exactly once). * * @param {Graph} graph * @return {GraphVertex[]} */ export default function eulerianPath(graph) { const eulerianPathVertices = []; // Set that contains all vertices wi...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/graph/eulerian-path/__test__/eulerianPath.test.js
src/algorithms/graph/eulerian-path/__test__/eulerianPath.test.js
import GraphVertex from '../../../../data-structures/graph/GraphVertex'; import GraphEdge from '../../../../data-structures/graph/GraphEdge'; import Graph from '../../../../data-structures/graph/Graph'; import eulerianPath from '../eulerianPath'; describe('eulerianPath', () => { it('should throw an error when graph ...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/graph/prim/prim.js
src/algorithms/graph/prim/prim.js
import Graph from '../../../data-structures/graph/Graph'; import PriorityQueue from '../../../data-structures/priority-queue/PriorityQueue'; /** * @param {Graph} graph * @return {Graph} */ export default function prim(graph) { // It should fire error if graph is directed since the algorithm works only // for un...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/graph/prim/__test__/prim.test.js
src/algorithms/graph/prim/__test__/prim.test.js
import GraphVertex from '../../../../data-structures/graph/GraphVertex'; import GraphEdge from '../../../../data-structures/graph/GraphEdge'; import Graph from '../../../../data-structures/graph/Graph'; import prim from '../prim'; describe('prim', () => { it('should fire an error for directed graph', () => { fun...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/graph/hamiltonian-cycle/hamiltonianCycle.js
src/algorithms/graph/hamiltonian-cycle/hamiltonianCycle.js
import GraphVertex from '../../../data-structures/graph/GraphVertex'; /** * @param {number[][]} adjacencyMatrix * @param {object} verticesIndices * @param {GraphVertex[]} cycle * @param {GraphVertex} vertexCandidate * @return {boolean} */ function isSafe(adjacencyMatrix, verticesIndices, cycle, vertexCandidate) ...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/graph/hamiltonian-cycle/__test__/hamiltonianCycle.test.js
src/algorithms/graph/hamiltonian-cycle/__test__/hamiltonianCycle.test.js
import GraphVertex from '../../../../data-structures/graph/GraphVertex'; import GraphEdge from '../../../../data-structures/graph/GraphEdge'; import Graph from '../../../../data-structures/graph/Graph'; import hamiltonianCycle from '../hamiltonianCycle'; describe('hamiltonianCycle', () => { it('should find hamiltoni...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/graph/bridges/graphBridges.js
src/algorithms/graph/bridges/graphBridges.js
import depthFirstSearch from '../depth-first-search/depthFirstSearch'; /** * Helper class for visited vertex metadata. */ class VisitMetadata { constructor({ discoveryTime, lowDiscoveryTime }) { this.discoveryTime = discoveryTime; this.lowDiscoveryTime = lowDiscoveryTime; } } /** * @param {Graph} graph...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/graph/bridges/__test__/graphBridges.test.js
src/algorithms/graph/bridges/__test__/graphBridges.test.js
import GraphVertex from '../../../../data-structures/graph/GraphVertex'; import GraphEdge from '../../../../data-structures/graph/GraphEdge'; import Graph from '../../../../data-structures/graph/Graph'; import graphBridges from '../graphBridges'; describe('graphBridges', () => { it('should find bridges in simple gra...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/graph/articulation-points/articulationPoints.js
src/algorithms/graph/articulation-points/articulationPoints.js
import depthFirstSearch from '../depth-first-search/depthFirstSearch'; /** * Helper class for visited vertex metadata. */ class VisitMetadata { constructor({ discoveryTime, lowDiscoveryTime }) { this.discoveryTime = discoveryTime; this.lowDiscoveryTime = lowDiscoveryTime; // We need this in order to ch...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/graph/articulation-points/__test__/articulationPoints.test.js
src/algorithms/graph/articulation-points/__test__/articulationPoints.test.js
import GraphVertex from '../../../../data-structures/graph/GraphVertex'; import GraphEdge from '../../../../data-structures/graph/GraphEdge'; import Graph from '../../../../data-structures/graph/Graph'; import articulationPoints from '../articulationPoints'; describe('articulationPoints', () => { it('should find art...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/graph/depth-first-search/depthFirstSearch.js
src/algorithms/graph/depth-first-search/depthFirstSearch.js
/** * @typedef {Object} Callbacks * * @property {function(vertices: Object): boolean} [allowTraversal] - * Determines whether DFS should traverse from the vertex to its neighbor * (along the edge). By default prohibits visiting the same vertex again. * * @property {function(vertices: Object)} [enterVertex] - C...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/graph/depth-first-search/__test__/depthFirstSearch.test.js
src/algorithms/graph/depth-first-search/__test__/depthFirstSearch.test.js
import Graph from '../../../../data-structures/graph/Graph'; import GraphVertex from '../../../../data-structures/graph/GraphVertex'; import GraphEdge from '../../../../data-structures/graph/GraphEdge'; import depthFirstSearch from '../depthFirstSearch'; describe('depthFirstSearch', () => { it('should perform DFS op...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/graph/detect-cycle/detectDirectedCycle.js
src/algorithms/graph/detect-cycle/detectDirectedCycle.js
import depthFirstSearch from '../depth-first-search/depthFirstSearch'; /** * Detect cycle in directed graph using Depth First Search. * * @param {Graph} graph */ export default function detectDirectedCycle(graph) { let cycle = null; // Will store parents (previous vertices) for all visited nodes. // This wi...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/graph/detect-cycle/detectUndirectedCycle.js
src/algorithms/graph/detect-cycle/detectUndirectedCycle.js
import depthFirstSearch from '../depth-first-search/depthFirstSearch'; /** * Detect cycle in undirected graph using Depth First Search. * * @param {Graph} graph */ export default function detectUndirectedCycle(graph) { let cycle = null; // List of vertices that we have visited. const visitedVertices = {}; ...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/graph/detect-cycle/detectUndirectedCycleUsingDisjointSet.js
src/algorithms/graph/detect-cycle/detectUndirectedCycleUsingDisjointSet.js
import DisjointSet from '../../../data-structures/disjoint-set/DisjointSet'; /** * Detect cycle in undirected graph using disjoint sets. * * @param {Graph} graph */ export default function detectUndirectedCycleUsingDisjointSet(graph) { // Create initial singleton disjoint sets for each graph vertex. /** @param...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/graph/detect-cycle/__test__/detectDirectedCycle.test.js
src/algorithms/graph/detect-cycle/__test__/detectDirectedCycle.test.js
import GraphVertex from '../../../../data-structures/graph/GraphVertex'; import GraphEdge from '../../../../data-structures/graph/GraphEdge'; import Graph from '../../../../data-structures/graph/Graph'; import detectDirectedCycle from '../detectDirectedCycle'; describe('detectDirectedCycle', () => { it('should detec...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/graph/detect-cycle/__test__/detectUndirectedCycle.test.js
src/algorithms/graph/detect-cycle/__test__/detectUndirectedCycle.test.js
import GraphVertex from '../../../../data-structures/graph/GraphVertex'; import GraphEdge from '../../../../data-structures/graph/GraphEdge'; import Graph from '../../../../data-structures/graph/Graph'; import detectUndirectedCycle from '../detectUndirectedCycle'; describe('detectUndirectedCycle', () => { it('should...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/graph/detect-cycle/__test__/detectUndirectedCycleUsingDisjointSet.test.js
src/algorithms/graph/detect-cycle/__test__/detectUndirectedCycleUsingDisjointSet.test.js
import GraphVertex from '../../../../data-structures/graph/GraphVertex'; import GraphEdge from '../../../../data-structures/graph/GraphEdge'; import Graph from '../../../../data-structures/graph/Graph'; import detectUndirectedCycleUsingDisjointSet from '../detectUndirectedCycleUsingDisjointSet'; describe('detectUndire...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/graph/bellman-ford/bellmanFord.js
src/algorithms/graph/bellman-ford/bellmanFord.js
/** * @param {Graph} graph * @param {GraphVertex} startVertex * @return {{distances, previousVertices}} */ export default function bellmanFord(graph, startVertex) { const distances = {}; const previousVertices = {}; // Init all distances with infinity assuming that currently we can't reach // any of the ve...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/graph/bellman-ford/__test__/bellmanFord.test.js
src/algorithms/graph/bellman-ford/__test__/bellmanFord.test.js
import GraphVertex from '../../../../data-structures/graph/GraphVertex'; import GraphEdge from '../../../../data-structures/graph/GraphEdge'; import Graph from '../../../../data-structures/graph/Graph'; import bellmanFord from '../bellmanFord'; describe('bellmanFord', () => { it('should find minimum paths to all ver...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/graph/strongly-connected-components/stronglyConnectedComponents.js
src/algorithms/graph/strongly-connected-components/stronglyConnectedComponents.js
import Stack from '../../../data-structures/stack/Stack'; import depthFirstSearch from '../depth-first-search/depthFirstSearch'; /** * @param {Graph} graph * @return {Stack} */ function getVerticesSortedByDfsFinishTime(graph) { // Set of all visited vertices during DFS pass. const visitedVerticesSet = {}; //...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/graph/strongly-connected-components/__test__/stronglyConnectedComponents.test.js
src/algorithms/graph/strongly-connected-components/__test__/stronglyConnectedComponents.test.js
import GraphVertex from '../../../../data-structures/graph/GraphVertex'; import GraphEdge from '../../../../data-structures/graph/GraphEdge'; import Graph from '../../../../data-structures/graph/Graph'; import stronglyConnectedComponents from '../stronglyConnectedComponents'; describe('stronglyConnectedComponents', ()...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/square-root/squareRoot.js
src/algorithms/math/square-root/squareRoot.js
/** * Calculates the square root of the number with given tolerance (precision) * by using Newton's method. * * @param number - the number we want to find a square root for. * @param [tolerance] - how many precise numbers after the floating point we want to get. * @return {number} */ export default function squa...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/square-root/__test__/squareRoot.test.js
src/algorithms/math/square-root/__test__/squareRoot.test.js
import squareRoot from '../squareRoot'; describe('squareRoot', () => { it('should throw for negative numbers', () => { function failingSquareRoot() { squareRoot(-5); } expect(failingSquareRoot).toThrow(); }); it('should correctly calculate square root with default tolerance', () => { expec...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/fast-powering/fastPowering.js
src/algorithms/math/fast-powering/fastPowering.js
/** * Fast Powering Algorithm. * Recursive implementation to compute power. * * Complexity: log(n) * * @param {number} base - Number that will be raised to the power. * @param {number} power - The power that number will be raised to. * @return {number} */ export default function fastPowering(base, power) { i...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/fast-powering/__test__/fastPowering.test.js
src/algorithms/math/fast-powering/__test__/fastPowering.test.js
import fastPowering from '../fastPowering'; describe('fastPowering', () => { it('should compute power in log(n) time', () => { expect(fastPowering(1, 1)).toBe(1); expect(fastPowering(2, 0)).toBe(1); expect(fastPowering(2, 2)).toBe(4); expect(fastPowering(2, 3)).toBe(8); expect(fastPowering(2, 4))...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/euclidean-algorithm/euclideanAlgorithmIterative.js
src/algorithms/math/euclidean-algorithm/euclideanAlgorithmIterative.js
/** * Iterative version of Euclidean Algorithm of finding greatest common divisor (GCD). * @param {number} originalA * @param {number} originalB * @return {number} */ export default function euclideanAlgorithmIterative(originalA, originalB) { // Make input numbers positive. let a = Math.abs(originalA); let b...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/euclidean-algorithm/euclideanAlgorithm.js
src/algorithms/math/euclidean-algorithm/euclideanAlgorithm.js
/** * Recursive version of Euclidean Algorithm of finding greatest common divisor (GCD). * @param {number} originalA * @param {number} originalB * @return {number} */ export default function euclideanAlgorithm(originalA, originalB) { // Make input numbers positive. const a = Math.abs(originalA); const b = Ma...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/euclidean-algorithm/__test__/euclideanAlgorithm.test.js
src/algorithms/math/euclidean-algorithm/__test__/euclideanAlgorithm.test.js
import euclideanAlgorithm from '../euclideanAlgorithm'; describe('euclideanAlgorithm', () => { it('should calculate GCD recursively', () => { expect(euclideanAlgorithm(0, 0)).toBe(0); expect(euclideanAlgorithm(2, 0)).toBe(2); expect(euclideanAlgorithm(0, 2)).toBe(2); expect(euclideanAlgorithm(1, 2))....
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/euclidean-algorithm/__test__/euclideanAlgorithmIterative.test.js
src/algorithms/math/euclidean-algorithm/__test__/euclideanAlgorithmIterative.test.js
import euclideanAlgorithmIterative from '../euclideanAlgorithmIterative'; describe('euclideanAlgorithmIterative', () => { it('should calculate GCD iteratively', () => { expect(euclideanAlgorithmIterative(0, 0)).toBe(0); expect(euclideanAlgorithmIterative(2, 0)).toBe(2); expect(euclideanAlgorithmIterative...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/fourier-transform/inverseDiscreteFourierTransform.js
src/algorithms/math/fourier-transform/inverseDiscreteFourierTransform.js
import ComplexNumber from '../complex-number/ComplexNumber'; const CLOSE_TO_ZERO_THRESHOLD = 1e-10; /** * Inverse Discrete Fourier Transform (IDFT): frequencies to time. * * Time complexity: O(N^2) * * @param {ComplexNumber[]} frequencies - Frequencies summands of the final signal. * @param {number} zeroThresho...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/fourier-transform/discreteFourierTransform.js
src/algorithms/math/fourier-transform/discreteFourierTransform.js
import ComplexNumber from '../complex-number/ComplexNumber'; const CLOSE_TO_ZERO_THRESHOLD = 1e-10; /** * Discrete Fourier Transform (DFT): time to frequencies. * * Time complexity: O(N^2) * * @param {number[]} inputAmplitudes - Input signal amplitudes over time (complex * numbers with real parts only). * @par...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/fourier-transform/fastFourierTransform.js
src/algorithms/math/fourier-transform/fastFourierTransform.js
import ComplexNumber from '../complex-number/ComplexNumber'; import bitLength from '../bits/bitLength'; /** * Returns the number which is the flipped binary representation of input. * * @param {number} input * @param {number} bitsCount * @return {number} */ function reverseBits(input, bitsCount) { let reversed...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/fourier-transform/__test__/fastFourierTransform.test.js
src/algorithms/math/fourier-transform/__test__/fastFourierTransform.test.js
import fastFourierTransform from '../fastFourierTransform'; import ComplexNumber from '../../complex-number/ComplexNumber'; /** * @param {ComplexNumber[]} sequence1 * @param {ComplexNumber[]} sequence2 * @param {Number} delta * @return {boolean} */ function sequencesApproximatelyEqual(sequence1, sequence2, delta)...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/fourier-transform/__test__/discreteFourierTransform.test.js
src/algorithms/math/fourier-transform/__test__/discreteFourierTransform.test.js
import discreteFourierTransform from '../discreteFourierTransform'; import FourierTester from './FourierTester'; describe('discreteFourierTransform', () => { it('should split signal into frequencies', () => { FourierTester.testDirectFourierTransform(discreteFourierTransform); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/fourier-transform/__test__/FourierTester.js
src/algorithms/math/fourier-transform/__test__/FourierTester.js
import ComplexNumber from '../../complex-number/ComplexNumber'; export const fourierTestCases = [ { input: [ { amplitude: 1 }, ], output: [ { frequency: 0, amplitude: 1, phase: 0, re: 1, im: 0, }, ], }, { input: [ { amplitude: 1 }, { amplitude: 0 }, ]...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/fourier-transform/__test__/inverseDiscreteFourierTransform.test.js
src/algorithms/math/fourier-transform/__test__/inverseDiscreteFourierTransform.test.js
import inverseDiscreteFourierTransform from '../inverseDiscreteFourierTransform'; import FourierTester from './FourierTester'; describe('inverseDiscreteFourierTransform', () => { it('should calculate output signal out of input frequencies', () => { FourierTester.testInverseFourierTransform(inverseDiscreteFourier...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/factorial/factorialRecursive.js
src/algorithms/math/factorial/factorialRecursive.js
/** * @param {number} number * @return {number} */ export default function factorialRecursive(number) { return number > 1 ? number * factorialRecursive(number - 1) : 1; }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/factorial/factorial.js
src/algorithms/math/factorial/factorial.js
/** * @param {number} number * @return {number} */ export default function factorial(number) { let result = 1; for (let i = 2; i <= number; i += 1) { result *= i; } return result; }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/factorial/__test__/factorial.test.js
src/algorithms/math/factorial/__test__/factorial.test.js
import factorial from '../factorial'; describe('factorial', () => { it('should calculate factorial', () => { expect(factorial(0)).toBe(1); expect(factorial(1)).toBe(1); expect(factorial(5)).toBe(120); expect(factorial(8)).toBe(40320); expect(factorial(10)).toBe(3628800); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/factorial/__test__/factorialRecursive.test.js
src/algorithms/math/factorial/__test__/factorialRecursive.test.js
import factorialRecursive from '../factorialRecursive'; describe('factorialRecursive', () => { it('should calculate factorial', () => { expect(factorialRecursive(0)).toBe(1); expect(factorialRecursive(1)).toBe(1); expect(factorialRecursive(5)).toBe(120); expect(factorialRecursive(8)).toBe(40320); ...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/prime-factors/primeFactors.js
src/algorithms/math/prime-factors/primeFactors.js
/** * Finds prime factors of a number. * * @param {number} n - the number that is going to be split into prime factors. * @returns {number[]} - array of prime factors. */ export function primeFactors(n) { // Clone n to avoid function arguments override. let nn = n; // Array that stores the all the prime fac...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/prime-factors/__test__/primeFactors.test.js
src/algorithms/math/prime-factors/__test__/primeFactors.test.js
import { primeFactors, hardyRamanujan, } from '../primeFactors'; /** * Calculates the error between exact and approximate prime factor counts. * @param {number} exactCount * @param {number} approximateCount * @returns {number} - approximation error (percentage). */ function approximationError(exactCount, appr...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/matrix/Matrix.js
src/algorithms/math/matrix/Matrix.js
/** * @typedef {number} Cell * @typedef {Cell[][]|Cell[][][]} Matrix * @typedef {number[]} Shape * @typedef {number[]} CellIndices */ /** * Gets the matrix's shape. * * @param {Matrix} m * @returns {Shape} */ export const shape = (m) => { const shapes = []; let dimension = m; while (dimension && Array....
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/matrix/__tests__/Matrix.test.js
src/algorithms/math/matrix/__tests__/Matrix.test.js
import * as mtrx from '../Matrix'; describe('Matrix', () => { it('should throw when trying to add matrices of invalid shapes', () => { expect( () => mtrx.dot([0], [1]), ).toThrowError('Invalid matrix format'); expect( () => mtrx.dot([[0]], [1]), ).toThrowError('Invalid matrix format'); ...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/pascal-triangle/pascalTriangle.js
src/algorithms/math/pascal-triangle/pascalTriangle.js
/** * @param {number} lineNumber - zero based. * @return {number[]} */ export default function pascalTriangle(lineNumber) { const currentLine = [1]; const currentLineSize = lineNumber + 1; for (let numIndex = 1; numIndex < currentLineSize; numIndex += 1) { // See explanation of this formula in README. ...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/pascal-triangle/pascalTriangleRecursive.js
src/algorithms/math/pascal-triangle/pascalTriangleRecursive.js
/** * @param {number} lineNumber - zero based. * @return {number[]} */ export default function pascalTriangleRecursive(lineNumber) { if (lineNumber === 0) { return [1]; } const currentLineSize = lineNumber + 1; const previousLineSize = currentLineSize - 1; // Create container for current line values....
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/pascal-triangle/__test__/pascalTriangleRecursive.test.js
src/algorithms/math/pascal-triangle/__test__/pascalTriangleRecursive.test.js
import pascalTriangleRecursive from '../pascalTriangleRecursive'; describe('pascalTriangleRecursive', () => { it('should calculate Pascal Triangle coefficients for specific line number', () => { expect(pascalTriangleRecursive(0)).toEqual([1]); expect(pascalTriangleRecursive(1)).toEqual([1, 1]); expect(pa...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/pascal-triangle/__test__/pascalTriangle.test.js
src/algorithms/math/pascal-triangle/__test__/pascalTriangle.test.js
import pascalTriangle from '../pascalTriangle'; describe('pascalTriangle', () => { it('should calculate Pascal Triangle coefficients for specific line number', () => { expect(pascalTriangle(0)).toEqual([1]); expect(pascalTriangle(1)).toEqual([1, 1]); expect(pascalTriangle(2)).toEqual([1, 2, 1]); expe...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/complex-number/ComplexNumber.js
src/algorithms/math/complex-number/ComplexNumber.js
import radianToDegree from '../radian/radianToDegree'; export default class ComplexNumber { /** * z = re + im * i * z = radius * e^(i * phase) * * @param {number} [re] * @param {number} [im] */ constructor({ re = 0, im = 0 } = {}) { this.re = re; this.im = im; } /** * @param {Comp...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/complex-number/__test__/ComplexNumber.test.js
src/algorithms/math/complex-number/__test__/ComplexNumber.test.js
import ComplexNumber from '../ComplexNumber'; describe('ComplexNumber', () => { it('should create complex numbers', () => { const complexNumber = new ComplexNumber({ re: 1, im: 2 }); expect(complexNumber).toBeDefined(); expect(complexNumber.re).toBe(1); expect(complexNumber.im).toBe(2); const d...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/binary-floating-point/testCases.js
src/algorithms/math/binary-floating-point/testCases.js
/** * @typedef {[number, string]} TestCase * @property {number} decimal * @property {string} binary */ /** * @type {TestCase[]} */ export const testCases16Bits = [ [-65504, '1111101111111111'], [-10344, '1111000100001101'], [-27.15625, '1100111011001010'], [-1, '1011110000000000'], [-0.09997558, '10101...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/binary-floating-point/bitsToFloat.js
src/algorithms/math/binary-floating-point/bitsToFloat.js
/** * Sequence of 0s and 1s. * @typedef {number[]} Bits */ /** * @typedef {{ * signBitsCount: number, * exponentBitsCount: number, * fractionBitsCount: number, * }} PrecisionConfig */ /** * @typedef {{ * half: PrecisionConfig, * single: PrecisionConfig, * double: PrecisionConfig * }} Precisi...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/binary-floating-point/floatAsBinaryString.js
src/algorithms/math/binary-floating-point/floatAsBinaryString.js
// @see: https://en.wikipedia.org/wiki/Single-precision_floating-point_format const singlePrecisionBytesLength = 4; // 32 bits // @see: https://en.wikipedia.org/wiki/Double-precision_floating-point_format const doublePrecisionBytesLength = 8; // 64 bits const bitsInByte = 8; /** * Converts the float number into its...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/binary-floating-point/__tests__/bitsToFloat.test.js
src/algorithms/math/binary-floating-point/__tests__/bitsToFloat.test.js
import { testCases16Bits, testCases32Bits, testCases64Bits } from '../testCases'; import { bitsToFloat16, bitsToFloat32, bitsToFloat64 } from '../bitsToFloat'; describe('bitsToFloat16', () => { it('should convert floating point binary bits to floating point decimal number', () => { for (let testCaseIndex = 0; te...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/binary-floating-point/__tests__/floatAsBinaryString.test.js
src/algorithms/math/binary-floating-point/__tests__/floatAsBinaryString.test.js
import { floatAs32BinaryString, floatAs64BinaryString } from '../floatAsBinaryString'; import { testCases32Bits, testCases64Bits } from '../testCases'; describe('floatAs32Binary', () => { it('should create a binary representation of the floating numbers', () => { for (let testCaseIndex = 0; testCaseIndex < testC...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/horner-method/classicPolynome.js
src/algorithms/math/horner-method/classicPolynome.js
/** * Returns the evaluation of a polynomial function at a certain point. * Uses straightforward approach with powers. * * @param {number[]} coefficients - i.e. [4, 3, 2] for (4 * x^2 + 3 * x + 2) * @param {number} xVal * @return {number} */ export default function classicPolynome(coefficients, xVal) { return ...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/horner-method/hornerMethod.js
src/algorithms/math/horner-method/hornerMethod.js
/** * Returns the evaluation of a polynomial function at a certain point. * Uses Horner's rule. * * @param {number[]} coefficients - i.e. [4, 3, 2] for (4 * x^2 + 3 * x + 2) * @param {number} xVal * @return {number} */ export default function hornerMethod(coefficients, xVal) { return coefficients.reduce( (...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/horner-method/__test__/hornerMethod.test.js
src/algorithms/math/horner-method/__test__/hornerMethod.test.js
import hornerMethod from '../hornerMethod'; import classicPolynome from '../classicPolynome'; describe('hornerMethod', () => { it('should evaluate the polynomial for the specified value of x correctly', () => { expect(hornerMethod([8], 0.1)).toBe(8); expect(hornerMethod([2, 4, 2, 5], 0.555)).toBe(7.68400775)...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/horner-method/__test__/classicPolynome.test.js
src/algorithms/math/horner-method/__test__/classicPolynome.test.js
import classicPolynome from '../classicPolynome'; describe('classicPolynome', () => { it('should evaluate the polynomial for the specified value of x correctly', () => { expect(classicPolynome([8], 0.1)).toBe(8); expect(classicPolynome([2, 4, 2, 5], 0.555)).toBe(7.68400775); expect(classicPolynome([2, 4,...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/primality-test/trialDivision.js
src/algorithms/math/primality-test/trialDivision.js
/** * @param {number} number * @return {boolean} */ export default function trialDivision(number) { // Check if number is integer. if (number % 1 !== 0) { return false; } if (number <= 1) { // If number is less than one then it isn't prime by definition. return false; } if (number <= 3) { ...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/primality-test/__test__/trialDivision.test.js
src/algorithms/math/primality-test/__test__/trialDivision.test.js
import trialDivision from '../trialDivision'; /** * @param {function(n: number)} testFunction */ function primalityTest(testFunction) { expect(testFunction(1)).toBe(false); expect(testFunction(2)).toBe(true); expect(testFunction(3)).toBe(true); expect(testFunction(5)).toBe(true); expect(testFunction(11)).t...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/euclidean-distance/euclideanDistance.js
src/algorithms/math/euclidean-distance/euclideanDistance.js
/** * @typedef {import('../matrix/Matrix.js').Matrix} Matrix */ import * as mtrx from '../matrix/Matrix'; /** * Calculates the euclidean distance between 2 matrices. * * @param {Matrix} a * @param {Matrix} b * @returns {number} * @trows {Error} */ const euclideanDistance = (a, b) => { mtrx.validateSameShap...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/euclidean-distance/__tests__/euclideanDistance.test.js
src/algorithms/math/euclidean-distance/__tests__/euclideanDistance.test.js
import euclideanDistance from '../euclideanDistance'; describe('euclideanDistance', () => { it('should calculate euclidean distance between vectors', () => { expect(euclideanDistance([[1]], [[2]])).toEqual(1); expect(euclideanDistance([[2]], [[1]])).toEqual(1); expect(euclideanDistance([[5, 8]], [[7, 3]]...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/radian/radianToDegree.js
src/algorithms/math/radian/radianToDegree.js
/** * @param {number} radian * @return {number} */ export default function radianToDegree(radian) { return radian * (180 / Math.PI); }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/radian/degreeToRadian.js
src/algorithms/math/radian/degreeToRadian.js
/** * @param {number} degree * @return {number} */ export default function degreeToRadian(degree) { return degree * (Math.PI / 180); }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/radian/__test__/degreeToRadian.test.js
src/algorithms/math/radian/__test__/degreeToRadian.test.js
import degreeToRadian from '../degreeToRadian'; describe('degreeToRadian', () => { it('should convert degree to radian', () => { expect(degreeToRadian(0)).toBe(0); expect(degreeToRadian(45)).toBe(Math.PI / 4); expect(degreeToRadian(90)).toBe(Math.PI / 2); expect(degreeToRadian(180)).toBe(Math.PI); ...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/radian/__test__/radianToDegree.test.js
src/algorithms/math/radian/__test__/radianToDegree.test.js
import radianToDegree from '../radianToDegree'; describe('radianToDegree', () => { it('should convert radian to degree', () => { expect(radianToDegree(0)).toBe(0); expect(radianToDegree(Math.PI / 4)).toBe(45); expect(radianToDegree(Math.PI / 2)).toBe(90); expect(radianToDegree(Math.PI)).toBe(180); ...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/is-power-of-two/isPowerOfTwo.js
src/algorithms/math/is-power-of-two/isPowerOfTwo.js
/** * @param {number} number * @return {boolean} */ export default function isPowerOfTwo(number) { // 1 (2^0) is the smallest power of two. if (number < 1) { return false; } // Let's find out if we can divide the number by two // many times without remainder. let dividedNumber = number; while (div...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/is-power-of-two/isPowerOfTwoBitwise.js
src/algorithms/math/is-power-of-two/isPowerOfTwoBitwise.js
/** * @param {number} number * @return {boolean} */ export default function isPowerOfTwoBitwise(number) { // 1 (2^0) is the smallest power of two. if (number < 1) { return false; } /* * Powers of two in binary look like this: * 1: 0001 * 2: 0010 * 4: 0100 * 8: 1000 * * Note that the...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/is-power-of-two/__test__/isPowerOfTwo.test.js
src/algorithms/math/is-power-of-two/__test__/isPowerOfTwo.test.js
import isPowerOfTwo from '../isPowerOfTwo'; describe('isPowerOfTwo', () => { it('should check if the number is made by multiplying twos', () => { expect(isPowerOfTwo(-1)).toBe(false); expect(isPowerOfTwo(0)).toBe(false); expect(isPowerOfTwo(1)).toBe(true); expect(isPowerOfTwo(2)).toBe(true); expe...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/is-power-of-two/__test__/isPowerOfTwoBitwise.test.js
src/algorithms/math/is-power-of-two/__test__/isPowerOfTwoBitwise.test.js
import isPowerOfTwoBitwise from '../isPowerOfTwoBitwise'; describe('isPowerOfTwoBitwise', () => { it('should check if the number is made by multiplying twos', () => { expect(isPowerOfTwoBitwise(-1)).toBe(false); expect(isPowerOfTwoBitwise(0)).toBe(false); expect(isPowerOfTwoBitwise(1)).toBe(true); ex...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/sieve-of-eratosthenes/sieveOfEratosthenes.js
src/algorithms/math/sieve-of-eratosthenes/sieveOfEratosthenes.js
/** * @param {number} maxNumber * @return {number[]} */ export default function sieveOfEratosthenes(maxNumber) { const isPrime = new Array(maxNumber + 1).fill(true); isPrime[0] = false; isPrime[1] = false; const primes = []; for (let number = 2; number <= maxNumber; number += 1) { if (isPrime[number]...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/sieve-of-eratosthenes/__test__/sieveOfEratosthenes.test.js
src/algorithms/math/sieve-of-eratosthenes/__test__/sieveOfEratosthenes.test.js
import sieveOfEratosthenes from '../sieveOfEratosthenes'; describe('sieveOfEratosthenes', () => { it('should find all primes less than or equal to n', () => { expect(sieveOfEratosthenes(5)).toEqual([2, 3, 5]); expect(sieveOfEratosthenes(10)).toEqual([2, 3, 5, 7]); expect(sieveOfEratosthenes(100)).toEqual...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/algorithms/math/liu-hui/liuHui.js
src/algorithms/math/liu-hui/liuHui.js
/* * Let circleRadius is the radius of circle. * circleRadius is also the side length of the inscribed hexagon */ const circleRadius = 1; /** * @param {number} sideLength * @param {number} splitCounter * @return {number} */ function getNGonSideLength(sideLength, splitCounter) { if (splitCounter <= 0) { re...
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false