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) {
const hasher = new PolynomialHash();
// Calculate word hash that we will use for comparison with other substring hashes.
const wordHash = hasher.hash(word);
let prevFrame = null;
let currentFrameHash = null;
// Go through all substring of the text that may match.
for (let charIndex = 0; charIndex <= (text.length - word.length); charIndex += 1) {
const currentFrame = text.substring(charIndex, charIndex + word.length);
// Calculate the hash of current substring.
if (currentFrameHash === null) {
currentFrameHash = hasher.hash(currentFrame);
} else {
currentFrameHash = hasher.roll(currentFrameHash, prevFrame, currentFrame);
}
prevFrame = currentFrame;
// Compare the hash of current substring and seeking string.
// In case if hashes match let's make sure that substrings are equal.
// In case of hash collision the strings may not be equal.
if (
wordHash === currentFrameHash
&& text.substr(charIndex, word.length) === word
) {
return charIndex;
}
}
return -1;
}
| 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')).toBe(-1);
expect(rabinKarp('abcbcglx', 'bcgl')).toBe(3);
expect(rabinKarp('abcxabcdabxabcdabcdabcy', 'abcdabcy')).toBe(15);
expect(rabinKarp('abcxabcdabxabcdabcdabcy', 'abcdabca')).toBe(-1);
expect(rabinKarp('abcxabcdabxaabcdabcabcdabcdabcy', 'abcdabca')).toBe(12);
expect(rabinKarp('abcxabcdabxaabaabaaaabcdabcdabcy', 'aabaabaaa')).toBe(11);
expect(rabinKarp('^ !/\'#\'pp', ' !/\'#\'pp')).toBe(1);
});
it('should work with bigger texts', () => {
const text = 'Lorem Ipsum is simply dummy text of the printing and '
+ 'typesetting industry. Lorem Ipsum has been the industry\'s standard '
+ 'dummy text ever since the 1500s, when an unknown printer took a '
+ 'galley of type and scrambled it to make a type specimen book. It '
+ 'has survived not only five centuries, but also the leap into '
+ 'electronic typesetting, remaining essentially unchanged. It was '
+ 'popularised in the 1960s with the release of Letraset sheets '
+ 'containing Lorem Ipsum passages, and more recently with desktop'
+ 'publishing software like Aldus PageMaker including versions of Lorem '
+ 'Ipsum.';
expect(rabinKarp(text, 'Lorem')).toBe(0);
expect(rabinKarp(text, 'versions')).toBe(549);
expect(rabinKarp(text, 'versions of Lorem Ipsum.')).toBe(549);
expect(rabinKarp(text, 'versions of Lorem Ipsum:')).toBe(-1);
expect(rabinKarp(text, 'Lorem Ipsum passages, and more recently with')).toBe(446);
});
it('should work with UTF symbols', () => {
expect(rabinKarp('a\u{ffff}', '\u{ffff}')).toBe(1);
expect(rabinKarp('\u0000耀\u0000', '耀\u0000')).toBe(1);
// @TODO: Provide Unicode support.
// expect(rabinKarp('a\u{20000}', '\u{20000}')).toBe(1);
});
});
| 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 pattern.
* We will have pattern characters on top (as columns) and string characters
* will be placed to the left of the table (as rows).
*
* Example:
*
* a * b . b
* - - - - - -
* a - - - - - -
* a - - - - - -
* b - - - - - -
* y - - - - - -
* b - - - - - -
*/
const matchMatrix = Array(string.length + 1).fill(null).map(() => {
return Array(pattern.length + 1).fill(null);
});
// Let's fill the top-left cell with true. This would mean that empty
// string '' matches to empty pattern ''.
matchMatrix[0][0] = true;
// Let's fill the first row of the matrix with false. That would mean that
// empty string can't match any non-empty pattern.
//
// Example:
// string: ''
// pattern: 'a.z'
//
// The one exception here is patterns like a*b* that matches the empty string.
for (let columnIndex = 1; columnIndex <= pattern.length; columnIndex += 1) {
const patternIndex = columnIndex - 1;
if (pattern[patternIndex] === ZERO_OR_MORE_CHARS) {
matchMatrix[0][columnIndex] = matchMatrix[0][columnIndex - 2];
} else {
matchMatrix[0][columnIndex] = false;
}
}
// Let's fill the first column with false. That would mean that empty pattern
// can't match any non-empty string.
//
// Example:
// string: 'ab'
// pattern: ''
for (let rowIndex = 1; rowIndex <= string.length; rowIndex += 1) {
matchMatrix[rowIndex][0] = false;
}
// Not let's go through every letter of the pattern and every letter of
// the string and compare them one by one.
for (let rowIndex = 1; rowIndex <= string.length; rowIndex += 1) {
for (let columnIndex = 1; columnIndex <= pattern.length; columnIndex += 1) {
// Take into account that fact that matrix contain one extra column and row.
const stringIndex = rowIndex - 1;
const patternIndex = columnIndex - 1;
if (pattern[patternIndex] === ZERO_OR_MORE_CHARS) {
/*
* In case if current pattern character is special '*' character we have
* two options:
*
* 1. Since * char allows it previous char to not be presented in a string we
* need to check if string matches the pattern without '*' char and without the
* char that goes before '*'. That would mean to go two positions left on the
* same row.
*
* 2. Since * char allows it previous char to be presented in a string many times we
* need to check if char before * is the same as current string char. If they are the
* same that would mean that current string matches the current pattern in case if
* the string WITHOUT current char matches the same pattern. This would mean to go
* one position up in the same row.
*/
if (matchMatrix[rowIndex][columnIndex - 2] === true) {
matchMatrix[rowIndex][columnIndex] = true;
} else if (
(
pattern[patternIndex - 1] === string[stringIndex]
|| pattern[patternIndex - 1] === ANY_CHAR
)
&& matchMatrix[rowIndex - 1][columnIndex] === true
) {
matchMatrix[rowIndex][columnIndex] = true;
} else {
matchMatrix[rowIndex][columnIndex] = false;
}
} else if (
pattern[patternIndex] === string[stringIndex]
|| pattern[patternIndex] === ANY_CHAR
) {
/*
* In case if current pattern char is the same as current string char
* or it may be any character (in case if pattern contains '.' char)
* we need to check if there was a match for the pattern and for the
* string by WITHOUT current char. This would mean that we may copy
* left-top diagonal value.
*
* Example:
*
* a b
* a 1 -
* b - 1
*/
matchMatrix[rowIndex][columnIndex] = matchMatrix[rowIndex - 1][columnIndex - 1];
} else {
/*
* In case if pattern char and string char are different we may
* treat this case as "no-match".
*
* Example:
*
* a b
* a - -
* c - 0
*/
matchMatrix[rowIndex][columnIndex] = false;
}
}
}
return matchMatrix[string.length][pattern.length];
}
| 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(regularExpressionMatching('aa', 'aa')).toBe(true);
expect(regularExpressionMatching('aab', 'aab')).toBe(true);
expect(regularExpressionMatching('aab', 'aa.')).toBe(true);
expect(regularExpressionMatching('aab', '.a.')).toBe(true);
expect(regularExpressionMatching('aab', '...')).toBe(true);
expect(regularExpressionMatching('a', 'a*')).toBe(true);
expect(regularExpressionMatching('aaa', 'a*')).toBe(true);
expect(regularExpressionMatching('aaab', 'a*b')).toBe(true);
expect(regularExpressionMatching('aaabb', 'a*b*')).toBe(true);
expect(regularExpressionMatching('aaabb', 'a*b*c*')).toBe(true);
expect(regularExpressionMatching('', 'a*')).toBe(true);
expect(regularExpressionMatching('xaabyc', 'xa*b.c')).toBe(true);
expect(regularExpressionMatching('aab', 'c*a*b*')).toBe(true);
expect(regularExpressionMatching('mississippi', 'mis*is*.p*.')).toBe(true);
expect(regularExpressionMatching('ab', '.*')).toBe(true);
expect(regularExpressionMatching('', 'a')).toBe(false);
expect(regularExpressionMatching('a', '')).toBe(false);
expect(regularExpressionMatching('aab', 'aa')).toBe(false);
expect(regularExpressionMatching('aab', 'baa')).toBe(false);
expect(regularExpressionMatching('aabc', '...')).toBe(false);
expect(regularExpressionMatching('aaabbdd', 'a*b*c*')).toBe(false);
expect(regularExpressionMatching('mississippi', 'mis*is*p*.')).toBe(false);
expect(regularExpressionMatching('ab', 'a*')).toBe(false);
expect(regularExpressionMatching('abba', 'a*b*.c')).toBe(false);
expect(regularExpressionMatching('abba', '.*c')).toBe(false);
});
});
| 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 boundaries.
let zBoxLeftIndex = 0;
let zBoxRightIndex = 0;
// Position of current zBox character that is also a position of
// the same character in prefix.
// For example:
// Z string: ab$xxabxx
// Indices: 012345678
// Prefix: ab.......
// Z box: .....ab..
// Z box shift for 'a' would be 0 (0-position in prefix and 0-position in Z box)
// Z box shift for 'b' would be 1 (1-position in prefix and 1-position in Z box)
let zBoxShift = 0;
// Go through all characters of the zString.
for (let charIndex = 1; charIndex < zString.length; charIndex += 1) {
if (charIndex > zBoxRightIndex) {
// We're OUTSIDE of Z box. In other words this is a case when we're
// starting from Z box of size 1.
// In this case let's make current character to be a Z box of length 1.
zBoxLeftIndex = charIndex;
zBoxRightIndex = charIndex;
// Now let's go and check current and the following characters to see if
// they are the same as a prefix. By doing this we will also expand our
// Z box. For example if starting from current position we will find 3
// more characters that are equal to the ones in the prefix we will expand
// right Z box boundary by 3.
while (
zBoxRightIndex < zString.length
&& zString[zBoxRightIndex - zBoxLeftIndex] === zString[zBoxRightIndex]
) {
// Expanding Z box right boundary.
zBoxRightIndex += 1;
}
// Now we may calculate how many characters starting from current position
// are are the same as the prefix. We may calculate it by difference between
// right and left Z box boundaries.
zArray[charIndex] = zBoxRightIndex - zBoxLeftIndex;
// Move right Z box boundary left by one position just because we've used
// [zBoxRightIndex - zBoxLeftIndex] index calculation above.
zBoxRightIndex -= 1;
} else {
// We're INSIDE of Z box.
// Calculate corresponding Z box shift. Because we want to copy the values
// from zArray that have been calculated before.
zBoxShift = charIndex - zBoxLeftIndex;
// Check if the value that has been already calculated before
// leaves us inside of Z box or it goes beyond the checkbox
// right boundary.
if (zArray[zBoxShift] < (zBoxRightIndex - charIndex) + 1) {
// If calculated value don't force us to go outside Z box
// then we're safe and we may simply use previously calculated value.
zArray[charIndex] = zArray[zBoxShift];
} else {
// In case if previously calculated values forces us to go outside of Z box
// we can't safely copy previously calculated zArray value. It is because
// we are sure that there is no further prefix matches outside of Z box.
// Thus such values must be re-calculated and reduced to certain point.
// To do so we need to shift left boundary of Z box to current position.
zBoxLeftIndex = charIndex;
// And start comparing characters one by one as we normally do for the case
// when we are outside of checkbox.
while (
zBoxRightIndex < zString.length
&& zString[zBoxRightIndex - zBoxLeftIndex] === zString[zBoxRightIndex]
) {
zBoxRightIndex += 1;
}
zArray[charIndex] = zBoxRightIndex - zBoxLeftIndex;
zBoxRightIndex -= 1;
}
}
}
// Return generated zArray.
return zArray;
}
/**
* @param {string} text
* @param {string} word
* @return {number[]}
*/
export default function zAlgorithm(text, word) {
// The list of word's positions in text. Word may be found in the same text
// in several different positions. Thus it is an array.
const wordPositions = [];
// Concatenate word and string. Word will be a prefix to a string.
const zString = `${word}${SEPARATOR}${text}`;
// Generate Z-array for concatenated string.
const zArray = buildZArray(zString);
// Based on Z-array properties each cell will tell us the length of the match between
// the string prefix and current sub-text. Thus we're may find all positions in zArray
// with the number that equals to the length of the word (zString prefix) and based on
// that positions we'll be able to calculate word positions in text.
for (let charIndex = 1; charIndex < zArray.length; charIndex += 1) {
if (zArray[charIndex] === word.length) {
// Since we did concatenation to form zString we need to subtract prefix
// and separator lengths.
const wordPosition = charIndex - word.length - SEPARATOR.length;
wordPositions.push(wordPosition);
}
}
// Return the list of word positions.
return wordPositions;
}
| 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('abcbcglabcx', 'abc')).toEqual([0, 7]);
expect(zAlgorithm('abcbcglx', 'bcgl')).toEqual([3]);
expect(zAlgorithm('abcbcglx', 'cglx')).toEqual([4]);
expect(zAlgorithm('abcxabcdabxabcdabcdabcy', 'abcdabcy')).toEqual([15]);
expect(zAlgorithm('abcxabcdabxabcdabcdabcy', 'abcdabca')).toEqual([]);
expect(zAlgorithm('abcxabcdabxaabcdabcabcdabcdabcy', 'abcdabca')).toEqual([12]);
expect(zAlgorithm('abcxabcdabxaabaabaaaabcdabcdabcy', 'aabaabaaa')).toEqual([11]);
});
});
| 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.e. [5, 4]
* @param {number} k - number of nearest neighbors which will be taken into account (preferably odd)
* @return {number} - the class of the point
*/
import euclideanDistance from '../../math/euclidean-distance/euclideanDistance';
export default function kNN(
dataSet,
labels,
toClassify,
k = 3,
) {
if (!dataSet || !labels || !toClassify) {
throw new Error('Either dataSet or labels or toClassify were not set');
}
// Calculate distance from toClassify to each point for all dimensions in dataSet.
// Store distance and point's label into distances list.
const distances = [];
for (let i = 0; i < dataSet.length; i += 1) {
distances.push({
dist: euclideanDistance([dataSet[i]], [toClassify]),
label: labels[i],
});
}
// Sort distances list (from closer point to further ones).
// Take initial k values, count with class index
const kNearest = distances.sort((a, b) => {
if (a.dist === b.dist) {
return 0;
}
return a.dist < b.dist ? -1 : 1;
}).slice(0, k);
// Count the number of instances of each class in top k members.
const labelsCounter = {};
let topClass = 0;
let topClassCount = 0;
for (let i = 0; i < kNearest.length; i += 1) {
if (kNearest[i].label in labelsCounter) {
labelsCounter[kNearest[i].label] += 1;
} else {
labelsCounter[kNearest[i].label] = 1;
}
if (labelsCounter[kNearest[i].label] > topClassCount) {
topClassCount = labelsCounter[kNearest[i].label];
topClass = kNearest[i].label;
}
}
// Return the class with highest count.
return topClass;
}
| 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, 1]]);
};
expect(noLabels).toThrowError('Either dataSet or labels or toClassify were not set');
});
it('should throw an error on not giving classification vector', () => {
const noClassification = () => {
kNN([[1, 1]], [1]);
};
expect(noClassification).toThrowError('Either dataSet or labels or toClassify were not set');
});
it('should throw an error on not giving classification vector', () => {
const inconsistent = () => {
kNN([[1, 1]], [1], [1]);
};
expect(inconsistent).toThrowError('Matrices have different shapes');
});
it('should find the nearest neighbour', () => {
let dataSet;
let labels;
let toClassify;
let expectedClass;
dataSet = [[1, 1], [2, 2]];
labels = [1, 2];
toClassify = [1, 1];
expectedClass = 1;
expect(kNN(dataSet, labels, toClassify)).toBe(expectedClass);
dataSet = [[1, 1], [6, 2], [3, 3], [4, 5], [9, 2], [2, 4], [8, 7]];
labels = [1, 2, 1, 2, 1, 2, 1];
toClassify = [1.25, 1.25];
expectedClass = 1;
expect(kNN(dataSet, labels, toClassify)).toBe(expectedClass);
dataSet = [[1, 1], [6, 2], [3, 3], [4, 5], [9, 2], [2, 4], [8, 7]];
labels = [1, 2, 1, 2, 1, 2, 1];
toClassify = [1.25, 1.25];
expectedClass = 2;
expect(kNN(dataSet, labels, toClassify, 5)).toBe(expectedClass);
});
it('should find the nearest neighbour with equal distances', () => {
const dataSet = [[0, 0], [1, 1], [0, 2]];
const labels = [1, 3, 3];
const toClassify = [0, 1];
const expectedClass = 3;
expect(kNN(dataSet, labels, toClassify)).toBe(expectedClass);
});
it('should find the nearest neighbour in 3D space', () => {
const dataSet = [[0, 0, 0], [0, 1, 1], [0, 0, 2]];
const labels = [1, 3, 3];
const toClassify = [0, 0, 1];
const expectedClass = 3;
expect(kNN(dataSet, labels, toClassify)).toBe(expectedClass);
});
});
| 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 clusters
* @return {number[]} - the class of the point
*/
export default function KMeans(
data,
k = 1,
) {
if (!data) {
throw new Error('The data is empty');
}
// Assign k clusters locations equal to the location of initial k points.
const dataDim = data[0].length;
const clusterCenters = data.slice(0, k);
// Continue optimization till convergence.
// Centroids should not be moving once optimized.
// Calculate distance of each candidate vector from each cluster center.
// Assign cluster number to each data vector according to minimum distance.
// Matrix of distance from each data point to each cluster centroid.
const distances = mtrx.zeros([data.length, k]);
// Vector data points' classes. The value of -1 means that no class has bee assigned yet.
const classes = Array(data.length).fill(-1);
let iterate = true;
while (iterate) {
iterate = false;
// Calculate and store the distance of each data point from each cluster.
for (let dataIndex = 0; dataIndex < data.length; dataIndex += 1) {
for (let clusterIndex = 0; clusterIndex < k; clusterIndex += 1) {
distances[dataIndex][clusterIndex] = euclideanDistance(
[clusterCenters[clusterIndex]],
[data[dataIndex]],
);
}
// Assign the closest cluster number to each dataSet point.
const closestClusterIdx = distances[dataIndex].indexOf(
Math.min(...distances[dataIndex]),
);
// Check if data point class has been changed and we still need to re-iterate.
if (classes[dataIndex] !== closestClusterIdx) {
iterate = true;
}
classes[dataIndex] = closestClusterIdx;
}
// Recalculate cluster centroid values via all dimensions of the points under it.
for (let clusterIndex = 0; clusterIndex < k; clusterIndex += 1) {
// Reset cluster center coordinates since we need to recalculate them.
clusterCenters[clusterIndex] = Array(dataDim).fill(0);
let clusterSize = 0;
for (let dataIndex = 0; dataIndex < data.length; dataIndex += 1) {
if (classes[dataIndex] === clusterIndex) {
// Register one more data point of current cluster.
clusterSize += 1;
for (let dimensionIndex = 0; dimensionIndex < dataDim; dimensionIndex += 1) {
// Add data point coordinates to the cluster center coordinates.
clusterCenters[clusterIndex][dimensionIndex] += data[dataIndex][dimensionIndex];
}
}
}
// Calculate the average for each cluster center coordinate.
for (let dimensionIndex = 0; dimensionIndex < dataDim; dimensionIndex += 1) {
clusterCenters[clusterIndex][dimensionIndex] = parseFloat(Number(
clusterCenters[clusterIndex][dimensionIndex] / clusterSize,
).toFixed(2));
}
}
}
// Return the clusters assigned.
return classes;
}
| 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);
}).toThrowError('Matrices have different shapes');
});
it('should find the nearest neighbour', () => {
const data = [[1, 1], [6, 2], [3, 3], [4, 5], [9, 2], [2, 4], [8, 7]];
const k = 2;
const expectedClusters = [0, 1, 0, 1, 1, 0, 1];
expect(KMeans(data, k)).toEqual(expectedClusters);
expect(KMeans([[0, 0], [0, 1], [10, 10]], 2)).toEqual(
[0, 0, 1],
);
});
it('should find the clusters with equal distances', () => {
const dataSet = [[0, 0], [1, 1], [2, 2]];
const k = 3;
const expectedCluster = [0, 1, 2];
expect(KMeans(dataSet, k)).toEqual(expectedCluster);
});
it('should find the nearest neighbour in 3D space', () => {
const dataSet = [[0, 0, 0], [0, 1, 0], [2, 0, 2]];
const k = 2;
const expectedCluster = [1, 1, 0];
expect(KMeans(dataSet, k)).toEqual(expectedCluster);
});
});
| 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 {PixelCoordinate} coordinate
* @returns {PixelColor}
*/
export const getPixel = (img, { x, y }) => {
// The ImageData data array is a flat 1D array.
// Thus we need to convert x and y coordinates to the linear index.
const i = y * img.width + x;
const cellsPerColor = 4; // RGBA
// For better efficiency, instead of creating a new sub-array we return
// a pointer to the part of the ImageData array.
return img.data.subarray(i * cellsPerColor, i * cellsPerColor + cellsPerColor);
};
/**
* Helper function that sets the color of the pixel.
* @param {ImageData} img
* @param {PixelCoordinate} coordinate
* @param {PixelColor} color
*/
export const setPixel = (img, { x, y }, color) => {
// The ImageData data array is a flat 1D array.
// Thus we need to convert x and y coordinates to the linear index.
const i = y * img.width + x;
const cellsPerColor = 4; // RGBA
img.data.set(color, i * cellsPerColor);
};
| 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
*/
/**
* The metadata for the pixels in the seam.
* @typedef {Object} SeamPixelMeta
* @property {number} energy - the energy of the pixel.
* @property {PixelCoordinate} coordinate - the coordinate of the pixel.
* @property {?PixelCoordinate} previous - the previous pixel in a seam.
*/
/**
* Type that describes the image size (width and height)
* @typedef {Object} ImageSize
* @property {number} w - image width.
* @property {number} h - image height.
*/
/**
* @typedef {Object} ResizeImageWidthArgs
* @property {ImageData} img - image data we want to resize.
* @property {number} toWidth - final image width we want the image to shrink to.
*/
/**
* @typedef {Object} ResizeImageWidthResult
* @property {ImageData} img - resized image data.
* @property {ImageSize} size - resized image size.
*/
/**
* Helper function that creates a matrix (2D array) of specific
* size (w x h) and fills it with specified value.
* @param {number} w
* @param {number} h
* @param {?(number | SeamPixelMeta)} filler
* @returns {?(number | SeamPixelMeta)[][]}
*/
const matrix = (w, h, filler) => {
return new Array(h)
.fill(null)
.map(() => {
return new Array(w).fill(filler);
});
};
/**
* Calculates the energy of a pixel.
* @param {?PixelColor} left
* @param {PixelColor} middle
* @param {?PixelColor} right
* @returns {number}
*/
const getPixelEnergy = (left, middle, right) => {
// Middle pixel is the pixel we're calculating the energy for.
const [mR, mG, mB] = middle;
// Energy from the left pixel (if it exists).
let lEnergy = 0;
if (left) {
const [lR, lG, lB] = left;
lEnergy = (lR - mR) ** 2 + (lG - mG) ** 2 + (lB - mB) ** 2;
}
// Energy from the right pixel (if it exists).
let rEnergy = 0;
if (right) {
const [rR, rG, rB] = right;
rEnergy = (rR - mR) ** 2 + (rG - mG) ** 2 + (rB - mB) ** 2;
}
// Resulting pixel energy.
return Math.sqrt(lEnergy + rEnergy);
};
/**
* Calculates the energy of each pixel of the image.
* @param {ImageData} img
* @param {ImageSize} size
* @returns {EnergyMap}
*/
const calculateEnergyMap = (img, { w, h }) => {
// Create an empty energy map where each pixel has infinitely high energy.
// We will update the energy of each pixel.
const energyMap = matrix(w, h, Infinity);
for (let y = 0; y < h; y += 1) {
for (let x = 0; x < w; x += 1) {
// Left pixel might not exist if we're on the very left edge of the image.
const left = (x - 1) >= 0 ? getPixel(img, { x: x - 1, y }) : null;
// The color of the middle pixel that we're calculating the energy for.
const middle = getPixel(img, { x, y });
// Right pixel might not exist if we're on the very right edge of the image.
const right = (x + 1) < w ? getPixel(img, { x: x + 1, y }) : null;
energyMap[y][x] = getPixelEnergy(left, middle, right);
}
}
return energyMap;
};
/**
* Finds the seam (the sequence of pixels from top to bottom) that has the
* lowest resulting energy using the Dynamic Programming approach.
* @param {EnergyMap} energyMap
* @param {ImageSize} size
* @returns {Seam}
*/
const findLowEnergySeam = (energyMap, { w, h }) => {
// The 2D array of the size of w and h, where each pixel contains the
// seam metadata (pixel energy, pixel coordinate and previous pixel from
// the lowest energy seam at this point).
const seamPixelsMap = matrix(w, h, null);
// Populate the first row of the map by just copying the energies
// from the energy map.
for (let x = 0; x < w; x += 1) {
const y = 0;
seamPixelsMap[y][x] = {
energy: energyMap[y][x],
coordinate: { x, y },
previous: null,
};
}
// Populate the rest of the rows.
for (let y = 1; y < h; y += 1) {
for (let x = 0; x < w; x += 1) {
// Find the top adjacent cell with minimum energy.
// This cell would be the tail of a seam with lowest energy at this point.
// It doesn't mean that this seam (path) has lowest energy globally.
// Instead, it means that we found a path with the lowest energy that may lead
// us to the current pixel with the coordinates x and y.
let minPrevEnergy = Infinity;
let minPrevX = x;
for (let i = (x - 1); i <= (x + 1); i += 1) {
if (i >= 0 && i < w && seamPixelsMap[y - 1][i].energy < minPrevEnergy) {
minPrevEnergy = seamPixelsMap[y - 1][i].energy;
minPrevX = i;
}
}
// Update the current cell.
seamPixelsMap[y][x] = {
energy: minPrevEnergy + energyMap[y][x],
coordinate: { x, y },
previous: { x: minPrevX, y: y - 1 },
};
}
}
// Find where the minimum energy seam ends.
// We need to find the tail of the lowest energy seam to start
// traversing it from its tail to its head (from the bottom to the top).
let lastMinCoordinate = null;
let minSeamEnergy = Infinity;
for (let x = 0; x < w; x += 1) {
const y = h - 1;
if (seamPixelsMap[y][x].energy < minSeamEnergy) {
minSeamEnergy = seamPixelsMap[y][x].energy;
lastMinCoordinate = { x, y };
}
}
// Find the lowest energy energy seam.
// Once we know where the tail is we may traverse and assemble the lowest
// energy seam based on the "previous" value of the seam pixel metadata.
const seam = [];
const { x: lastMinX, y: lastMinY } = lastMinCoordinate;
// Adding new pixel to the seam path one by one until we reach the top.
let currentSeam = seamPixelsMap[lastMinY][lastMinX];
while (currentSeam) {
seam.push(currentSeam.coordinate);
const prevMinCoordinates = currentSeam.previous;
if (!prevMinCoordinates) {
currentSeam = null;
} else {
const { x: prevMinX, y: prevMinY } = prevMinCoordinates;
currentSeam = seamPixelsMap[prevMinY][prevMinX];
}
}
return seam;
};
/**
* Deletes the seam from the image data.
* We delete the pixel in each row and then shift the rest of the row pixels to the left.
* @param {ImageData} img
* @param {Seam} seam
* @param {ImageSize} size
*/
const deleteSeam = (img, seam, { w }) => {
seam.forEach(({ x: seamX, y: seamY }) => {
for (let x = seamX; x < (w - 1); x += 1) {
const nextPixel = getPixel(img, { x: x + 1, y: seamY });
setPixel(img, { x, y: seamY }, nextPixel);
}
});
};
/**
* Performs the content-aware image width resizing using the seam carving method.
* @param {ResizeImageWidthArgs} args
* @returns {ResizeImageWidthResult}
*/
const resizeImageWidth = ({ img, toWidth }) => {
/**
* For performance reasons we want to avoid changing the img data array size.
* Instead we'll just keep the record of the resized image width and height separately.
* @type {ImageSize}
*/
const size = { w: img.width, h: img.height };
// Calculating the number of pixels to remove.
const pxToRemove = img.width - toWidth;
let energyMap = null;
let seam = null;
// Removing the lowest energy seams one by one.
for (let i = 0; i < pxToRemove; i += 1) {
// 1. Calculate the energy map for the current version of the image.
energyMap = calculateEnergyMap(img, size);
// 2. Find the seam with the lowest energy based on the energy map.
seam = findLowEnergySeam(energyMap, size);
// 3. Delete the seam with the lowest energy seam from the image.
deleteSeam(img, seam, size);
// Reduce the image width, and continue iterations.
size.w -= 1;
}
// Returning the resized image and its final size.
// The img is actually a reference to the ImageData, so technically
// the caller of the function already has this pointer. But let's
// still return it for better code readability.
return { img, size };
};
export default resizeImageWidth;
| 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';
/**
* Compares two images and finds the number of different pixels.
*
* @param {ImageData} imgA - ImageData for the first image.
* @param {ImageData} imgB - ImageData for the second image.
* @param {number} threshold - Color difference threshold [0..255]. Smaller - stricter.
* @returns {number} - Number of different pixels.
*/
function pixelsDiff(imgA, imgB, threshold = 0) {
if (imgA.width !== imgB.width || imgA.height !== imgB.height) {
throw new Error('Images must have the same size');
}
let differentPixels = 0;
const numColorParams = 4; // RGBA
for (let pixelIndex = 0; pixelIndex < imgA.data.length; pixelIndex += numColorParams) {
// Get pixel's color for each image.
const [aR, aG, aB] = imgA.data.subarray(pixelIndex, pixelIndex + numColorParams);
const [bR, bG, bB] = imgB.data.subarray(pixelIndex, pixelIndex + numColorParams);
// Get average pixel's color for each image (make them greyscale).
const aAvgColor = Math.floor((aR + aG + aB) / 3);
const bAvgColor = Math.floor((bR + bG + bB) / 3);
// Compare pixel colors.
if (Math.abs(aAvgColor - bAvgColor) > threshold) {
differentPixels += 1;
}
}
return differentPixels;
}
const pngLoad = (path) => new Promise((resolve) => {
fs.createReadStream(path)
.pipe(new PNG())
.on('parsed', function Parsed() {
/** @type {ImageData} */
const imageData = {
colorSpace: 'srgb',
width: this.width,
height: this.height,
data: this.data,
};
resolve(imageData);
});
});
describe('resizeImageWidth', () => {
it('should perform content-aware image width reduction', async () => {
const imgBefore = await pngLoad(testImageBeforePath);
const imgAfter = await pngLoad(testImageAfterPath);
const toWidth = Math.floor(imgBefore.width / 2);
const {
img: imgResized,
size: resizedSize,
} = resizeImageWidth({ img: imgBefore, toWidth });
expect(imgResized).toBeDefined();
expect(resizedSize).toBeDefined();
expect(resizedSize).toEqual({ w: toWidth, h: imgBefore.height });
expect(imgResized.width).toBe(imgAfter.width);
expect(imgResized.height).toBe(imgAfter.height);
const colorThreshold = 50;
const differentPixels = pixelsDiff(imgResized, imgAfter, colorThreshold);
// Allow 10% of pixels to be different
const pixelsThreshold = Math.floor((imgAfter.width * imgAfter.height) / 10);
expect(differentPixels).toBeLessThanOrEqual(pixelsThreshold);
});
});
| 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 graph is directed since the algorithm works only
// for undirected graphs.
if (graph.isDirected) {
throw new Error('Kruskal\'s algorithms works only for undirected graphs');
}
// Init new graph that will contain minimum spanning tree of original graph.
const minimumSpanningTree = new Graph();
// Sort all graph edges in increasing order.
const sortingCallbacks = {
/**
* @param {GraphEdge} graphEdgeA
* @param {GraphEdge} graphEdgeB
*/
compareCallback: (graphEdgeA, graphEdgeB) => {
if (graphEdgeA.weight === graphEdgeB.weight) {
return 1;
}
return graphEdgeA.weight <= graphEdgeB.weight ? -1 : 1;
},
};
const sortedEdges = new QuickSort(sortingCallbacks).sort(graph.getAllEdges());
// Create disjoint sets for all graph vertices.
const keyCallback = (graphVertex) => graphVertex.getKey();
const disjointSet = new DisjointSet(keyCallback);
graph.getAllVertices().forEach((graphVertex) => {
disjointSet.makeSet(graphVertex);
});
// Go through all edges started from the minimum one and try to add them
// to minimum spanning tree. The criteria of adding the edge would be whether
// it is forms the cycle or not (if it connects two vertices from one disjoint
// set or not).
for (let edgeIndex = 0; edgeIndex < sortedEdges.length; edgeIndex += 1) {
/** @var {GraphEdge} currentEdge */
const currentEdge = sortedEdges[edgeIndex];
// Check if edge forms the cycle. If it does then skip it.
if (!disjointSet.inSameSet(currentEdge.startVertex, currentEdge.endVertex)) {
// Unite two subsets into one.
disjointSet.union(currentEdge.startVertex, currentEdge.endVertex);
// Add this edge to spanning tree.
minimumSpanningTree.addEdge(currentEdge);
}
}
return minimumSpanningTree;
}
| 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', () => {
function applyPrimToDirectedGraph() {
const graph = new Graph(true);
kruskal(graph);
}
expect(applyPrimToDirectedGraph).toThrowError();
});
it('should find minimum spanning tree', () => {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const vertexE = new GraphVertex('E');
const vertexF = new GraphVertex('F');
const vertexG = new GraphVertex('G');
const edgeAB = new GraphEdge(vertexA, vertexB, 2);
const edgeAD = new GraphEdge(vertexA, vertexD, 3);
const edgeAC = new GraphEdge(vertexA, vertexC, 3);
const edgeBC = new GraphEdge(vertexB, vertexC, 4);
const edgeBE = new GraphEdge(vertexB, vertexE, 3);
const edgeDF = new GraphEdge(vertexD, vertexF, 7);
const edgeEC = new GraphEdge(vertexE, vertexC, 1);
const edgeEF = new GraphEdge(vertexE, vertexF, 8);
const edgeFG = new GraphEdge(vertexF, vertexG, 9);
const edgeFC = new GraphEdge(vertexF, vertexC, 6);
const graph = new Graph();
graph
.addEdge(edgeAB)
.addEdge(edgeAD)
.addEdge(edgeAC)
.addEdge(edgeBC)
.addEdge(edgeBE)
.addEdge(edgeDF)
.addEdge(edgeEC)
.addEdge(edgeEF)
.addEdge(edgeFC)
.addEdge(edgeFG);
expect(graph.getWeight()).toEqual(46);
const minimumSpanningTree = kruskal(graph);
expect(minimumSpanningTree.getWeight()).toBe(24);
expect(minimumSpanningTree.getAllVertices().length).toBe(graph.getAllVertices().length);
expect(minimumSpanningTree.getAllEdges().length).toBe(graph.getAllVertices().length - 1);
expect(minimumSpanningTree.toString()).toBe('E,C,A,B,D,F,G');
});
it('should find minimum spanning tree for simple graph', () => {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const edgeAB = new GraphEdge(vertexA, vertexB, 1);
const edgeAD = new GraphEdge(vertexA, vertexD, 3);
const edgeBC = new GraphEdge(vertexB, vertexC, 1);
const edgeBD = new GraphEdge(vertexB, vertexD, 3);
const edgeCD = new GraphEdge(vertexC, vertexD, 1);
const graph = new Graph();
graph
.addEdge(edgeAB)
.addEdge(edgeAD)
.addEdge(edgeBC)
.addEdge(edgeBD)
.addEdge(edgeCD);
expect(graph.getWeight()).toEqual(9);
const minimumSpanningTree = kruskal(graph);
expect(minimumSpanningTree.getWeight()).toBe(3);
expect(minimumSpanningTree.getAllVertices().length).toBe(graph.getAllVertices().length);
expect(minimumSpanningTree.getAllEdges().length).toBe(graph.getAllVertices().length - 1);
expect(minimumSpanningTree.toString()).toBe('A,B,C,D');
});
});
| 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().forEach((vertex) => {
unvisitedSet[vertex.getKey()] = vertex;
});
// Create a set for all vertices that we've already visited.
const visitedSet = {};
// Create a stack of already ordered vertices.
const sortedStack = new Stack();
const dfsCallbacks = {
enterVertex: ({ currentVertex }) => {
// Add vertex to visited set in case if all its children has been explored.
visitedSet[currentVertex.getKey()] = currentVertex;
// Remove this vertex from unvisited set.
delete unvisitedSet[currentVertex.getKey()];
},
leaveVertex: ({ currentVertex }) => {
// If the vertex has been totally explored then we may push it to stack.
sortedStack.push(currentVertex);
},
allowTraversal: ({ nextVertex }) => {
return !visitedSet[nextVertex.getKey()];
},
};
// Let's go and do DFS for all unvisited nodes.
while (Object.keys(unvisitedSet).length) {
const currentVertexKey = Object.keys(unvisitedSet)[0];
const currentVertex = unvisitedSet[currentVertexKey];
// Do DFS for current node.
depthFirstSearch(graph, currentVertex, dfsCallbacks);
}
return sortedStack.toArray();
}
| 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 sorting on graph', () => {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const vertexE = new GraphVertex('E');
const vertexF = new GraphVertex('F');
const vertexG = new GraphVertex('G');
const vertexH = new GraphVertex('H');
const edgeAC = new GraphEdge(vertexA, vertexC);
const edgeBC = new GraphEdge(vertexB, vertexC);
const edgeBD = new GraphEdge(vertexB, vertexD);
const edgeCE = new GraphEdge(vertexC, vertexE);
const edgeDF = new GraphEdge(vertexD, vertexF);
const edgeEF = new GraphEdge(vertexE, vertexF);
const edgeEH = new GraphEdge(vertexE, vertexH);
const edgeFG = new GraphEdge(vertexF, vertexG);
const graph = new Graph(true);
graph
.addEdge(edgeAC)
.addEdge(edgeBC)
.addEdge(edgeBD)
.addEdge(edgeCE)
.addEdge(edgeDF)
.addEdge(edgeEF)
.addEdge(edgeEH)
.addEdge(edgeFG);
const sortedVertices = topologicalSort(graph);
expect(sortedVertices).toBeDefined();
expect(sortedVertices.length).toBe(graph.getAllVertices().length);
expect(sortedVertices).toEqual([
vertexB,
vertexD,
vertexA,
vertexC,
vertexE,
vertexH,
vertexF,
vertexG,
]);
});
});
| 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.
*
* @property {function(vertices: Object)} [enterVertex] - Called when BFS enters the vertex.
*
* @property {function(vertices: Object)} [leaveVertex] - Called when BFS leaves the vertex.
*/
/**
* @param {Callbacks} [callbacks]
* @returns {Callbacks}
*/
function initCallbacks(callbacks = {}) {
const initiatedCallback = callbacks;
const stubCallback = () => {};
const allowTraversalCallback = (
() => {
const seen = {};
return ({ nextVertex }) => {
if (!seen[nextVertex.getKey()]) {
seen[nextVertex.getKey()] = true;
return true;
}
return false;
};
}
)();
initiatedCallback.allowTraversal = callbacks.allowTraversal || allowTraversalCallback;
initiatedCallback.enterVertex = callbacks.enterVertex || stubCallback;
initiatedCallback.leaveVertex = callbacks.leaveVertex || stubCallback;
return initiatedCallback;
}
/**
* @param {Graph} graph
* @param {GraphVertex} startVertex
* @param {Callbacks} [originalCallbacks]
*/
export default function breadthFirstSearch(graph, startVertex, originalCallbacks) {
const callbacks = initCallbacks(originalCallbacks);
const vertexQueue = new Queue();
// Do initial queue setup.
vertexQueue.enqueue(startVertex);
let previousVertex = null;
// Traverse all vertices from the queue.
while (!vertexQueue.isEmpty()) {
const currentVertex = vertexQueue.dequeue();
callbacks.enterVertex({ currentVertex, previousVertex });
// Add all neighbors to the queue for future traversals.
graph.getNeighbors(currentVertex).forEach((nextVertex) => {
if (callbacks.allowTraversal({ previousVertex, currentVertex, nextVertex })) {
vertexQueue.enqueue(nextVertex);
}
});
callbacks.leaveVertex({ currentVertex, previousVertex });
// Memorize current vertex before next loop.
previousVertex = currentVertex;
}
}
| 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 BFS operation on graph', () => {
const graph = new Graph(true);
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const vertexE = new GraphVertex('E');
const vertexF = new GraphVertex('F');
const vertexG = new GraphVertex('G');
const vertexH = new GraphVertex('H');
const edgeAB = new GraphEdge(vertexA, vertexB);
const edgeBC = new GraphEdge(vertexB, vertexC);
const edgeCG = new GraphEdge(vertexC, vertexG);
const edgeAD = new GraphEdge(vertexA, vertexD);
const edgeAE = new GraphEdge(vertexA, vertexE);
const edgeEF = new GraphEdge(vertexE, vertexF);
const edgeFD = new GraphEdge(vertexF, vertexD);
const edgeDH = new GraphEdge(vertexD, vertexH);
const edgeGH = new GraphEdge(vertexG, vertexH);
graph
.addEdge(edgeAB)
.addEdge(edgeBC)
.addEdge(edgeCG)
.addEdge(edgeAD)
.addEdge(edgeAE)
.addEdge(edgeEF)
.addEdge(edgeFD)
.addEdge(edgeDH)
.addEdge(edgeGH);
expect(graph.toString()).toBe('A,B,C,G,D,E,F,H');
const enterVertexCallback = jest.fn();
const leaveVertexCallback = jest.fn();
// Traverse graphs without callbacks first.
breadthFirstSearch(graph, vertexA);
// Traverse graph with enterVertex and leaveVertex callbacks.
breadthFirstSearch(graph, vertexA, {
enterVertex: enterVertexCallback,
leaveVertex: leaveVertexCallback,
});
expect(enterVertexCallback).toHaveBeenCalledTimes(8);
expect(leaveVertexCallback).toHaveBeenCalledTimes(8);
const enterVertexParamsMap = [
{ currentVertex: vertexA, previousVertex: null },
{ currentVertex: vertexB, previousVertex: vertexA },
{ currentVertex: vertexD, previousVertex: vertexB },
{ currentVertex: vertexE, previousVertex: vertexD },
{ currentVertex: vertexC, previousVertex: vertexE },
{ currentVertex: vertexH, previousVertex: vertexC },
{ currentVertex: vertexF, previousVertex: vertexH },
{ currentVertex: vertexG, previousVertex: vertexF },
];
for (let callIndex = 0; callIndex < graph.getAllVertices().length; callIndex += 1) {
const params = enterVertexCallback.mock.calls[callIndex][0];
expect(params.currentVertex).toEqual(enterVertexParamsMap[callIndex].currentVertex);
expect(params.previousVertex).toEqual(enterVertexParamsMap[callIndex].previousVertex);
}
const leaveVertexParamsMap = [
{ currentVertex: vertexA, previousVertex: null },
{ currentVertex: vertexB, previousVertex: vertexA },
{ currentVertex: vertexD, previousVertex: vertexB },
{ currentVertex: vertexE, previousVertex: vertexD },
{ currentVertex: vertexC, previousVertex: vertexE },
{ currentVertex: vertexH, previousVertex: vertexC },
{ currentVertex: vertexF, previousVertex: vertexH },
{ currentVertex: vertexG, previousVertex: vertexF },
];
for (let callIndex = 0; callIndex < graph.getAllVertices().length; callIndex += 1) {
const params = leaveVertexCallback.mock.calls[callIndex][0];
expect(params.currentVertex).toEqual(leaveVertexParamsMap[callIndex].currentVertex);
expect(params.previousVertex).toEqual(leaveVertexParamsMap[callIndex].previousVertex);
}
});
it('should allow to create custom vertex visiting logic', () => {
const graph = new Graph(true);
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const vertexE = new GraphVertex('E');
const vertexF = new GraphVertex('F');
const vertexG = new GraphVertex('G');
const vertexH = new GraphVertex('H');
const edgeAB = new GraphEdge(vertexA, vertexB);
const edgeBC = new GraphEdge(vertexB, vertexC);
const edgeCG = new GraphEdge(vertexC, vertexG);
const edgeAD = new GraphEdge(vertexA, vertexD);
const edgeAE = new GraphEdge(vertexA, vertexE);
const edgeEF = new GraphEdge(vertexE, vertexF);
const edgeFD = new GraphEdge(vertexF, vertexD);
const edgeDH = new GraphEdge(vertexD, vertexH);
const edgeGH = new GraphEdge(vertexG, vertexH);
graph
.addEdge(edgeAB)
.addEdge(edgeBC)
.addEdge(edgeCG)
.addEdge(edgeAD)
.addEdge(edgeAE)
.addEdge(edgeEF)
.addEdge(edgeFD)
.addEdge(edgeDH)
.addEdge(edgeGH);
expect(graph.toString()).toBe('A,B,C,G,D,E,F,H');
const enterVertexCallback = jest.fn();
const leaveVertexCallback = jest.fn();
// Traverse graph with enterVertex and leaveVertex callbacks.
breadthFirstSearch(graph, vertexA, {
enterVertex: enterVertexCallback,
leaveVertex: leaveVertexCallback,
allowTraversal: ({ currentVertex, nextVertex }) => {
return !(currentVertex === vertexA && nextVertex === vertexB);
},
});
expect(enterVertexCallback).toHaveBeenCalledTimes(7);
expect(leaveVertexCallback).toHaveBeenCalledTimes(7);
const enterVertexParamsMap = [
{ currentVertex: vertexA, previousVertex: null },
{ currentVertex: vertexD, previousVertex: vertexA },
{ currentVertex: vertexE, previousVertex: vertexD },
{ currentVertex: vertexH, previousVertex: vertexE },
{ currentVertex: vertexF, previousVertex: vertexH },
{ currentVertex: vertexD, previousVertex: vertexF },
{ currentVertex: vertexH, previousVertex: vertexD },
];
for (let callIndex = 0; callIndex < 7; callIndex += 1) {
const params = enterVertexCallback.mock.calls[callIndex][0];
expect(params.currentVertex).toEqual(enterVertexParamsMap[callIndex].currentVertex);
expect(params.previousVertex).toEqual(enterVertexParamsMap[callIndex].previousVertex);
}
const leaveVertexParamsMap = [
{ currentVertex: vertexA, previousVertex: null },
{ currentVertex: vertexD, previousVertex: vertexA },
{ currentVertex: vertexE, previousVertex: vertexD },
{ currentVertex: vertexH, previousVertex: vertexE },
{ currentVertex: vertexF, previousVertex: vertexH },
{ currentVertex: vertexD, previousVertex: vertexF },
{ currentVertex: vertexH, previousVertex: vertexD },
];
for (let callIndex = 0; callIndex < 7; callIndex += 1) {
const params = leaveVertexCallback.mock.calls[callIndex][0];
expect(params.currentVertex).toEqual(leaveVertexParamsMap[callIndex].currentVertex);
expect(params.previousVertex).toEqual(leaveVertexParamsMap[callIndex].previousVertex);
}
});
});
| 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 that will give us shortest path.
const nextVertices = Array(vertices.length).fill(null).map(() => {
return Array(vertices.length).fill(null);
});
// Init distances matrix with Infinities meaning there are no paths
// between vertices exist so far.
const distances = Array(vertices.length).fill(null).map(() => {
return Array(vertices.length).fill(Infinity);
});
// Init distance matrix with the distance we already now (from existing edges).
// And also init previous vertices from the edges.
vertices.forEach((startVertex, startIndex) => {
vertices.forEach((endVertex, endIndex) => {
if (startVertex === endVertex) {
// Distance to the vertex itself is 0.
distances[startIndex][endIndex] = 0;
} else {
// Find edge between the start and end vertices.
const edge = graph.findEdge(startVertex, endVertex);
if (edge) {
// There is an edge from vertex with startIndex to vertex with endIndex.
// Save distance and previous vertex.
distances[startIndex][endIndex] = edge.weight;
nextVertices[startIndex][endIndex] = startVertex;
} else {
distances[startIndex][endIndex] = Infinity;
}
}
});
});
// Now let's go to the core of the algorithm.
// Let's all pair of vertices (from start to end ones) and try to check if there
// is a shorter path exists between them via middle vertex. Middle vertex may also
// be one of the graph vertices. As you may see now we're going to have three
// loops over all graph vertices: for start, end and middle vertices.
vertices.forEach((middleVertex, middleIndex) => {
// Path starts from startVertex with startIndex.
vertices.forEach((startVertex, startIndex) => {
// Path ends to endVertex with endIndex.
vertices.forEach((endVertex, endIndex) => {
// Compare existing distance from startVertex to endVertex, with distance
// from startVertex to endVertex but via middleVertex.
// Save the shortest distance and previous vertex that allows
// us to have this shortest distance.
const distViaMiddle = distances[startIndex][middleIndex] + distances[middleIndex][endIndex];
if (distances[startIndex][endIndex] > distViaMiddle) {
// We've found a shortest pass via middle vertex.
distances[startIndex][endIndex] = distViaMiddle;
nextVertices[startIndex][endIndex] = middleVertex;
}
});
});
});
// Shortest distance from x to y: distance[x][y].
// Next vertex after x one in path from x to y: nextVertices[x][y].
return { distances, nextVertices };
}
| 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 all vertices for undirected graph', () => {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const vertexE = new GraphVertex('E');
const vertexF = new GraphVertex('F');
const vertexG = new GraphVertex('G');
const vertexH = new GraphVertex('H');
const edgeAB = new GraphEdge(vertexA, vertexB, 4);
const edgeAE = new GraphEdge(vertexA, vertexE, 7);
const edgeAC = new GraphEdge(vertexA, vertexC, 3);
const edgeBC = new GraphEdge(vertexB, vertexC, 6);
const edgeBD = new GraphEdge(vertexB, vertexD, 5);
const edgeEC = new GraphEdge(vertexE, vertexC, 8);
const edgeED = new GraphEdge(vertexE, vertexD, 2);
const edgeDC = new GraphEdge(vertexD, vertexC, 11);
const edgeDG = new GraphEdge(vertexD, vertexG, 10);
const edgeDF = new GraphEdge(vertexD, vertexF, 2);
const edgeFG = new GraphEdge(vertexF, vertexG, 3);
const edgeEG = new GraphEdge(vertexE, vertexG, 5);
const graph = new Graph();
// Add vertices first just to have them in desired order.
graph
.addVertex(vertexA)
.addVertex(vertexB)
.addVertex(vertexC)
.addVertex(vertexD)
.addVertex(vertexE)
.addVertex(vertexF)
.addVertex(vertexG)
.addVertex(vertexH);
// Now, when vertices are in correct order let's add edges.
graph
.addEdge(edgeAB)
.addEdge(edgeAE)
.addEdge(edgeAC)
.addEdge(edgeBC)
.addEdge(edgeBD)
.addEdge(edgeEC)
.addEdge(edgeED)
.addEdge(edgeDC)
.addEdge(edgeDG)
.addEdge(edgeDF)
.addEdge(edgeFG)
.addEdge(edgeEG);
const { distances, nextVertices } = floydWarshall(graph);
const vertices = graph.getAllVertices();
const vertexAIndex = vertices.indexOf(vertexA);
const vertexBIndex = vertices.indexOf(vertexB);
const vertexCIndex = vertices.indexOf(vertexC);
const vertexDIndex = vertices.indexOf(vertexD);
const vertexEIndex = vertices.indexOf(vertexE);
const vertexFIndex = vertices.indexOf(vertexF);
const vertexGIndex = vertices.indexOf(vertexG);
const vertexHIndex = vertices.indexOf(vertexH);
expect(distances[vertexAIndex][vertexHIndex]).toBe(Infinity);
expect(distances[vertexAIndex][vertexAIndex]).toBe(0);
expect(distances[vertexAIndex][vertexBIndex]).toBe(4);
expect(distances[vertexAIndex][vertexEIndex]).toBe(7);
expect(distances[vertexAIndex][vertexCIndex]).toBe(3);
expect(distances[vertexAIndex][vertexDIndex]).toBe(9);
expect(distances[vertexAIndex][vertexGIndex]).toBe(12);
expect(distances[vertexAIndex][vertexFIndex]).toBe(11);
expect(nextVertices[vertexAIndex][vertexFIndex]).toBe(vertexD);
expect(nextVertices[vertexAIndex][vertexDIndex]).toBe(vertexB);
expect(nextVertices[vertexAIndex][vertexBIndex]).toBe(vertexA);
expect(nextVertices[vertexAIndex][vertexGIndex]).toBe(vertexE);
expect(nextVertices[vertexAIndex][vertexCIndex]).toBe(vertexA);
expect(nextVertices[vertexAIndex][vertexAIndex]).toBe(null);
expect(nextVertices[vertexAIndex][vertexHIndex]).toBe(null);
});
it('should find minimum paths to all vertices for directed graph', () => {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const edgeAB = new GraphEdge(vertexA, vertexB, 3);
const edgeBA = new GraphEdge(vertexB, vertexA, 8);
const edgeAD = new GraphEdge(vertexA, vertexD, 7);
const edgeDA = new GraphEdge(vertexD, vertexA, 2);
const edgeBC = new GraphEdge(vertexB, vertexC, 2);
const edgeCA = new GraphEdge(vertexC, vertexA, 5);
const edgeCD = new GraphEdge(vertexC, vertexD, 1);
const graph = new Graph(true);
// Add vertices first just to have them in desired order.
graph
.addVertex(vertexA)
.addVertex(vertexB)
.addVertex(vertexC)
.addVertex(vertexD);
// Now, when vertices are in correct order let's add edges.
graph
.addEdge(edgeAB)
.addEdge(edgeBA)
.addEdge(edgeAD)
.addEdge(edgeDA)
.addEdge(edgeBC)
.addEdge(edgeCA)
.addEdge(edgeCD);
const { distances, nextVertices } = floydWarshall(graph);
const vertices = graph.getAllVertices();
const vertexAIndex = vertices.indexOf(vertexA);
const vertexBIndex = vertices.indexOf(vertexB);
const vertexCIndex = vertices.indexOf(vertexC);
const vertexDIndex = vertices.indexOf(vertexD);
expect(distances[vertexAIndex][vertexAIndex]).toBe(0);
expect(distances[vertexAIndex][vertexBIndex]).toBe(3);
expect(distances[vertexAIndex][vertexCIndex]).toBe(5);
expect(distances[vertexAIndex][vertexDIndex]).toBe(6);
expect(distances).toEqual([
[0, 3, 5, 6],
[5, 0, 2, 3],
[3, 6, 0, 1],
[2, 5, 7, 0],
]);
expect(nextVertices[vertexAIndex][vertexDIndex]).toBe(vertexC);
expect(nextVertices[vertexAIndex][vertexCIndex]).toBe(vertexB);
expect(nextVertices[vertexBIndex][vertexDIndex]).toBe(vertexC);
expect(nextVertices[vertexAIndex][vertexAIndex]).toBe(null);
expect(nextVertices[vertexAIndex][vertexBIndex]).toBe(vertexA);
});
it('should find minimum paths to all vertices for directed graph with negative edge weights', () => {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const vertexE = new GraphVertex('E');
const vertexF = new GraphVertex('F');
const vertexG = new GraphVertex('G');
const edgeFE = new GraphEdge(vertexF, vertexE, 8);
const edgeFA = new GraphEdge(vertexF, vertexA, 10);
const edgeED = new GraphEdge(vertexE, vertexD, 1);
const edgeDA = new GraphEdge(vertexD, vertexA, -4);
const edgeDC = new GraphEdge(vertexD, vertexC, -1);
const edgeAC = new GraphEdge(vertexA, vertexC, 2);
const edgeCB = new GraphEdge(vertexC, vertexB, -2);
const edgeBA = new GraphEdge(vertexB, vertexA, 1);
const graph = new Graph(true);
// Add vertices first just to have them in desired order.
graph
.addVertex(vertexA)
.addVertex(vertexB)
.addVertex(vertexC)
.addVertex(vertexD)
.addVertex(vertexE)
.addVertex(vertexF)
.addVertex(vertexG);
// Now, when vertices are in correct order let's add edges.
graph
.addEdge(edgeFE)
.addEdge(edgeFA)
.addEdge(edgeED)
.addEdge(edgeDA)
.addEdge(edgeDC)
.addEdge(edgeAC)
.addEdge(edgeCB)
.addEdge(edgeBA);
const { distances, nextVertices } = floydWarshall(graph);
const vertices = graph.getAllVertices();
const vertexAIndex = vertices.indexOf(vertexA);
const vertexBIndex = vertices.indexOf(vertexB);
const vertexCIndex = vertices.indexOf(vertexC);
const vertexDIndex = vertices.indexOf(vertexD);
const vertexEIndex = vertices.indexOf(vertexE);
const vertexGIndex = vertices.indexOf(vertexG);
const vertexFIndex = vertices.indexOf(vertexF);
expect(distances[vertexFIndex][vertexGIndex]).toBe(Infinity);
expect(distances[vertexFIndex][vertexFIndex]).toBe(0);
expect(distances[vertexFIndex][vertexAIndex]).toBe(5);
expect(distances[vertexFIndex][vertexBIndex]).toBe(5);
expect(distances[vertexFIndex][vertexCIndex]).toBe(7);
expect(distances[vertexFIndex][vertexDIndex]).toBe(9);
expect(distances[vertexFIndex][vertexEIndex]).toBe(8);
expect(nextVertices[vertexFIndex][vertexGIndex]).toBe(null);
expect(nextVertices[vertexFIndex][vertexFIndex]).toBe(null);
expect(nextVertices[vertexAIndex][vertexBIndex]).toBe(vertexC);
expect(nextVertices[vertexAIndex][vertexCIndex]).toBe(vertexA);
expect(nextVertices[vertexFIndex][vertexBIndex]).toBe(vertexE);
expect(nextVertices[vertexEIndex][vertexBIndex]).toBe(vertexD);
expect(nextVertices[vertexDIndex][vertexBIndex]).toBe(vertexC);
expect(nextVertices[vertexCIndex][vertexBIndex]).toBe(vertexC);
});
});
| 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);
// Generate visited set from path.
const visitedSet = currentPath.reduce((accumulator, vertex) => {
const updatedAccumulator = { ...accumulator };
updatedAccumulator[vertex.getKey()] = vertex;
return updatedAccumulator;
}, {});
// Get all unvisited neighbors of startVertex.
const unvisitedNeighbors = startVertex.getNeighbors().filter((neighbor) => {
return !visitedSet[neighbor.getKey()];
});
// If there no unvisited neighbors then treat current path as complete and save it.
if (!unvisitedNeighbors.length) {
paths.push(currentPath);
return paths;
}
// Go through all the neighbors.
for (let neighborIndex = 0; neighborIndex < unvisitedNeighbors.length; neighborIndex += 1) {
const currentUnvisitedNeighbor = unvisitedNeighbors[neighborIndex];
findAllPaths(currentUnvisitedNeighbor, paths, currentPath);
}
return paths;
}
/**
* @param {number[][]} adjacencyMatrix
* @param {object} verticesIndices
* @param {GraphVertex[]} cycle
* @return {number}
*/
function getCycleWeight(adjacencyMatrix, verticesIndices, cycle) {
let weight = 0;
for (let cycleIndex = 1; cycleIndex < cycle.length; cycleIndex += 1) {
const fromVertex = cycle[cycleIndex - 1];
const toVertex = cycle[cycleIndex];
const fromVertexIndex = verticesIndices[fromVertex.getKey()];
const toVertexIndex = verticesIndices[toVertex.getKey()];
weight += adjacencyMatrix[fromVertexIndex][toVertexIndex];
}
return weight;
}
/**
* BRUTE FORCE approach to solve Traveling Salesman Problem.
*
* @param {Graph} graph
* @return {GraphVertex[]}
*/
export default function bfTravellingSalesman(graph) {
// Pick starting point from where we will traverse the graph.
const startVertex = graph.getAllVertices()[0];
// BRUTE FORCE.
// Generate all possible paths from startVertex.
const allPossiblePaths = findAllPaths(startVertex);
// Filter out paths that are not cycles.
const allPossibleCycles = allPossiblePaths.filter((path) => {
/** @var {GraphVertex} */
const lastVertex = path[path.length - 1];
const lastVertexNeighbors = lastVertex.getNeighbors();
return lastVertexNeighbors.includes(startVertex);
});
// Go through all possible cycles and pick the one with minimum overall tour weight.
const adjacencyMatrix = graph.getAdjacencyMatrix();
const verticesIndices = graph.getVerticesIndices();
let salesmanPath = [];
let salesmanPathWeight = null;
for (let cycleIndex = 0; cycleIndex < allPossibleCycles.length; cycleIndex += 1) {
const currentCycle = allPossibleCycles[cycleIndex];
const currentCycleWeight = getCycleWeight(adjacencyMatrix, verticesIndices, currentCycle);
// If current cycle weight is smaller then previous ones treat current cycle as most optimal.
if (salesmanPathWeight === null || currentCycleWeight < salesmanPathWeight) {
salesmanPath = currentCycle;
salesmanPathWeight = currentCycleWeight;
}
}
// Return the solution.
return salesmanPath;
}
| 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 solve problem for simple graph', () => {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const edgeAB = new GraphEdge(vertexA, vertexB, 1);
const edgeBD = new GraphEdge(vertexB, vertexD, 1);
const edgeDC = new GraphEdge(vertexD, vertexC, 1);
const edgeCA = new GraphEdge(vertexC, vertexA, 1);
const edgeBA = new GraphEdge(vertexB, vertexA, 5);
const edgeDB = new GraphEdge(vertexD, vertexB, 8);
const edgeCD = new GraphEdge(vertexC, vertexD, 7);
const edgeAC = new GraphEdge(vertexA, vertexC, 4);
const edgeAD = new GraphEdge(vertexA, vertexD, 2);
const edgeDA = new GraphEdge(vertexD, vertexA, 3);
const edgeBC = new GraphEdge(vertexB, vertexC, 3);
const edgeCB = new GraphEdge(vertexC, vertexB, 9);
const graph = new Graph(true);
graph
.addEdge(edgeAB)
.addEdge(edgeBD)
.addEdge(edgeDC)
.addEdge(edgeCA)
.addEdge(edgeBA)
.addEdge(edgeDB)
.addEdge(edgeCD)
.addEdge(edgeAC)
.addEdge(edgeAD)
.addEdge(edgeDA)
.addEdge(edgeBC)
.addEdge(edgeCB);
const salesmanPath = bfTravellingSalesman(graph);
expect(salesmanPath.length).toBe(4);
expect(salesmanPath[0].getKey()).toEqual(vertexA.getKey());
expect(salesmanPath[1].getKey()).toEqual(vertexB.getKey());
expect(salesmanPath[2].getKey()).toEqual(vertexD.getKey());
expect(salesmanPath[3].getKey()).toEqual(vertexC.getKey());
});
});
| 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 finding the shortest paths to graph nodes.
* @param {Graph} graph - graph we're going to traverse.
* @param {GraphVertex} startVertex - traversal start vertex.
* @return {ShortestPaths}
*/
export default function dijkstra(graph, startVertex) {
// Init helper variables that we will need for Dijkstra algorithm.
const distances = {};
const visitedVertices = {};
const previousVertices = {};
const queue = new PriorityQueue();
// Init all distances with infinity assuming that currently we can't reach
// any of the vertices except the start one.
graph.getAllVertices().forEach((vertex) => {
distances[vertex.getKey()] = Infinity;
previousVertices[vertex.getKey()] = null;
});
// We are already at the startVertex so the distance to it is zero.
distances[startVertex.getKey()] = 0;
// Init vertices queue.
queue.add(startVertex, distances[startVertex.getKey()]);
// Iterate over the priority queue of vertices until it is empty.
while (!queue.isEmpty()) {
// Fetch next closest vertex.
const currentVertex = queue.poll();
// Iterate over every unvisited neighbor of the current vertex.
currentVertex.getNeighbors().forEach((neighbor) => {
// Don't visit already visited vertices.
if (!visitedVertices[neighbor.getKey()]) {
// Update distances to every neighbor from current vertex.
const edge = graph.findEdge(currentVertex, neighbor);
const existingDistanceToNeighbor = distances[neighbor.getKey()];
const distanceToNeighborFromCurrent = distances[currentVertex.getKey()] + edge.weight;
// If we've found shorter path to the neighbor - update it.
if (distanceToNeighborFromCurrent < existingDistanceToNeighbor) {
distances[neighbor.getKey()] = distanceToNeighborFromCurrent;
// Change priority of the neighbor in a queue since it might have became closer.
if (queue.hasValue(neighbor)) {
queue.changePriority(neighbor, distances[neighbor.getKey()]);
}
// Remember previous closest vertex.
previousVertices[neighbor.getKey()] = currentVertex;
}
// Add neighbor to the queue for further visiting.
if (!queue.hasValue(neighbor)) {
queue.add(neighbor, distances[neighbor.getKey()]);
}
}
});
// Add current vertex to visited ones to avoid visiting it again later.
visitedVertices[currentVertex.getKey()] = currentVertex;
}
// Return the set of shortest distances to all vertices and the set of
// shortest paths to all vertices in a graph.
return {
distances,
previousVertices,
};
}
| 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 undirected graph', () => {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const vertexE = new GraphVertex('E');
const vertexF = new GraphVertex('F');
const vertexG = new GraphVertex('G');
const vertexH = new GraphVertex('H');
const edgeAB = new GraphEdge(vertexA, vertexB, 4);
const edgeAE = new GraphEdge(vertexA, vertexE, 7);
const edgeAC = new GraphEdge(vertexA, vertexC, 3);
const edgeBC = new GraphEdge(vertexB, vertexC, 6);
const edgeBD = new GraphEdge(vertexB, vertexD, 5);
const edgeEC = new GraphEdge(vertexE, vertexC, 8);
const edgeED = new GraphEdge(vertexE, vertexD, 2);
const edgeDC = new GraphEdge(vertexD, vertexC, 11);
const edgeDG = new GraphEdge(vertexD, vertexG, 10);
const edgeDF = new GraphEdge(vertexD, vertexF, 2);
const edgeFG = new GraphEdge(vertexF, vertexG, 3);
const edgeEG = new GraphEdge(vertexE, vertexG, 5);
const graph = new Graph();
graph
.addVertex(vertexH)
.addEdge(edgeAB)
.addEdge(edgeAE)
.addEdge(edgeAC)
.addEdge(edgeBC)
.addEdge(edgeBD)
.addEdge(edgeEC)
.addEdge(edgeED)
.addEdge(edgeDC)
.addEdge(edgeDG)
.addEdge(edgeDF)
.addEdge(edgeFG)
.addEdge(edgeEG);
const { distances, previousVertices } = dijkstra(graph, vertexA);
expect(distances).toEqual({
H: Infinity,
A: 0,
B: 4,
E: 7,
C: 3,
D: 9,
G: 12,
F: 11,
});
expect(previousVertices.F.getKey()).toBe('D');
expect(previousVertices.D.getKey()).toBe('B');
expect(previousVertices.B.getKey()).toBe('A');
expect(previousVertices.G.getKey()).toBe('E');
expect(previousVertices.C.getKey()).toBe('A');
expect(previousVertices.A).toBeNull();
expect(previousVertices.H).toBeNull();
});
it('should find minimum paths to all vertices for directed graph with negative edge weights', () => {
const vertexS = new GraphVertex('S');
const vertexE = new GraphVertex('E');
const vertexA = new GraphVertex('A');
const vertexD = new GraphVertex('D');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexH = new GraphVertex('H');
const edgeSE = new GraphEdge(vertexS, vertexE, 8);
const edgeSA = new GraphEdge(vertexS, vertexA, 10);
const edgeED = new GraphEdge(vertexE, vertexD, 1);
const edgeDA = new GraphEdge(vertexD, vertexA, -4);
const edgeDC = new GraphEdge(vertexD, vertexC, -1);
const edgeAC = new GraphEdge(vertexA, vertexC, 2);
const edgeCB = new GraphEdge(vertexC, vertexB, -2);
const edgeBA = new GraphEdge(vertexB, vertexA, 1);
const graph = new Graph(true);
graph
.addVertex(vertexH)
.addEdge(edgeSE)
.addEdge(edgeSA)
.addEdge(edgeED)
.addEdge(edgeDA)
.addEdge(edgeDC)
.addEdge(edgeAC)
.addEdge(edgeCB)
.addEdge(edgeBA);
const { distances, previousVertices } = dijkstra(graph, vertexS);
expect(distances).toEqual({
H: Infinity,
S: 0,
A: 5,
B: 5,
C: 7,
D: 9,
E: 8,
});
expect(previousVertices.H).toBeNull();
expect(previousVertices.S).toBeNull();
expect(previousVertices.B.getKey()).toBe('C');
expect(previousVertices.C.getKey()).toBe('A');
expect(previousVertices.A.getKey()).toBe('D');
expect(previousVertices.D.getKey()).toBe('E');
});
});
| 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 with even rank (number of neighbors).
const evenRankVertices = {};
// Set that contains all vertices with odd rank (number of neighbors).
const oddRankVertices = {};
// Set of all not visited edges.
const notVisitedEdges = {};
graph.getAllEdges().forEach((vertex) => {
notVisitedEdges[vertex.getKey()] = vertex;
});
// Detect whether graph contains Eulerian Circuit or Eulerian Path or none of them.
/** @params {GraphVertex} vertex */
graph.getAllVertices().forEach((vertex) => {
if (vertex.getDegree() % 2) {
oddRankVertices[vertex.getKey()] = vertex;
} else {
evenRankVertices[vertex.getKey()] = vertex;
}
});
// Check whether we're dealing with Eulerian Circuit or Eulerian Path only.
// Graph would be an Eulerian Circuit in case if all its vertices has even degree.
// If not all vertices have even degree then graph must contain only two odd-degree
// vertices in order to have Euler Path.
const isCircuit = !Object.values(oddRankVertices).length;
if (!isCircuit && Object.values(oddRankVertices).length !== 2) {
throw new Error('Eulerian path must contain two odd-ranked vertices');
}
// Pick start vertex for traversal.
let startVertex = null;
if (isCircuit) {
// For Eulerian Circuit it doesn't matter from what vertex to start thus we'll just
// peek a first node.
const evenVertexKey = Object.keys(evenRankVertices)[0];
startVertex = evenRankVertices[evenVertexKey];
} else {
// For Eulerian Path we need to start from one of two odd-degree vertices.
const oddVertexKey = Object.keys(oddRankVertices)[0];
startVertex = oddRankVertices[oddVertexKey];
}
// Start traversing the graph.
let currentVertex = startVertex;
while (Object.values(notVisitedEdges).length) {
// Add current vertex to Eulerian path.
eulerianPathVertices.push(currentVertex);
// Detect all bridges in graph.
// We need to do it in order to not delete bridges if there are other edges
// exists for deletion.
const bridges = graphBridges(graph);
// Peek the next edge to delete from graph.
const currentEdges = currentVertex.getEdges();
/** @var {GraphEdge} edgeToDelete */
let edgeToDelete = null;
if (currentEdges.length === 1) {
// If there is only one edge left we need to peek it.
[edgeToDelete] = currentEdges;
} else {
// If there are many edges left then we need to peek any of those except bridges.
[edgeToDelete] = currentEdges.filter((edge) => !bridges[edge.getKey()]);
}
// Detect next current vertex.
if (currentVertex.getKey() === edgeToDelete.startVertex.getKey()) {
currentVertex = edgeToDelete.endVertex;
} else {
currentVertex = edgeToDelete.startVertex;
}
// Delete edge from not visited edges set.
delete notVisitedEdges[edgeToDelete.getKey()];
// If last edge were deleted then add finish vertex to Eulerian Path.
if (Object.values(notVisitedEdges).length === 0) {
eulerianPathVertices.push(currentVertex);
}
// Delete the edge from graph.
graph.deleteEdge(edgeToDelete);
}
return eulerianPathVertices;
}
| 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 is not Eulerian', () => {
function findEulerianPathInNotEulerianGraph() {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const vertexE = new GraphVertex('E');
const edgeAB = new GraphEdge(vertexA, vertexB);
const edgeAC = new GraphEdge(vertexA, vertexC);
const edgeBC = new GraphEdge(vertexB, vertexC);
const edgeBD = new GraphEdge(vertexB, vertexD);
const edgeCE = new GraphEdge(vertexC, vertexE);
const graph = new Graph();
graph
.addEdge(edgeAB)
.addEdge(edgeAC)
.addEdge(edgeBC)
.addEdge(edgeBD)
.addEdge(edgeCE);
eulerianPath(graph);
}
expect(findEulerianPathInNotEulerianGraph).toThrowError();
});
it('should find Eulerian Circuit in graph', () => {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const vertexE = new GraphVertex('E');
const vertexF = new GraphVertex('F');
const vertexG = new GraphVertex('G');
const edgeAB = new GraphEdge(vertexA, vertexB);
const edgeAE = new GraphEdge(vertexA, vertexE);
const edgeAF = new GraphEdge(vertexA, vertexF);
const edgeAG = new GraphEdge(vertexA, vertexG);
const edgeGF = new GraphEdge(vertexG, vertexF);
const edgeBE = new GraphEdge(vertexB, vertexE);
const edgeEB = new GraphEdge(vertexE, vertexB);
const edgeBC = new GraphEdge(vertexB, vertexC);
const edgeED = new GraphEdge(vertexE, vertexD);
const edgeCD = new GraphEdge(vertexC, vertexD);
const graph = new Graph();
graph
.addEdge(edgeAB)
.addEdge(edgeAE)
.addEdge(edgeAF)
.addEdge(edgeAG)
.addEdge(edgeGF)
.addEdge(edgeBE)
.addEdge(edgeEB)
.addEdge(edgeBC)
.addEdge(edgeED)
.addEdge(edgeCD);
const graphEdgesCount = graph.getAllEdges().length;
const eulerianPathSet = eulerianPath(graph);
expect(eulerianPathSet.length).toBe(graphEdgesCount + 1);
expect(eulerianPathSet[0].getKey()).toBe(vertexA.getKey());
expect(eulerianPathSet[1].getKey()).toBe(vertexB.getKey());
expect(eulerianPathSet[2].getKey()).toBe(vertexE.getKey());
expect(eulerianPathSet[3].getKey()).toBe(vertexB.getKey());
expect(eulerianPathSet[4].getKey()).toBe(vertexC.getKey());
expect(eulerianPathSet[5].getKey()).toBe(vertexD.getKey());
expect(eulerianPathSet[6].getKey()).toBe(vertexE.getKey());
expect(eulerianPathSet[7].getKey()).toBe(vertexA.getKey());
expect(eulerianPathSet[8].getKey()).toBe(vertexF.getKey());
expect(eulerianPathSet[9].getKey()).toBe(vertexG.getKey());
expect(eulerianPathSet[10].getKey()).toBe(vertexA.getKey());
});
it('should find Eulerian Path in graph', () => {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const vertexE = new GraphVertex('E');
const vertexF = new GraphVertex('F');
const vertexG = new GraphVertex('G');
const vertexH = new GraphVertex('H');
const edgeAB = new GraphEdge(vertexA, vertexB);
const edgeAC = new GraphEdge(vertexA, vertexC);
const edgeBD = new GraphEdge(vertexB, vertexD);
const edgeDC = new GraphEdge(vertexD, vertexC);
const edgeCE = new GraphEdge(vertexC, vertexE);
const edgeEF = new GraphEdge(vertexE, vertexF);
const edgeFH = new GraphEdge(vertexF, vertexH);
const edgeFG = new GraphEdge(vertexF, vertexG);
const edgeHG = new GraphEdge(vertexH, vertexG);
const graph = new Graph();
graph
.addEdge(edgeAB)
.addEdge(edgeAC)
.addEdge(edgeBD)
.addEdge(edgeDC)
.addEdge(edgeCE)
.addEdge(edgeEF)
.addEdge(edgeFH)
.addEdge(edgeFG)
.addEdge(edgeHG);
const graphEdgesCount = graph.getAllEdges().length;
const eulerianPathSet = eulerianPath(graph);
expect(eulerianPathSet.length).toBe(graphEdgesCount + 1);
expect(eulerianPathSet[0].getKey()).toBe(vertexC.getKey());
expect(eulerianPathSet[1].getKey()).toBe(vertexA.getKey());
expect(eulerianPathSet[2].getKey()).toBe(vertexB.getKey());
expect(eulerianPathSet[3].getKey()).toBe(vertexD.getKey());
expect(eulerianPathSet[4].getKey()).toBe(vertexC.getKey());
expect(eulerianPathSet[5].getKey()).toBe(vertexE.getKey());
expect(eulerianPathSet[6].getKey()).toBe(vertexF.getKey());
expect(eulerianPathSet[7].getKey()).toBe(vertexH.getKey());
expect(eulerianPathSet[8].getKey()).toBe(vertexG.getKey());
expect(eulerianPathSet[9].getKey()).toBe(vertexF.getKey());
});
});
| 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 undirected graphs.
if (graph.isDirected) {
throw new Error('Prim\'s algorithms works only for undirected graphs');
}
// Init new graph that will contain minimum spanning tree of original graph.
const minimumSpanningTree = new Graph();
// This priority queue will contain all the edges that are starting from
// visited nodes and they will be ranked by edge weight - so that on each step
// we would always pick the edge with minimal edge weight.
const edgesQueue = new PriorityQueue();
// Set of vertices that has been already visited.
const visitedVertices = {};
// Vertex from which we will start graph traversal.
const startVertex = graph.getAllVertices()[0];
// Add start vertex to the set of visited ones.
visitedVertices[startVertex.getKey()] = startVertex;
// Add all edges of start vertex to the queue.
startVertex.getEdges().forEach((graphEdge) => {
edgesQueue.add(graphEdge, graphEdge.weight);
});
// Now let's explore all queued edges.
while (!edgesQueue.isEmpty()) {
// Fetch next queued edge with minimal weight.
/** @var {GraphEdge} currentEdge */
const currentMinEdge = edgesQueue.poll();
// Find out the next unvisited minimal vertex to traverse.
let nextMinVertex = null;
if (!visitedVertices[currentMinEdge.startVertex.getKey()]) {
nextMinVertex = currentMinEdge.startVertex;
} else if (!visitedVertices[currentMinEdge.endVertex.getKey()]) {
nextMinVertex = currentMinEdge.endVertex;
}
// If all vertices of current edge has been already visited then skip this round.
if (nextMinVertex) {
// Add current min edge to MST.
minimumSpanningTree.addEdge(currentMinEdge);
// Add vertex to the set of visited ones.
visitedVertices[nextMinVertex.getKey()] = nextMinVertex;
// Add all current vertex's edges to the queue.
nextMinVertex.getEdges().forEach((graphEdge) => {
// Add only vertices that link to unvisited nodes.
if (
!visitedVertices[graphEdge.startVertex.getKey()]
|| !visitedVertices[graphEdge.endVertex.getKey()]
) {
edgesQueue.add(graphEdge, graphEdge.weight);
}
});
}
}
return minimumSpanningTree;
}
| 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', () => {
function applyPrimToDirectedGraph() {
const graph = new Graph(true);
prim(graph);
}
expect(applyPrimToDirectedGraph).toThrowError();
});
it('should find minimum spanning tree', () => {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const vertexE = new GraphVertex('E');
const vertexF = new GraphVertex('F');
const vertexG = new GraphVertex('G');
const edgeAB = new GraphEdge(vertexA, vertexB, 2);
const edgeAD = new GraphEdge(vertexA, vertexD, 3);
const edgeAC = new GraphEdge(vertexA, vertexC, 3);
const edgeBC = new GraphEdge(vertexB, vertexC, 4);
const edgeBE = new GraphEdge(vertexB, vertexE, 3);
const edgeDF = new GraphEdge(vertexD, vertexF, 7);
const edgeEC = new GraphEdge(vertexE, vertexC, 1);
const edgeEF = new GraphEdge(vertexE, vertexF, 8);
const edgeFG = new GraphEdge(vertexF, vertexG, 9);
const edgeFC = new GraphEdge(vertexF, vertexC, 6);
const graph = new Graph();
graph
.addEdge(edgeAB)
.addEdge(edgeAD)
.addEdge(edgeAC)
.addEdge(edgeBC)
.addEdge(edgeBE)
.addEdge(edgeDF)
.addEdge(edgeEC)
.addEdge(edgeEF)
.addEdge(edgeFC)
.addEdge(edgeFG);
expect(graph.getWeight()).toEqual(46);
const minimumSpanningTree = prim(graph);
expect(minimumSpanningTree.getWeight()).toBe(24);
expect(minimumSpanningTree.getAllVertices().length).toBe(graph.getAllVertices().length);
expect(minimumSpanningTree.getAllEdges().length).toBe(graph.getAllVertices().length - 1);
expect(minimumSpanningTree.toString()).toBe('A,B,C,E,D,F,G');
});
it('should find minimum spanning tree for simple graph', () => {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const edgeAB = new GraphEdge(vertexA, vertexB, 1);
const edgeAD = new GraphEdge(vertexA, vertexD, 3);
const edgeBC = new GraphEdge(vertexB, vertexC, 1);
const edgeBD = new GraphEdge(vertexB, vertexD, 3);
const edgeCD = new GraphEdge(vertexC, vertexD, 1);
const graph = new Graph();
graph
.addEdge(edgeAB)
.addEdge(edgeAD)
.addEdge(edgeBC)
.addEdge(edgeBD)
.addEdge(edgeCD);
expect(graph.getWeight()).toEqual(9);
const minimumSpanningTree = prim(graph);
expect(minimumSpanningTree.getWeight()).toBe(3);
expect(minimumSpanningTree.getAllVertices().length).toBe(graph.getAllVertices().length);
expect(minimumSpanningTree.getAllEdges().length).toBe(graph.getAllVertices().length - 1);
expect(minimumSpanningTree.toString()).toBe('A,B,C,D');
});
});
| 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) {
const endVertex = cycle[cycle.length - 1];
// Get end and candidate vertices indices in adjacency matrix.
const candidateVertexAdjacencyIndex = verticesIndices[vertexCandidate.getKey()];
const endVertexAdjacencyIndex = verticesIndices[endVertex.getKey()];
// Check if last vertex in the path and candidate vertex are adjacent.
if (adjacencyMatrix[endVertexAdjacencyIndex][candidateVertexAdjacencyIndex] === Infinity) {
return false;
}
// Check if vertexCandidate is being added to the path for the first time.
const candidateDuplicate = cycle.find((vertex) => vertex.getKey() === vertexCandidate.getKey());
return !candidateDuplicate;
}
/**
* @param {number[][]} adjacencyMatrix
* @param {object} verticesIndices
* @param {GraphVertex[]} cycle
* @return {boolean}
*/
function isCycle(adjacencyMatrix, verticesIndices, cycle) {
// Check if first and last vertices in hamiltonian path are adjacent.
// Get start and end vertices from the path.
const startVertex = cycle[0];
const endVertex = cycle[cycle.length - 1];
// Get start/end vertices indices in adjacency matrix.
const startVertexAdjacencyIndex = verticesIndices[startVertex.getKey()];
const endVertexAdjacencyIndex = verticesIndices[endVertex.getKey()];
// Check if we can go from end vertex to the start one.
return adjacencyMatrix[endVertexAdjacencyIndex][startVertexAdjacencyIndex] !== Infinity;
}
/**
* @param {number[][]} adjacencyMatrix
* @param {GraphVertex[]} vertices
* @param {object} verticesIndices
* @param {GraphVertex[][]} cycles
* @param {GraphVertex[]} cycle
*/
function hamiltonianCycleRecursive({
adjacencyMatrix,
vertices,
verticesIndices,
cycles,
cycle,
}) {
// Clone cycle in order to prevent it from modification by other DFS branches.
const currentCycle = [...cycle].map((vertex) => new GraphVertex(vertex.value));
if (vertices.length === currentCycle.length) {
// Hamiltonian path is found.
// Now we need to check if it is cycle or not.
if (isCycle(adjacencyMatrix, verticesIndices, currentCycle)) {
// Another solution has been found. Save it.
cycles.push(currentCycle);
}
return;
}
for (let vertexIndex = 0; vertexIndex < vertices.length; vertexIndex += 1) {
// Get vertex candidate that we will try to put into next path step and see if it fits.
const vertexCandidate = vertices[vertexIndex];
// Check if it is safe to put vertex candidate to cycle.
if (isSafe(adjacencyMatrix, verticesIndices, currentCycle, vertexCandidate)) {
// Add candidate vertex to cycle path.
currentCycle.push(vertexCandidate);
// Try to find other vertices in cycle.
hamiltonianCycleRecursive({
adjacencyMatrix,
vertices,
verticesIndices,
cycles,
cycle: currentCycle,
});
// BACKTRACKING.
// Remove candidate vertex from cycle path in order to try another one.
currentCycle.pop();
}
}
}
/**
* @param {Graph} graph
* @return {GraphVertex[][]}
*/
export default function hamiltonianCycle(graph) {
// Gather some information about the graph that we will need to during
// the problem solving.
const verticesIndices = graph.getVerticesIndices();
const adjacencyMatrix = graph.getAdjacencyMatrix();
const vertices = graph.getAllVertices();
// Define start vertex. We will always pick the first one
// this it doesn't matter which vertex to pick in a cycle.
// Every vertex is in a cycle so we can start from any of them.
const startVertex = vertices[0];
// Init cycles array that will hold all solutions.
const cycles = [];
// Init cycle array that will hold current cycle path.
const cycle = [startVertex];
// Try to find cycles recursively in Depth First Search order.
hamiltonianCycleRecursive({
adjacencyMatrix,
vertices,
verticesIndices,
cycles,
cycle,
});
// Return found cycles.
return cycles;
}
| 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 hamiltonian paths in graph', () => {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const vertexE = new GraphVertex('E');
const edgeAB = new GraphEdge(vertexA, vertexB);
const edgeAE = new GraphEdge(vertexA, vertexE);
const edgeAC = new GraphEdge(vertexA, vertexC);
const edgeBE = new GraphEdge(vertexB, vertexE);
const edgeBC = new GraphEdge(vertexB, vertexC);
const edgeBD = new GraphEdge(vertexB, vertexD);
const edgeCD = new GraphEdge(vertexC, vertexD);
const edgeDE = new GraphEdge(vertexD, vertexE);
const graph = new Graph();
graph
.addEdge(edgeAB)
.addEdge(edgeAE)
.addEdge(edgeAC)
.addEdge(edgeBE)
.addEdge(edgeBC)
.addEdge(edgeBD)
.addEdge(edgeCD)
.addEdge(edgeDE);
const hamiltonianCycleSet = hamiltonianCycle(graph);
expect(hamiltonianCycleSet.length).toBe(8);
expect(hamiltonianCycleSet[0][0].getKey()).toBe(vertexA.getKey());
expect(hamiltonianCycleSet[0][1].getKey()).toBe(vertexB.getKey());
expect(hamiltonianCycleSet[0][2].getKey()).toBe(vertexE.getKey());
expect(hamiltonianCycleSet[0][3].getKey()).toBe(vertexD.getKey());
expect(hamiltonianCycleSet[0][4].getKey()).toBe(vertexC.getKey());
expect(hamiltonianCycleSet[1][0].getKey()).toBe(vertexA.getKey());
expect(hamiltonianCycleSet[1][1].getKey()).toBe(vertexB.getKey());
expect(hamiltonianCycleSet[1][2].getKey()).toBe(vertexC.getKey());
expect(hamiltonianCycleSet[1][3].getKey()).toBe(vertexD.getKey());
expect(hamiltonianCycleSet[1][4].getKey()).toBe(vertexE.getKey());
expect(hamiltonianCycleSet[2][0].getKey()).toBe(vertexA.getKey());
expect(hamiltonianCycleSet[2][1].getKey()).toBe(vertexE.getKey());
expect(hamiltonianCycleSet[2][2].getKey()).toBe(vertexB.getKey());
expect(hamiltonianCycleSet[2][3].getKey()).toBe(vertexD.getKey());
expect(hamiltonianCycleSet[2][4].getKey()).toBe(vertexC.getKey());
expect(hamiltonianCycleSet[3][0].getKey()).toBe(vertexA.getKey());
expect(hamiltonianCycleSet[3][1].getKey()).toBe(vertexE.getKey());
expect(hamiltonianCycleSet[3][2].getKey()).toBe(vertexD.getKey());
expect(hamiltonianCycleSet[3][3].getKey()).toBe(vertexB.getKey());
expect(hamiltonianCycleSet[3][4].getKey()).toBe(vertexC.getKey());
});
it('should return false for graph without Hamiltonian path', () => {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const vertexE = new GraphVertex('E');
const edgeAB = new GraphEdge(vertexA, vertexB);
const edgeAE = new GraphEdge(vertexA, vertexE);
const edgeBE = new GraphEdge(vertexB, vertexE);
const edgeBC = new GraphEdge(vertexB, vertexC);
const edgeBD = new GraphEdge(vertexB, vertexD);
const edgeCD = new GraphEdge(vertexC, vertexD);
const graph = new Graph();
graph
.addEdge(edgeAB)
.addEdge(edgeAE)
.addEdge(edgeBE)
.addEdge(edgeBC)
.addEdge(edgeBD)
.addEdge(edgeCD);
const hamiltonianCycleSet = hamiltonianCycle(graph);
expect(hamiltonianCycleSet.length).toBe(0);
});
});
| 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
* @return {Object}
*/
export default function graphBridges(graph) {
// Set of vertices we've already visited during DFS.
const visitedSet = {};
// Set of bridges.
const bridges = {};
// Time needed to discover to the current vertex.
let discoveryTime = 0;
// Peek the start vertex for DFS traversal.
const startVertex = graph.getAllVertices()[0];
const dfsCallbacks = {
/**
* @param {GraphVertex} currentVertex
*/
enterVertex: ({ currentVertex }) => {
// Tick discovery time.
discoveryTime += 1;
// Put current vertex to visited set.
visitedSet[currentVertex.getKey()] = new VisitMetadata({
discoveryTime,
lowDiscoveryTime: discoveryTime,
});
},
/**
* @param {GraphVertex} currentVertex
* @param {GraphVertex} previousVertex
*/
leaveVertex: ({ currentVertex, previousVertex }) => {
if (previousVertex === null) {
// Don't do anything for the root vertex if it is already current (not previous one).
return;
}
// Check if current node is connected to any early node other then previous one.
visitedSet[currentVertex.getKey()].lowDiscoveryTime = currentVertex.getNeighbors()
.filter((earlyNeighbor) => earlyNeighbor.getKey() !== previousVertex.getKey())
.reduce(
/**
* @param {number} lowestDiscoveryTime
* @param {GraphVertex} neighbor
*/
(lowestDiscoveryTime, neighbor) => {
const neighborLowTime = visitedSet[neighbor.getKey()].lowDiscoveryTime;
return neighborLowTime < lowestDiscoveryTime ? neighborLowTime : lowestDiscoveryTime;
},
visitedSet[currentVertex.getKey()].lowDiscoveryTime,
);
// Compare low discovery times. In case if current low discovery time is less than the one
// in previous vertex then update previous vertex low time.
const currentLowDiscoveryTime = visitedSet[currentVertex.getKey()].lowDiscoveryTime;
const previousLowDiscoveryTime = visitedSet[previousVertex.getKey()].lowDiscoveryTime;
if (currentLowDiscoveryTime < previousLowDiscoveryTime) {
visitedSet[previousVertex.getKey()].lowDiscoveryTime = currentLowDiscoveryTime;
}
// Compare current vertex low discovery time with parent discovery time. Check if there
// are any short path (back edge) exists. If we can't get to current vertex other then
// via parent then the parent vertex is articulation point for current one.
const parentDiscoveryTime = visitedSet[previousVertex.getKey()].discoveryTime;
if (parentDiscoveryTime < currentLowDiscoveryTime) {
const bridge = graph.findEdge(previousVertex, currentVertex);
bridges[bridge.getKey()] = bridge;
}
},
allowTraversal: ({ nextVertex }) => {
return !visitedSet[nextVertex.getKey()];
},
};
// Do Depth First Search traversal over submitted graph.
depthFirstSearch(graph, startVertex, dfsCallbacks);
return bridges;
}
| 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 graph', () => {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const edgeAB = new GraphEdge(vertexA, vertexB);
const edgeBC = new GraphEdge(vertexB, vertexC);
const edgeCD = new GraphEdge(vertexC, vertexD);
const graph = new Graph();
graph
.addEdge(edgeAB)
.addEdge(edgeBC)
.addEdge(edgeCD);
const bridges = Object.values(graphBridges(graph));
expect(bridges.length).toBe(3);
expect(bridges[0].getKey()).toBe(edgeCD.getKey());
expect(bridges[1].getKey()).toBe(edgeBC.getKey());
expect(bridges[2].getKey()).toBe(edgeAB.getKey());
});
it('should find bridges in simple graph with back edge', () => {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const edgeAB = new GraphEdge(vertexA, vertexB);
const edgeBC = new GraphEdge(vertexB, vertexC);
const edgeCD = new GraphEdge(vertexC, vertexD);
const edgeAC = new GraphEdge(vertexA, vertexC);
const graph = new Graph();
graph
.addEdge(edgeAB)
.addEdge(edgeAC)
.addEdge(edgeBC)
.addEdge(edgeCD);
const bridges = Object.values(graphBridges(graph));
expect(bridges.length).toBe(1);
expect(bridges[0].getKey()).toBe(edgeCD.getKey());
});
it('should find bridges in graph', () => {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const vertexE = new GraphVertex('E');
const vertexF = new GraphVertex('F');
const vertexG = new GraphVertex('G');
const vertexH = new GraphVertex('H');
const edgeAB = new GraphEdge(vertexA, vertexB);
const edgeBC = new GraphEdge(vertexB, vertexC);
const edgeAC = new GraphEdge(vertexA, vertexC);
const edgeCD = new GraphEdge(vertexC, vertexD);
const edgeDE = new GraphEdge(vertexD, vertexE);
const edgeEG = new GraphEdge(vertexE, vertexG);
const edgeEF = new GraphEdge(vertexE, vertexF);
const edgeGF = new GraphEdge(vertexG, vertexF);
const edgeFH = new GraphEdge(vertexF, vertexH);
const graph = new Graph();
graph
.addEdge(edgeAB)
.addEdge(edgeBC)
.addEdge(edgeAC)
.addEdge(edgeCD)
.addEdge(edgeDE)
.addEdge(edgeEG)
.addEdge(edgeEF)
.addEdge(edgeGF)
.addEdge(edgeFH);
const bridges = Object.values(graphBridges(graph));
expect(bridges.length).toBe(3);
expect(bridges[0].getKey()).toBe(edgeFH.getKey());
expect(bridges[1].getKey()).toBe(edgeDE.getKey());
expect(bridges[2].getKey()).toBe(edgeCD.getKey());
});
it('should find bridges in graph starting with different root vertex', () => {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const vertexE = new GraphVertex('E');
const vertexF = new GraphVertex('F');
const vertexG = new GraphVertex('G');
const vertexH = new GraphVertex('H');
const edgeAB = new GraphEdge(vertexA, vertexB);
const edgeBC = new GraphEdge(vertexB, vertexC);
const edgeAC = new GraphEdge(vertexA, vertexC);
const edgeCD = new GraphEdge(vertexC, vertexD);
const edgeDE = new GraphEdge(vertexD, vertexE);
const edgeEG = new GraphEdge(vertexE, vertexG);
const edgeEF = new GraphEdge(vertexE, vertexF);
const edgeGF = new GraphEdge(vertexG, vertexF);
const edgeFH = new GraphEdge(vertexF, vertexH);
const graph = new Graph();
graph
.addEdge(edgeDE)
.addEdge(edgeAB)
.addEdge(edgeBC)
.addEdge(edgeAC)
.addEdge(edgeCD)
.addEdge(edgeEG)
.addEdge(edgeEF)
.addEdge(edgeGF)
.addEdge(edgeFH);
const bridges = Object.values(graphBridges(graph));
expect(bridges.length).toBe(3);
expect(bridges[0].getKey()).toBe(edgeFH.getKey());
expect(bridges[1].getKey()).toBe(edgeDE.getKey());
expect(bridges[2].getKey()).toBe(edgeCD.getKey());
});
it('should find bridges in yet another graph #1', () => {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const vertexE = new GraphVertex('E');
const edgeAB = new GraphEdge(vertexA, vertexB);
const edgeAC = new GraphEdge(vertexA, vertexC);
const edgeBC = new GraphEdge(vertexB, vertexC);
const edgeCD = new GraphEdge(vertexC, vertexD);
const edgeDE = new GraphEdge(vertexD, vertexE);
const graph = new Graph();
graph
.addEdge(edgeAB)
.addEdge(edgeAC)
.addEdge(edgeBC)
.addEdge(edgeCD)
.addEdge(edgeDE);
const bridges = Object.values(graphBridges(graph));
expect(bridges.length).toBe(2);
expect(bridges[0].getKey()).toBe(edgeDE.getKey());
expect(bridges[1].getKey()).toBe(edgeCD.getKey());
});
it('should find bridges in yet another graph #2', () => {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const vertexE = new GraphVertex('E');
const vertexF = new GraphVertex('F');
const vertexG = new GraphVertex('G');
const edgeAB = new GraphEdge(vertexA, vertexB);
const edgeAC = new GraphEdge(vertexA, vertexC);
const edgeBC = new GraphEdge(vertexB, vertexC);
const edgeCD = new GraphEdge(vertexC, vertexD);
const edgeCE = new GraphEdge(vertexC, vertexE);
const edgeCF = new GraphEdge(vertexC, vertexF);
const edgeEG = new GraphEdge(vertexE, vertexG);
const edgeFG = new GraphEdge(vertexF, vertexG);
const graph = new Graph();
graph
.addEdge(edgeAB)
.addEdge(edgeAC)
.addEdge(edgeBC)
.addEdge(edgeCD)
.addEdge(edgeCE)
.addEdge(edgeCF)
.addEdge(edgeEG)
.addEdge(edgeFG);
const bridges = Object.values(graphBridges(graph));
expect(bridges.length).toBe(1);
expect(bridges[0].getKey()).toBe(edgeCD.getKey());
});
});
| 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 check graph root node, whether it has two
// disconnected children or not.
this.independentChildrenCount = 0;
}
}
/**
* Tarjan's algorithm for finding articulation points in graph.
*
* @param {Graph} graph
* @return {Object}
*/
export default function articulationPoints(graph) {
// Set of vertices we've already visited during DFS.
const visitedSet = {};
// Set of articulation points.
const articulationPointsSet = {};
// Time needed to discover to the current vertex.
let discoveryTime = 0;
// Peek the start vertex for DFS traversal.
const startVertex = graph.getAllVertices()[0];
const dfsCallbacks = {
/**
* @param {GraphVertex} currentVertex
* @param {GraphVertex} previousVertex
*/
enterVertex: ({ currentVertex, previousVertex }) => {
// Tick discovery time.
discoveryTime += 1;
// Put current vertex to visited set.
visitedSet[currentVertex.getKey()] = new VisitMetadata({
discoveryTime,
lowDiscoveryTime: discoveryTime,
});
if (previousVertex) {
// Update children counter for previous vertex.
visitedSet[previousVertex.getKey()].independentChildrenCount += 1;
}
},
/**
* @param {GraphVertex} currentVertex
* @param {GraphVertex} previousVertex
*/
leaveVertex: ({ currentVertex, previousVertex }) => {
if (previousVertex === null) {
// Don't do anything for the root vertex if it is already current (not previous one)
return;
}
// Update the low time with the smallest time of adjacent vertices.
// Get minimum low discovery time from all neighbors.
/** @param {GraphVertex} neighbor */
visitedSet[currentVertex.getKey()].lowDiscoveryTime = currentVertex.getNeighbors()
.filter((earlyNeighbor) => earlyNeighbor.getKey() !== previousVertex.getKey())
/**
* @param {number} lowestDiscoveryTime
* @param {GraphVertex} neighbor
*/
.reduce(
(lowestDiscoveryTime, neighbor) => {
const neighborLowTime = visitedSet[neighbor.getKey()].lowDiscoveryTime;
return neighborLowTime < lowestDiscoveryTime ? neighborLowTime : lowestDiscoveryTime;
},
visitedSet[currentVertex.getKey()].lowDiscoveryTime,
);
// Detect whether previous vertex is articulation point or not.
// To do so we need to check two [OR] conditions:
// 1. Is it a root vertex with at least two independent children.
// 2. If its visited time is <= low time of adjacent vertex.
if (previousVertex === startVertex) {
// Check that root vertex has at least two independent children.
if (visitedSet[previousVertex.getKey()].independentChildrenCount >= 2) {
articulationPointsSet[previousVertex.getKey()] = previousVertex;
}
} else {
// Get current vertex low discovery time.
const currentLowDiscoveryTime = visitedSet[currentVertex.getKey()].lowDiscoveryTime;
// Compare current vertex low discovery time with parent discovery time. Check if there
// are any short path (back edge) exists. If we can't get to current vertex other then
// via parent then the parent vertex is articulation point for current one.
const parentDiscoveryTime = visitedSet[previousVertex.getKey()].discoveryTime;
if (parentDiscoveryTime <= currentLowDiscoveryTime) {
articulationPointsSet[previousVertex.getKey()] = previousVertex;
}
}
},
allowTraversal: ({ nextVertex }) => {
return !visitedSet[nextVertex.getKey()];
},
};
// Do Depth First Search traversal over submitted graph.
depthFirstSearch(graph, startVertex, dfsCallbacks);
return articulationPointsSet;
}
| 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 articulation points in simple graph', () => {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const edgeAB = new GraphEdge(vertexA, vertexB);
const edgeBC = new GraphEdge(vertexB, vertexC);
const edgeCD = new GraphEdge(vertexC, vertexD);
const graph = new Graph();
graph
.addEdge(edgeAB)
.addEdge(edgeBC)
.addEdge(edgeCD);
const articulationPointsSet = Object.values(articulationPoints(graph));
expect(articulationPointsSet.length).toBe(2);
expect(articulationPointsSet[0].getKey()).toBe(vertexC.getKey());
expect(articulationPointsSet[1].getKey()).toBe(vertexB.getKey());
});
it('should find articulation points in simple graph with back edge', () => {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const edgeAB = new GraphEdge(vertexA, vertexB);
const edgeBC = new GraphEdge(vertexB, vertexC);
const edgeCD = new GraphEdge(vertexC, vertexD);
const edgeAC = new GraphEdge(vertexA, vertexC);
const graph = new Graph();
graph
.addEdge(edgeAB)
.addEdge(edgeAC)
.addEdge(edgeBC)
.addEdge(edgeCD);
const articulationPointsSet = Object.values(articulationPoints(graph));
expect(articulationPointsSet.length).toBe(1);
expect(articulationPointsSet[0].getKey()).toBe(vertexC.getKey());
});
it('should find articulation points in simple graph with back edge #2', () => {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const vertexE = new GraphVertex('E');
const edgeAB = new GraphEdge(vertexA, vertexB);
const edgeBC = new GraphEdge(vertexB, vertexC);
const edgeCD = new GraphEdge(vertexC, vertexD);
const edgeAE = new GraphEdge(vertexA, vertexE);
const edgeCE = new GraphEdge(vertexC, vertexE);
const graph = new Graph();
graph
.addEdge(edgeAB)
.addEdge(edgeAE)
.addEdge(edgeCE)
.addEdge(edgeBC)
.addEdge(edgeCD);
const articulationPointsSet = Object.values(articulationPoints(graph));
expect(articulationPointsSet.length).toBe(1);
expect(articulationPointsSet[0].getKey()).toBe(vertexC.getKey());
});
it('should find articulation points in graph', () => {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const vertexE = new GraphVertex('E');
const vertexF = new GraphVertex('F');
const vertexG = new GraphVertex('G');
const vertexH = new GraphVertex('H');
const edgeAB = new GraphEdge(vertexA, vertexB);
const edgeBC = new GraphEdge(vertexB, vertexC);
const edgeAC = new GraphEdge(vertexA, vertexC);
const edgeCD = new GraphEdge(vertexC, vertexD);
const edgeDE = new GraphEdge(vertexD, vertexE);
const edgeEG = new GraphEdge(vertexE, vertexG);
const edgeEF = new GraphEdge(vertexE, vertexF);
const edgeGF = new GraphEdge(vertexG, vertexF);
const edgeFH = new GraphEdge(vertexF, vertexH);
const graph = new Graph();
graph
.addEdge(edgeAB)
.addEdge(edgeBC)
.addEdge(edgeAC)
.addEdge(edgeCD)
.addEdge(edgeDE)
.addEdge(edgeEG)
.addEdge(edgeEF)
.addEdge(edgeGF)
.addEdge(edgeFH);
const articulationPointsSet = Object.values(articulationPoints(graph));
expect(articulationPointsSet.length).toBe(4);
expect(articulationPointsSet[0].getKey()).toBe(vertexF.getKey());
expect(articulationPointsSet[1].getKey()).toBe(vertexE.getKey());
expect(articulationPointsSet[2].getKey()).toBe(vertexD.getKey());
expect(articulationPointsSet[3].getKey()).toBe(vertexC.getKey());
});
it('should find articulation points in graph starting with articulation root vertex', () => {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const vertexE = new GraphVertex('E');
const vertexF = new GraphVertex('F');
const vertexG = new GraphVertex('G');
const vertexH = new GraphVertex('H');
const edgeAB = new GraphEdge(vertexA, vertexB);
const edgeBC = new GraphEdge(vertexB, vertexC);
const edgeAC = new GraphEdge(vertexA, vertexC);
const edgeCD = new GraphEdge(vertexC, vertexD);
const edgeDE = new GraphEdge(vertexD, vertexE);
const edgeEG = new GraphEdge(vertexE, vertexG);
const edgeEF = new GraphEdge(vertexE, vertexF);
const edgeGF = new GraphEdge(vertexG, vertexF);
const edgeFH = new GraphEdge(vertexF, vertexH);
const graph = new Graph();
graph
.addEdge(edgeDE)
.addEdge(edgeAB)
.addEdge(edgeBC)
.addEdge(edgeAC)
.addEdge(edgeCD)
.addEdge(edgeEG)
.addEdge(edgeEF)
.addEdge(edgeGF)
.addEdge(edgeFH);
const articulationPointsSet = Object.values(articulationPoints(graph));
expect(articulationPointsSet.length).toBe(4);
expect(articulationPointsSet[0].getKey()).toBe(vertexF.getKey());
expect(articulationPointsSet[1].getKey()).toBe(vertexE.getKey());
expect(articulationPointsSet[2].getKey()).toBe(vertexC.getKey());
expect(articulationPointsSet[3].getKey()).toBe(vertexD.getKey());
});
it('should find articulation points in yet another graph #1', () => {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const vertexE = new GraphVertex('E');
const edgeAB = new GraphEdge(vertexA, vertexB);
const edgeAC = new GraphEdge(vertexA, vertexC);
const edgeBC = new GraphEdge(vertexB, vertexC);
const edgeCD = new GraphEdge(vertexC, vertexD);
const edgeDE = new GraphEdge(vertexD, vertexE);
const graph = new Graph();
graph
.addEdge(edgeAB)
.addEdge(edgeAC)
.addEdge(edgeBC)
.addEdge(edgeCD)
.addEdge(edgeDE);
const articulationPointsSet = Object.values(articulationPoints(graph));
expect(articulationPointsSet.length).toBe(2);
expect(articulationPointsSet[0].getKey()).toBe(vertexD.getKey());
expect(articulationPointsSet[1].getKey()).toBe(vertexC.getKey());
});
it('should find articulation points in yet another graph #2', () => {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const vertexE = new GraphVertex('E');
const vertexF = new GraphVertex('F');
const vertexG = new GraphVertex('G');
const edgeAB = new GraphEdge(vertexA, vertexB);
const edgeAC = new GraphEdge(vertexA, vertexC);
const edgeBC = new GraphEdge(vertexB, vertexC);
const edgeCD = new GraphEdge(vertexC, vertexD);
const edgeCE = new GraphEdge(vertexC, vertexE);
const edgeCF = new GraphEdge(vertexC, vertexF);
const edgeEG = new GraphEdge(vertexE, vertexG);
const edgeFG = new GraphEdge(vertexF, vertexG);
const graph = new Graph();
graph
.addEdge(edgeAB)
.addEdge(edgeAC)
.addEdge(edgeBC)
.addEdge(edgeCD)
.addEdge(edgeCE)
.addEdge(edgeCF)
.addEdge(edgeEG)
.addEdge(edgeFG);
const articulationPointsSet = Object.values(articulationPoints(graph));
expect(articulationPointsSet.length).toBe(1);
expect(articulationPointsSet[0].getKey()).toBe(vertexC.getKey());
});
});
| 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] - Called when DFS enters the vertex.
*
* @property {function(vertices: Object)} [leaveVertex] - Called when DFS leaves the vertex.
*/
/**
* @param {Callbacks} [callbacks]
* @returns {Callbacks}
*/
function initCallbacks(callbacks = {}) {
const initiatedCallback = callbacks;
const stubCallback = () => {};
const allowTraversalCallback = (
() => {
const seen = {};
return ({ nextVertex }) => {
if (!seen[nextVertex.getKey()]) {
seen[nextVertex.getKey()] = true;
return true;
}
return false;
};
}
)();
initiatedCallback.allowTraversal = callbacks.allowTraversal || allowTraversalCallback;
initiatedCallback.enterVertex = callbacks.enterVertex || stubCallback;
initiatedCallback.leaveVertex = callbacks.leaveVertex || stubCallback;
return initiatedCallback;
}
/**
* @param {Graph} graph
* @param {GraphVertex} currentVertex
* @param {GraphVertex} previousVertex
* @param {Callbacks} callbacks
*/
function depthFirstSearchRecursive(graph, currentVertex, previousVertex, callbacks) {
callbacks.enterVertex({ currentVertex, previousVertex });
graph.getNeighbors(currentVertex).forEach((nextVertex) => {
if (callbacks.allowTraversal({ previousVertex, currentVertex, nextVertex })) {
depthFirstSearchRecursive(graph, nextVertex, currentVertex, callbacks);
}
});
callbacks.leaveVertex({ currentVertex, previousVertex });
}
/**
* @param {Graph} graph
* @param {GraphVertex} startVertex
* @param {Callbacks} [callbacks]
*/
export default function depthFirstSearch(graph, startVertex, callbacks) {
const previousVertex = null;
depthFirstSearchRecursive(graph, startVertex, previousVertex, initCallbacks(callbacks));
}
| 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 operation on graph', () => {
const graph = new Graph(true);
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const vertexE = new GraphVertex('E');
const vertexF = new GraphVertex('F');
const vertexG = new GraphVertex('G');
const edgeAB = new GraphEdge(vertexA, vertexB);
const edgeBC = new GraphEdge(vertexB, vertexC);
const edgeCG = new GraphEdge(vertexC, vertexG);
const edgeAD = new GraphEdge(vertexA, vertexD);
const edgeAE = new GraphEdge(vertexA, vertexE);
const edgeEF = new GraphEdge(vertexE, vertexF);
const edgeFD = new GraphEdge(vertexF, vertexD);
const edgeDG = new GraphEdge(vertexD, vertexG);
graph
.addEdge(edgeAB)
.addEdge(edgeBC)
.addEdge(edgeCG)
.addEdge(edgeAD)
.addEdge(edgeAE)
.addEdge(edgeEF)
.addEdge(edgeFD)
.addEdge(edgeDG);
expect(graph.toString()).toBe('A,B,C,G,D,E,F');
const enterVertexCallback = jest.fn();
const leaveVertexCallback = jest.fn();
// Traverse graphs without callbacks first to check default ones.
depthFirstSearch(graph, vertexA);
// Traverse graph with enterVertex and leaveVertex callbacks.
depthFirstSearch(graph, vertexA, {
enterVertex: enterVertexCallback,
leaveVertex: leaveVertexCallback,
});
expect(enterVertexCallback).toHaveBeenCalledTimes(graph.getAllVertices().length);
expect(leaveVertexCallback).toHaveBeenCalledTimes(graph.getAllVertices().length);
const enterVertexParamsMap = [
{ currentVertex: vertexA, previousVertex: null },
{ currentVertex: vertexB, previousVertex: vertexA },
{ currentVertex: vertexC, previousVertex: vertexB },
{ currentVertex: vertexG, previousVertex: vertexC },
{ currentVertex: vertexD, previousVertex: vertexA },
{ currentVertex: vertexE, previousVertex: vertexA },
{ currentVertex: vertexF, previousVertex: vertexE },
];
for (let callIndex = 0; callIndex < graph.getAllVertices().length; callIndex += 1) {
const params = enterVertexCallback.mock.calls[callIndex][0];
expect(params.currentVertex).toEqual(enterVertexParamsMap[callIndex].currentVertex);
expect(params.previousVertex).toEqual(enterVertexParamsMap[callIndex].previousVertex);
}
const leaveVertexParamsMap = [
{ currentVertex: vertexG, previousVertex: vertexC },
{ currentVertex: vertexC, previousVertex: vertexB },
{ currentVertex: vertexB, previousVertex: vertexA },
{ currentVertex: vertexD, previousVertex: vertexA },
{ currentVertex: vertexF, previousVertex: vertexE },
{ currentVertex: vertexE, previousVertex: vertexA },
{ currentVertex: vertexA, previousVertex: null },
];
for (let callIndex = 0; callIndex < graph.getAllVertices().length; callIndex += 1) {
const params = leaveVertexCallback.mock.calls[callIndex][0];
expect(params.currentVertex).toEqual(leaveVertexParamsMap[callIndex].currentVertex);
expect(params.previousVertex).toEqual(leaveVertexParamsMap[callIndex].previousVertex);
}
});
it('allow users to redefine vertex visiting logic', () => {
const graph = new Graph(true);
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const vertexE = new GraphVertex('E');
const vertexF = new GraphVertex('F');
const vertexG = new GraphVertex('G');
const edgeAB = new GraphEdge(vertexA, vertexB);
const edgeBC = new GraphEdge(vertexB, vertexC);
const edgeCG = new GraphEdge(vertexC, vertexG);
const edgeAD = new GraphEdge(vertexA, vertexD);
const edgeAE = new GraphEdge(vertexA, vertexE);
const edgeEF = new GraphEdge(vertexE, vertexF);
const edgeFD = new GraphEdge(vertexF, vertexD);
const edgeDG = new GraphEdge(vertexD, vertexG);
graph
.addEdge(edgeAB)
.addEdge(edgeBC)
.addEdge(edgeCG)
.addEdge(edgeAD)
.addEdge(edgeAE)
.addEdge(edgeEF)
.addEdge(edgeFD)
.addEdge(edgeDG);
expect(graph.toString()).toBe('A,B,C,G,D,E,F');
const enterVertexCallback = jest.fn();
const leaveVertexCallback = jest.fn();
depthFirstSearch(graph, vertexA, {
enterVertex: enterVertexCallback,
leaveVertex: leaveVertexCallback,
allowTraversal: ({ currentVertex, nextVertex }) => {
return !(currentVertex === vertexA && nextVertex === vertexB);
},
});
expect(enterVertexCallback).toHaveBeenCalledTimes(7);
expect(leaveVertexCallback).toHaveBeenCalledTimes(7);
const enterVertexParamsMap = [
{ currentVertex: vertexA, previousVertex: null },
{ currentVertex: vertexD, previousVertex: vertexA },
{ currentVertex: vertexG, previousVertex: vertexD },
{ currentVertex: vertexE, previousVertex: vertexA },
{ currentVertex: vertexF, previousVertex: vertexE },
{ currentVertex: vertexD, previousVertex: vertexF },
{ currentVertex: vertexG, previousVertex: vertexD },
];
for (let callIndex = 0; callIndex < graph.getAllVertices().length; callIndex += 1) {
const params = enterVertexCallback.mock.calls[callIndex][0];
expect(params.currentVertex).toEqual(enterVertexParamsMap[callIndex].currentVertex);
expect(params.previousVertex).toEqual(enterVertexParamsMap[callIndex].previousVertex);
}
const leaveVertexParamsMap = [
{ currentVertex: vertexG, previousVertex: vertexD },
{ currentVertex: vertexD, previousVertex: vertexA },
{ currentVertex: vertexG, previousVertex: vertexD },
{ currentVertex: vertexD, previousVertex: vertexF },
{ currentVertex: vertexF, previousVertex: vertexE },
{ currentVertex: vertexE, previousVertex: vertexA },
{ currentVertex: vertexA, previousVertex: null },
];
for (let callIndex = 0; callIndex < graph.getAllVertices().length; callIndex += 1) {
const params = leaveVertexCallback.mock.calls[callIndex][0];
expect(params.currentVertex).toEqual(leaveVertexParamsMap[callIndex].currentVertex);
expect(params.previousVertex).toEqual(leaveVertexParamsMap[callIndex].previousVertex);
}
});
});
| 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 will be needed in order to specify what path exactly is a cycle.
const dfsParentMap = {};
// White set (UNVISITED) contains all the vertices that haven't been visited at all.
const whiteSet = {};
// Gray set (VISITING) contains all the vertices that are being visited right now
// (in current path).
const graySet = {};
// Black set (VISITED) contains all the vertices that has been fully visited.
// Meaning that all children of the vertex has been visited.
const blackSet = {};
// If we encounter vertex in gray set it means that we've found a cycle.
// Because when vertex in gray set it means that its neighbors or its neighbors
// neighbors are still being explored.
// Init white set and add all vertices to it.
/** @param {GraphVertex} vertex */
graph.getAllVertices().forEach((vertex) => {
whiteSet[vertex.getKey()] = vertex;
});
// Describe BFS callbacks.
const callbacks = {
enterVertex: ({ currentVertex, previousVertex }) => {
if (graySet[currentVertex.getKey()]) {
// If current vertex already in grey set it means that cycle is detected.
// Let's detect cycle path.
cycle = {};
let currentCycleVertex = currentVertex;
let previousCycleVertex = previousVertex;
while (previousCycleVertex.getKey() !== currentVertex.getKey()) {
cycle[currentCycleVertex.getKey()] = previousCycleVertex;
currentCycleVertex = previousCycleVertex;
previousCycleVertex = dfsParentMap[previousCycleVertex.getKey()];
}
cycle[currentCycleVertex.getKey()] = previousCycleVertex;
} else {
// Otherwise let's add current vertex to gray set and remove it from white set.
graySet[currentVertex.getKey()] = currentVertex;
delete whiteSet[currentVertex.getKey()];
// Update DFS parents list.
dfsParentMap[currentVertex.getKey()] = previousVertex;
}
},
leaveVertex: ({ currentVertex }) => {
// If all node's children has been visited let's remove it from gray set
// and move it to the black set meaning that all its neighbors are visited.
blackSet[currentVertex.getKey()] = currentVertex;
delete graySet[currentVertex.getKey()];
},
allowTraversal: ({ nextVertex }) => {
// If cycle was detected we must forbid all further traversing since it will
// cause infinite traversal loop.
if (cycle) {
return false;
}
// Allow traversal only for the vertices that are not in black set
// since all black set vertices have been already visited.
return !blackSet[nextVertex.getKey()];
},
};
// Start exploring vertices.
while (Object.keys(whiteSet).length) {
// Pick fist vertex to start BFS from.
const firstWhiteKey = Object.keys(whiteSet)[0];
const startVertex = whiteSet[firstWhiteKey];
// Do Depth First Search.
depthFirstSearch(graph, startVertex, callbacks);
}
return cycle;
}
| 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 = {};
// List of parents vertices for every visited vertex.
const parents = {};
// Callbacks for DFS traversing.
const callbacks = {
allowTraversal: ({ currentVertex, nextVertex }) => {
// Don't allow further traversal in case if cycle has been detected.
if (cycle) {
return false;
}
// Don't allow traversal from child back to its parent.
const currentVertexParent = parents[currentVertex.getKey()];
const currentVertexParentKey = currentVertexParent ? currentVertexParent.getKey() : null;
return currentVertexParentKey !== nextVertex.getKey();
},
enterVertex: ({ currentVertex, previousVertex }) => {
if (visitedVertices[currentVertex.getKey()]) {
// Compile cycle path based on parents of previous vertices.
cycle = {};
let currentCycleVertex = currentVertex;
let previousCycleVertex = previousVertex;
while (previousCycleVertex.getKey() !== currentVertex.getKey()) {
cycle[currentCycleVertex.getKey()] = previousCycleVertex;
currentCycleVertex = previousCycleVertex;
previousCycleVertex = parents[previousCycleVertex.getKey()];
}
cycle[currentCycleVertex.getKey()] = previousCycleVertex;
} else {
// Add next vertex to visited set.
visitedVertices[currentVertex.getKey()] = currentVertex;
parents[currentVertex.getKey()] = previousVertex;
}
},
};
// Start DFS traversing.
const startVertex = graph.getAllVertices()[0];
depthFirstSearch(graph, startVertex, callbacks);
return cycle;
}
| 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 {GraphVertex} graphVertex */
const keyExtractor = (graphVertex) => graphVertex.getKey();
const disjointSet = new DisjointSet(keyExtractor);
graph.getAllVertices().forEach((graphVertex) => disjointSet.makeSet(graphVertex));
// Go trough all graph edges one by one and check if edge vertices are from the
// different sets. In this case joint those sets together. Do this until you find
// an edge where to edge vertices are already in one set. This means that current
// edge will create a cycle.
let cycleFound = false;
/** @param {GraphEdge} graphEdge */
graph.getAllEdges().forEach((graphEdge) => {
if (disjointSet.inSameSet(graphEdge.startVertex, graphEdge.endVertex)) {
// Cycle found.
cycleFound = true;
} else {
disjointSet.union(graphEdge.startVertex, graphEdge.endVertex);
}
});
return cycleFound;
}
| 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 detect directed cycle', () => {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const vertexE = new GraphVertex('E');
const vertexF = new GraphVertex('F');
const edgeAB = new GraphEdge(vertexA, vertexB);
const edgeBC = new GraphEdge(vertexB, vertexC);
const edgeAC = new GraphEdge(vertexA, vertexC);
const edgeDA = new GraphEdge(vertexD, vertexA);
const edgeDE = new GraphEdge(vertexD, vertexE);
const edgeEF = new GraphEdge(vertexE, vertexF);
const edgeFD = new GraphEdge(vertexF, vertexD);
const graph = new Graph(true);
graph
.addEdge(edgeAB)
.addEdge(edgeBC)
.addEdge(edgeAC)
.addEdge(edgeDA)
.addEdge(edgeDE)
.addEdge(edgeEF);
expect(detectDirectedCycle(graph)).toBeNull();
graph.addEdge(edgeFD);
expect(detectDirectedCycle(graph)).toEqual({
D: vertexF,
F: vertexE,
E: vertexD,
});
});
});
| 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 detect undirected cycle', () => {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const vertexE = new GraphVertex('E');
const vertexF = new GraphVertex('F');
const edgeAF = new GraphEdge(vertexA, vertexF);
const edgeAB = new GraphEdge(vertexA, vertexB);
const edgeBE = new GraphEdge(vertexB, vertexE);
const edgeBC = new GraphEdge(vertexB, vertexC);
const edgeCD = new GraphEdge(vertexC, vertexD);
const edgeDE = new GraphEdge(vertexD, vertexE);
const graph = new Graph();
graph
.addEdge(edgeAF)
.addEdge(edgeAB)
.addEdge(edgeBE)
.addEdge(edgeBC)
.addEdge(edgeCD);
expect(detectUndirectedCycle(graph)).toBeNull();
graph.addEdge(edgeDE);
expect(detectUndirectedCycle(graph)).toEqual({
B: vertexC,
C: vertexD,
D: vertexE,
E: vertexB,
});
});
});
| 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('detectUndirectedCycleUsingDisjointSet', () => {
it('should detect undirected cycle', () => {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const vertexE = new GraphVertex('E');
const vertexF = new GraphVertex('F');
const edgeAF = new GraphEdge(vertexA, vertexF);
const edgeAB = new GraphEdge(vertexA, vertexB);
const edgeBE = new GraphEdge(vertexB, vertexE);
const edgeBC = new GraphEdge(vertexB, vertexC);
const edgeCD = new GraphEdge(vertexC, vertexD);
const edgeDE = new GraphEdge(vertexD, vertexE);
const graph = new Graph();
graph
.addEdge(edgeAF)
.addEdge(edgeAB)
.addEdge(edgeBE)
.addEdge(edgeBC)
.addEdge(edgeCD);
expect(detectUndirectedCycleUsingDisjointSet(graph)).toBe(false);
graph.addEdge(edgeDE);
expect(detectUndirectedCycleUsingDisjointSet(graph)).toBe(true);
});
});
| 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 vertices except start one.
distances[startVertex.getKey()] = 0;
graph.getAllVertices().forEach((vertex) => {
previousVertices[vertex.getKey()] = null;
if (vertex.getKey() !== startVertex.getKey()) {
distances[vertex.getKey()] = Infinity;
}
});
// We need (|V| - 1) iterations.
for (let iteration = 0; iteration < (graph.getAllVertices().length - 1); iteration += 1) {
// During each iteration go through all vertices.
Object.keys(distances).forEach((vertexKey) => {
const vertex = graph.getVertexByKey(vertexKey);
// Go through all vertex edges.
graph.getNeighbors(vertex).forEach((neighbor) => {
const edge = graph.findEdge(vertex, neighbor);
// Find out if the distance to the neighbor is shorter in this iteration
// then in previous one.
const distanceToVertex = distances[vertex.getKey()];
const distanceToNeighbor = distanceToVertex + edge.weight;
if (distanceToNeighbor < distances[neighbor.getKey()]) {
distances[neighbor.getKey()] = distanceToNeighbor;
previousVertices[neighbor.getKey()] = vertex;
}
});
});
}
return {
distances,
previousVertices,
};
}
| 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 vertices for undirected graph', () => {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const vertexE = new GraphVertex('E');
const vertexF = new GraphVertex('F');
const vertexG = new GraphVertex('G');
const vertexH = new GraphVertex('H');
const edgeAB = new GraphEdge(vertexA, vertexB, 4);
const edgeAE = new GraphEdge(vertexA, vertexE, 7);
const edgeAC = new GraphEdge(vertexA, vertexC, 3);
const edgeBC = new GraphEdge(vertexB, vertexC, 6);
const edgeBD = new GraphEdge(vertexB, vertexD, 5);
const edgeEC = new GraphEdge(vertexE, vertexC, 8);
const edgeED = new GraphEdge(vertexE, vertexD, 2);
const edgeDC = new GraphEdge(vertexD, vertexC, 11);
const edgeDG = new GraphEdge(vertexD, vertexG, 10);
const edgeDF = new GraphEdge(vertexD, vertexF, 2);
const edgeFG = new GraphEdge(vertexF, vertexG, 3);
const edgeEG = new GraphEdge(vertexE, vertexG, 5);
const graph = new Graph();
graph
.addVertex(vertexH)
.addEdge(edgeAB)
.addEdge(edgeAE)
.addEdge(edgeAC)
.addEdge(edgeBC)
.addEdge(edgeBD)
.addEdge(edgeEC)
.addEdge(edgeED)
.addEdge(edgeDC)
.addEdge(edgeDG)
.addEdge(edgeDF)
.addEdge(edgeFG)
.addEdge(edgeEG);
const { distances, previousVertices } = bellmanFord(graph, vertexA);
expect(distances).toEqual({
H: Infinity,
A: 0,
B: 4,
E: 7,
C: 3,
D: 9,
G: 12,
F: 11,
});
expect(previousVertices.F.getKey()).toBe('D');
expect(previousVertices.D.getKey()).toBe('B');
expect(previousVertices.B.getKey()).toBe('A');
expect(previousVertices.G.getKey()).toBe('E');
expect(previousVertices.C.getKey()).toBe('A');
expect(previousVertices.A).toBeNull();
expect(previousVertices.H).toBeNull();
});
it('should find minimum paths to all vertices for directed graph with negative edge weights', () => {
const vertexS = new GraphVertex('S');
const vertexE = new GraphVertex('E');
const vertexA = new GraphVertex('A');
const vertexD = new GraphVertex('D');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexH = new GraphVertex('H');
const edgeSE = new GraphEdge(vertexS, vertexE, 8);
const edgeSA = new GraphEdge(vertexS, vertexA, 10);
const edgeED = new GraphEdge(vertexE, vertexD, 1);
const edgeDA = new GraphEdge(vertexD, vertexA, -4);
const edgeDC = new GraphEdge(vertexD, vertexC, -1);
const edgeAC = new GraphEdge(vertexA, vertexC, 2);
const edgeCB = new GraphEdge(vertexC, vertexB, -2);
const edgeBA = new GraphEdge(vertexB, vertexA, 1);
const graph = new Graph(true);
graph
.addVertex(vertexH)
.addEdge(edgeSE)
.addEdge(edgeSA)
.addEdge(edgeED)
.addEdge(edgeDA)
.addEdge(edgeDC)
.addEdge(edgeAC)
.addEdge(edgeCB)
.addEdge(edgeBA);
const { distances, previousVertices } = bellmanFord(graph, vertexS);
expect(distances).toEqual({
H: Infinity,
S: 0,
A: 5,
B: 5,
C: 7,
D: 9,
E: 8,
});
expect(previousVertices.H).toBeNull();
expect(previousVertices.S).toBeNull();
expect(previousVertices.B.getKey()).toBe('C');
expect(previousVertices.C.getKey()).toBe('A');
expect(previousVertices.A.getKey()).toBe('D');
expect(previousVertices.D.getKey()).toBe('E');
});
});
| 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 = {};
// Stack of vertices by finish time.
// All vertices in this stack are ordered by finished time in decreasing order.
// Vertex that has been finished first will be at the bottom of the stack and
// vertex that has been finished last will be at the top of the stack.
const verticesByDfsFinishTime = new Stack();
// Set of all vertices we're going to visit.
const notVisitedVerticesSet = {};
graph.getAllVertices().forEach((vertex) => {
notVisitedVerticesSet[vertex.getKey()] = vertex;
});
// Specify DFS traversal callbacks.
const dfsCallbacks = {
enterVertex: ({ currentVertex }) => {
// Add current vertex to visited set.
visitedVerticesSet[currentVertex.getKey()] = currentVertex;
// Delete current vertex from not visited set.
delete notVisitedVerticesSet[currentVertex.getKey()];
},
leaveVertex: ({ currentVertex }) => {
// Push vertex to the stack when leaving it.
// This will make stack to be ordered by finish time in decreasing order.
verticesByDfsFinishTime.push(currentVertex);
},
allowTraversal: ({ nextVertex }) => {
// Don't allow to traverse the nodes that have been already visited.
return !visitedVerticesSet[nextVertex.getKey()];
},
};
// Do FIRST DFS PASS traversal for all graph vertices to fill the verticesByFinishTime stack.
while (Object.values(notVisitedVerticesSet).length) {
// Peek any vertex to start DFS traversal from.
const startVertexKey = Object.keys(notVisitedVerticesSet)[0];
const startVertex = notVisitedVerticesSet[startVertexKey];
delete notVisitedVerticesSet[startVertexKey];
depthFirstSearch(graph, startVertex, dfsCallbacks);
}
return verticesByDfsFinishTime;
}
/**
* @param {Graph} graph
* @param {Stack} verticesByFinishTime
* @return {*[]}
*/
function getSCCSets(graph, verticesByFinishTime) {
// Array of arrays of strongly connected vertices.
const stronglyConnectedComponentsSets = [];
// Array that will hold all vertices that are being visited during one DFS run.
let stronglyConnectedComponentsSet = [];
// Visited vertices set.
const visitedVerticesSet = {};
// Callbacks for DFS traversal.
const dfsCallbacks = {
enterVertex: ({ currentVertex }) => {
// Add current vertex to SCC set of current DFS round.
stronglyConnectedComponentsSet.push(currentVertex);
// Add current vertex to visited set.
visitedVerticesSet[currentVertex.getKey()] = currentVertex;
},
leaveVertex: ({ previousVertex }) => {
// Once DFS traversal is finished push the set of found strongly connected
// components during current DFS round to overall strongly connected components set.
// The sign that traversal is about to be finished is that we came back to start vertex
// which doesn't have parent.
if (previousVertex === null) {
stronglyConnectedComponentsSets.push([...stronglyConnectedComponentsSet]);
}
},
allowTraversal: ({ nextVertex }) => {
// Don't allow traversal of already visited vertices.
return !visitedVerticesSet[nextVertex.getKey()];
},
};
while (!verticesByFinishTime.isEmpty()) {
/** @var {GraphVertex} startVertex */
const startVertex = verticesByFinishTime.pop();
// Reset the set of strongly connected vertices.
stronglyConnectedComponentsSet = [];
// Don't do DFS on already visited vertices.
if (!visitedVerticesSet[startVertex.getKey()]) {
// Do DFS traversal.
depthFirstSearch(graph, startVertex, dfsCallbacks);
}
}
return stronglyConnectedComponentsSets;
}
/**
* Kosaraju's algorithm.
*
* @param {Graph} graph
* @return {*[]}
*/
export default function stronglyConnectedComponents(graph) {
// In this algorithm we will need to do TWO DFS PASSES overt the graph.
// Get stack of vertices ordered by DFS finish time.
// All vertices in this stack are ordered by finished time in decreasing order:
// Vertex that has been finished first will be at the bottom of the stack and
// vertex that has been finished last will be at the top of the stack.
const verticesByFinishTime = getVerticesSortedByDfsFinishTime(graph);
// Reverse the graph.
graph.reverse();
// Do DFS once again on reversed graph.
return getSCCSets(graph, verticesByFinishTime);
}
| 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', () => {
it('should detect strongly connected components in simple graph', () => {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const edgeAB = new GraphEdge(vertexA, vertexB);
const edgeBC = new GraphEdge(vertexB, vertexC);
const edgeCA = new GraphEdge(vertexC, vertexA);
const edgeCD = new GraphEdge(vertexC, vertexD);
const graph = new Graph(true);
graph
.addEdge(edgeAB)
.addEdge(edgeBC)
.addEdge(edgeCA)
.addEdge(edgeCD);
const components = stronglyConnectedComponents(graph);
expect(components).toBeDefined();
expect(components.length).toBe(2);
expect(components[0][0].getKey()).toBe(vertexA.getKey());
expect(components[0][1].getKey()).toBe(vertexC.getKey());
expect(components[0][2].getKey()).toBe(vertexB.getKey());
expect(components[1][0].getKey()).toBe(vertexD.getKey());
});
it('should detect strongly connected components in graph', () => {
const vertexA = new GraphVertex('A');
const vertexB = new GraphVertex('B');
const vertexC = new GraphVertex('C');
const vertexD = new GraphVertex('D');
const vertexE = new GraphVertex('E');
const vertexF = new GraphVertex('F');
const vertexG = new GraphVertex('G');
const vertexH = new GraphVertex('H');
const vertexI = new GraphVertex('I');
const vertexJ = new GraphVertex('J');
const vertexK = new GraphVertex('K');
const edgeAB = new GraphEdge(vertexA, vertexB);
const edgeBC = new GraphEdge(vertexB, vertexC);
const edgeCA = new GraphEdge(vertexC, vertexA);
const edgeBD = new GraphEdge(vertexB, vertexD);
const edgeDE = new GraphEdge(vertexD, vertexE);
const edgeEF = new GraphEdge(vertexE, vertexF);
const edgeFD = new GraphEdge(vertexF, vertexD);
const edgeGF = new GraphEdge(vertexG, vertexF);
const edgeGH = new GraphEdge(vertexG, vertexH);
const edgeHI = new GraphEdge(vertexH, vertexI);
const edgeIJ = new GraphEdge(vertexI, vertexJ);
const edgeJG = new GraphEdge(vertexJ, vertexG);
const edgeJK = new GraphEdge(vertexJ, vertexK);
const graph = new Graph(true);
graph
.addEdge(edgeAB)
.addEdge(edgeBC)
.addEdge(edgeCA)
.addEdge(edgeBD)
.addEdge(edgeDE)
.addEdge(edgeEF)
.addEdge(edgeFD)
.addEdge(edgeGF)
.addEdge(edgeGH)
.addEdge(edgeHI)
.addEdge(edgeIJ)
.addEdge(edgeJG)
.addEdge(edgeJK);
const components = stronglyConnectedComponents(graph);
expect(components).toBeDefined();
expect(components.length).toBe(4);
expect(components[0][0].getKey()).toBe(vertexG.getKey());
expect(components[0][1].getKey()).toBe(vertexJ.getKey());
expect(components[0][2].getKey()).toBe(vertexI.getKey());
expect(components[0][3].getKey()).toBe(vertexH.getKey());
expect(components[1][0].getKey()).toBe(vertexK.getKey());
expect(components[2][0].getKey()).toBe(vertexA.getKey());
expect(components[2][1].getKey()).toBe(vertexC.getKey());
expect(components[2][2].getKey()).toBe(vertexB.getKey());
expect(components[3][0].getKey()).toBe(vertexD.getKey());
expect(components[3][1].getKey()).toBe(vertexF.getKey());
expect(components[3][2].getKey()).toBe(vertexE.getKey());
});
});
| 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 squareRoot(number, tolerance = 0) {
// For now we won't support operations that involves manipulation with complex numbers.
if (number < 0) {
throw new Error('The method supports only positive integers');
}
// Handle edge case with finding the square root of zero.
if (number === 0) {
return 0;
}
// We will start approximation from value 1.
let root = 1;
// Delta is a desired distance between the number and the square of the root.
// - if tolerance=0 then delta=1
// - if tolerance=1 then delta=0.1
// - if tolerance=2 then delta=0.01
// - and so on...
const requiredDelta = 1 / (10 ** tolerance);
// Approximating the root value to the point when we get a desired precision.
while (Math.abs(number - (root ** 2)) > requiredDelta) {
// Newton's method reduces in this case to the so-called Babylonian method.
// These methods generally yield approximate results, but can be made arbitrarily
// precise by increasing the number of calculation steps.
root -= ((root ** 2) - number) / (2 * root);
}
// Cut off undesired floating digits and return the root value.
return Math.round(root * (10 ** tolerance)) / (10 ** tolerance);
}
| 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', () => {
expect(squareRoot(0)).toBe(0);
expect(squareRoot(1)).toBe(1);
expect(squareRoot(2)).toBe(1);
expect(squareRoot(3)).toBe(2);
expect(squareRoot(4)).toBe(2);
expect(squareRoot(15)).toBe(4);
expect(squareRoot(16)).toBe(4);
expect(squareRoot(256)).toBe(16);
expect(squareRoot(473)).toBe(22);
expect(squareRoot(14723)).toBe(121);
});
it('should correctly calculate square root for integers with custom tolerance', () => {
let tolerance = 1;
expect(squareRoot(0, tolerance)).toBe(0);
expect(squareRoot(1, tolerance)).toBe(1);
expect(squareRoot(2, tolerance)).toBe(1.4);
expect(squareRoot(3, tolerance)).toBe(1.8);
expect(squareRoot(4, tolerance)).toBe(2);
expect(squareRoot(15, tolerance)).toBe(3.9);
expect(squareRoot(16, tolerance)).toBe(4);
expect(squareRoot(256, tolerance)).toBe(16);
expect(squareRoot(473, tolerance)).toBe(21.7);
expect(squareRoot(14723, tolerance)).toBe(121.3);
tolerance = 3;
expect(squareRoot(0, tolerance)).toBe(0);
expect(squareRoot(1, tolerance)).toBe(1);
expect(squareRoot(2, tolerance)).toBe(1.414);
expect(squareRoot(3, tolerance)).toBe(1.732);
expect(squareRoot(4, tolerance)).toBe(2);
expect(squareRoot(15, tolerance)).toBe(3.873);
expect(squareRoot(16, tolerance)).toBe(4);
expect(squareRoot(256, tolerance)).toBe(16);
expect(squareRoot(473, tolerance)).toBe(21.749);
expect(squareRoot(14723, tolerance)).toBe(121.338);
tolerance = 10;
expect(squareRoot(0, tolerance)).toBe(0);
expect(squareRoot(1, tolerance)).toBe(1);
expect(squareRoot(2, tolerance)).toBe(1.4142135624);
expect(squareRoot(3, tolerance)).toBe(1.7320508076);
expect(squareRoot(4, tolerance)).toBe(2);
expect(squareRoot(15, tolerance)).toBe(3.8729833462);
expect(squareRoot(16, tolerance)).toBe(4);
expect(squareRoot(256, tolerance)).toBe(16);
expect(squareRoot(473, tolerance)).toBe(21.7485631709);
expect(squareRoot(14723, tolerance)).toBe(121.3383698588);
});
it('should correctly calculate square root for integers with custom tolerance', () => {
expect(squareRoot(4.5, 10)).toBe(2.1213203436);
expect(squareRoot(217.534, 10)).toBe(14.7490338667);
});
});
| 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) {
if (power === 0) {
// Anything that is raised to the power of zero is 1.
return 1;
}
if (power % 2 === 0) {
// If the power is even...
// we may recursively redefine the result via twice smaller powers:
// x^8 = x^4 * x^4.
const multiplier = fastPowering(base, power / 2);
return multiplier * multiplier;
}
// If the power is odd...
// we may recursively redefine the result via twice smaller powers:
// x^9 = x^4 * x^4 * x.
const multiplier = fastPowering(base, Math.floor(power / 2));
return multiplier * multiplier * base;
}
| 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)).toBe(16);
expect(fastPowering(2, 5)).toBe(32);
expect(fastPowering(2, 6)).toBe(64);
expect(fastPowering(2, 7)).toBe(128);
expect(fastPowering(2, 8)).toBe(256);
expect(fastPowering(3, 4)).toBe(81);
expect(fastPowering(190, 2)).toBe(36100);
expect(fastPowering(11, 5)).toBe(161051);
expect(fastPowering(13, 11)).toBe(1792160394037);
expect(fastPowering(9, 16)).toBe(1853020188851841);
expect(fastPowering(16, 16)).toBe(18446744073709552000);
expect(fastPowering(7, 21)).toBe(558545864083284000);
expect(fastPowering(100, 9)).toBe(1000000000000000000);
});
});
| 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 = Math.abs(originalB);
// Subtract one number from another until both numbers would become the same.
// This will be out GCD. Also quit the loop if one of the numbers is zero.
while (a && b && a !== b) {
[a, b] = a > b ? [a - b, b] : [a, b - a];
}
// Return the number that is not equal to zero since the last subtraction (it will be a GCD).
return a || 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 = Math.abs(originalB);
// To make algorithm work faster instead of subtracting one number from the other
// we may use modulo operation.
return (b === 0) ? a : euclideanAlgorithm(b, a % 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/__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)).toBe(1);
expect(euclideanAlgorithm(2, 1)).toBe(1);
expect(euclideanAlgorithm(6, 6)).toBe(6);
expect(euclideanAlgorithm(2, 4)).toBe(2);
expect(euclideanAlgorithm(4, 2)).toBe(2);
expect(euclideanAlgorithm(12, 4)).toBe(4);
expect(euclideanAlgorithm(4, 12)).toBe(4);
expect(euclideanAlgorithm(5, 13)).toBe(1);
expect(euclideanAlgorithm(27, 13)).toBe(1);
expect(euclideanAlgorithm(24, 60)).toBe(12);
expect(euclideanAlgorithm(60, 24)).toBe(12);
expect(euclideanAlgorithm(252, 105)).toBe(21);
expect(euclideanAlgorithm(105, 252)).toBe(21);
expect(euclideanAlgorithm(1071, 462)).toBe(21);
expect(euclideanAlgorithm(462, 1071)).toBe(21);
expect(euclideanAlgorithm(462, -1071)).toBe(21);
expect(euclideanAlgorithm(-462, -1071)).toBe(21);
});
});
| 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(0, 2)).toBe(2);
expect(euclideanAlgorithmIterative(1, 2)).toBe(1);
expect(euclideanAlgorithmIterative(2, 1)).toBe(1);
expect(euclideanAlgorithmIterative(6, 6)).toBe(6);
expect(euclideanAlgorithmIterative(2, 4)).toBe(2);
expect(euclideanAlgorithmIterative(4, 2)).toBe(2);
expect(euclideanAlgorithmIterative(12, 4)).toBe(4);
expect(euclideanAlgorithmIterative(4, 12)).toBe(4);
expect(euclideanAlgorithmIterative(5, 13)).toBe(1);
expect(euclideanAlgorithmIterative(27, 13)).toBe(1);
expect(euclideanAlgorithmIterative(24, 60)).toBe(12);
expect(euclideanAlgorithmIterative(60, 24)).toBe(12);
expect(euclideanAlgorithmIterative(252, 105)).toBe(21);
expect(euclideanAlgorithmIterative(105, 252)).toBe(21);
expect(euclideanAlgorithmIterative(1071, 462)).toBe(21);
expect(euclideanAlgorithmIterative(462, 1071)).toBe(21);
expect(euclideanAlgorithmIterative(462, -1071)).toBe(21);
expect(euclideanAlgorithmIterative(-462, -1071)).toBe(21);
});
});
| 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} zeroThreshold - Threshold that is used to convert real and imaginary numbers
* to zero in case if they are smaller then this.
*
* @return {number[]} - Discrete amplitudes distributed in time.
*/
export default function inverseDiscreteFourierTransform(
frequencies,
zeroThreshold = CLOSE_TO_ZERO_THRESHOLD,
) {
const N = frequencies.length;
const amplitudes = [];
// Go through every discrete point of time.
for (let timer = 0; timer < N; timer += 1) {
// Compound amplitude at current time.
let amplitude = new ComplexNumber();
// Go through all discrete frequencies.
for (let frequency = 0; frequency < N; frequency += 1) {
const currentFrequency = frequencies[frequency];
// Calculate rotation angle.
const rotationAngle = (2 * Math.PI) * frequency * (timer / N);
// Remember that e^ix = cos(x) + i * sin(x);
const frequencyContribution = new ComplexNumber({
re: Math.cos(rotationAngle),
im: Math.sin(rotationAngle),
}).multiply(currentFrequency);
amplitude = amplitude.add(frequencyContribution);
}
// Close to zero? You're zero.
if (Math.abs(amplitude.re) < zeroThreshold) {
amplitude.re = 0;
}
if (Math.abs(amplitude.im) < zeroThreshold) {
amplitude.im = 0;
}
// Add current frequency signal to the list of compound signals.
amplitudes[timer] = amplitude.re;
}
return amplitudes;
}
| 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).
* @param {number} zeroThreshold - Threshold that is used to convert real and imaginary numbers
* to zero in case if they are smaller then this.
*
* @return {ComplexNumber[]} - Array of complex number. Each of the number represents the frequency
* or signal. All signals together will form input signal over discrete time periods. Each signal's
* complex number has radius (amplitude) and phase (angle) in polar form that describes the signal.
*
* @see https://gist.github.com/anonymous/129d477ddb1c8025c9ac
* @see https://betterexplained.com/articles/an-interactive-guide-to-the-fourier-transform/
*/
export default function dft(inputAmplitudes, zeroThreshold = CLOSE_TO_ZERO_THRESHOLD) {
const N = inputAmplitudes.length;
const signals = [];
// Go through every discrete frequency.
for (let frequency = 0; frequency < N; frequency += 1) {
// Compound signal at current frequency that will ultimately
// take part in forming input amplitudes.
let frequencySignal = new ComplexNumber();
// Go through every discrete point in time.
for (let timer = 0; timer < N; timer += 1) {
const currentAmplitude = inputAmplitudes[timer];
// Calculate rotation angle.
const rotationAngle = -1 * (2 * Math.PI) * frequency * (timer / N);
// Remember that e^ix = cos(x) + i * sin(x);
const dataPointContribution = new ComplexNumber({
re: Math.cos(rotationAngle),
im: Math.sin(rotationAngle),
}).multiply(currentAmplitude);
// Add this data point's contribution.
frequencySignal = frequencySignal.add(dataPointContribution);
}
// Close to zero? You're zero.
if (Math.abs(frequencySignal.re) < zeroThreshold) {
frequencySignal.re = 0;
}
if (Math.abs(frequencySignal.im) < zeroThreshold) {
frequencySignal.im = 0;
}
// Average contribution at this frequency.
// The 1/N factor is usually moved to the reverse transform (going from frequencies
// back to time). This is allowed, though it would be nice to have 1/N in the forward
// transform since it gives the actual sizes for the time spikes.
frequencySignal = frequencySignal.divide(N);
// Add current frequency signal to the list of compound signals.
signals[frequency] = frequencySignal;
}
return signals;
}
| 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 reversedBits = 0;
for (let bitIndex = 0; bitIndex < bitsCount; bitIndex += 1) {
reversedBits *= 2;
if (Math.floor(input / (1 << bitIndex)) % 2 === 1) {
reversedBits += 1;
}
}
return reversedBits;
}
/**
* Returns the radix-2 fast fourier transform of the given array.
* Optionally computes the radix-2 inverse fast fourier transform.
*
* @param {ComplexNumber[]} inputData
* @param {boolean} [inverse]
* @return {ComplexNumber[]}
*/
export default function fastFourierTransform(inputData, inverse = false) {
const bitsCount = bitLength(inputData.length - 1);
const N = 1 << bitsCount;
while (inputData.length < N) {
inputData.push(new ComplexNumber());
}
const output = [];
for (let dataSampleIndex = 0; dataSampleIndex < N; dataSampleIndex += 1) {
output[dataSampleIndex] = inputData[reverseBits(dataSampleIndex, bitsCount)];
}
for (let blockLength = 2; blockLength <= N; blockLength *= 2) {
const imaginarySign = inverse ? -1 : 1;
const phaseStep = new ComplexNumber({
re: Math.cos((2 * Math.PI) / blockLength),
im: imaginarySign * Math.sin((2 * Math.PI) / blockLength),
});
for (let blockStart = 0; blockStart < N; blockStart += blockLength) {
let phase = new ComplexNumber({ re: 1, im: 0 });
for (let signalId = blockStart; signalId < (blockStart + blockLength / 2); signalId += 1) {
const component = output[signalId + blockLength / 2].multiply(phase);
const upd1 = output[signalId].add(component);
const upd2 = output[signalId].subtract(component);
output[signalId] = upd1;
output[signalId + blockLength / 2] = upd2;
phase = phase.multiply(phaseStep);
}
}
}
if (inverse) {
for (let signalId = 0; signalId < N; signalId += 1) {
output[signalId] /= N;
}
}
return output;
}
| 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) {
if (sequence1.length !== sequence2.length) {
return false;
}
for (let numberIndex = 0; numberIndex < sequence1.length; numberIndex += 1) {
if (Math.abs(sequence1[numberIndex].re - sequence2[numberIndex].re) > delta) {
return false;
}
if (Math.abs(sequence1[numberIndex].im - sequence2[numberIndex].im) > delta) {
return false;
}
}
return true;
}
const delta = 1e-6;
describe('fastFourierTransform', () => {
it('should calculate the radix-2 discrete fourier transform #1', () => {
const input = [new ComplexNumber({ re: 0, im: 0 })];
const expectedOutput = [new ComplexNumber({ re: 0, im: 0 })];
const output = fastFourierTransform(input);
const invertedOutput = fastFourierTransform(output, true);
expect(sequencesApproximatelyEqual(expectedOutput, output, delta)).toBe(true);
expect(sequencesApproximatelyEqual(input, invertedOutput, delta)).toBe(true);
});
it('should calculate the radix-2 discrete fourier transform #2', () => {
const input = [
new ComplexNumber({ re: 1, im: 2 }),
new ComplexNumber({ re: 2, im: 3 }),
new ComplexNumber({ re: 8, im: 4 }),
];
const expectedOutput = [
new ComplexNumber({ re: 11, im: 9 }),
new ComplexNumber({ re: -10, im: 0 }),
new ComplexNumber({ re: 7, im: 3 }),
new ComplexNumber({ re: -4, im: -4 }),
];
const output = fastFourierTransform(input);
const invertedOutput = fastFourierTransform(output, true);
expect(sequencesApproximatelyEqual(expectedOutput, output, delta)).toBe(true);
expect(sequencesApproximatelyEqual(input, invertedOutput, delta)).toBe(true);
});
it('should calculate the radix-2 discrete fourier transform #3', () => {
const input = [
new ComplexNumber({ re: -83656.9359385182, im: 98724.08038374918 }),
new ComplexNumber({ re: -47537.415125808424, im: 88441.58381765135 }),
new ComplexNumber({ re: -24849.657029355192, im: -72621.79007878687 }),
new ComplexNumber({ re: 31451.27290052717, im: -21113.301128347346 }),
new ComplexNumber({ re: 13973.90836288876, im: -73378.36721594246 }),
new ComplexNumber({ re: 14981.520420492234, im: 63279.524958963884 }),
new ComplexNumber({ re: -9892.575367044381, im: -81748.44671677813 }),
new ComplexNumber({ re: -35933.00356823792, im: -46153.47157161784 }),
new ComplexNumber({ re: -22425.008561855735, im: -86284.24507370662 }),
new ComplexNumber({ re: -39327.43830818355, im: 30611.949874562706 }),
];
const expectedOutput = [
new ComplexNumber({ re: -203215.3322151, im: -100242.4827503 }),
new ComplexNumber({ re: 99217.0805705, im: 270646.9331932 }),
new ComplexNumber({ re: -305990.9040412, im: 68224.8435751 }),
new ComplexNumber({ re: -14135.7758282, im: 199223.9878095 }),
new ComplexNumber({ re: -306965.6350922, im: 26030.1025439 }),
new ComplexNumber({ re: -76477.6755206, im: 40781.9078990 }),
new ComplexNumber({ re: -48409.3099088, im: 54674.7959662 }),
new ComplexNumber({ re: -329683.0131713, im: 164287.7995937 }),
new ComplexNumber({ re: -50485.2048527, im: -330375.0546527 }),
new ComplexNumber({ re: 122235.7738708, im: 91091.6398019 }),
new ComplexNumber({ re: 47625.8850387, im: 73497.3981523 }),
new ComplexNumber({ re: -15619.8231136, im: 80804.8685410 }),
new ComplexNumber({ re: 192234.0276101, im: 160833.3072355 }),
new ComplexNumber({ re: -96389.4195635, im: 393408.4543872 }),
new ComplexNumber({ re: -173449.0825417, im: 146875.7724104 }),
new ComplexNumber({ re: -179002.5662573, im: 239821.0124341 }),
];
const output = fastFourierTransform(input);
const invertedOutput = fastFourierTransform(output, true);
expect(sequencesApproximatelyEqual(expectedOutput, output, delta)).toBe(true);
expect(sequencesApproximatelyEqual(input, invertedOutput, delta)).toBe(true);
});
});
| 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 },
],
output: [
{
frequency: 0, amplitude: 0.5, phase: 0, re: 0.5, im: 0,
},
{
frequency: 1, amplitude: 0.5, phase: 0, re: 0.5, im: 0,
},
],
},
{
input: [
{ amplitude: 2 },
{ amplitude: 0 },
],
output: [
{
frequency: 0, amplitude: 1, phase: 0, re: 1, im: 0,
},
{
frequency: 1, amplitude: 1, phase: 0, re: 1, im: 0,
},
],
},
{
input: [
{ amplitude: 1 },
{ amplitude: 0 },
{ amplitude: 0 },
],
output: [
{
frequency: 0, amplitude: 0.33333, phase: 0, re: 0.33333, im: 0,
},
{
frequency: 1, amplitude: 0.33333, phase: 0, re: 0.33333, im: 0,
},
{
frequency: 2, amplitude: 0.33333, phase: 0, re: 0.33333, im: 0,
},
],
},
{
input: [
{ amplitude: 1 },
{ amplitude: 0 },
{ amplitude: 0 },
{ amplitude: 0 },
],
output: [
{
frequency: 0, amplitude: 0.25, phase: 0, re: 0.25, im: 0,
},
{
frequency: 1, amplitude: 0.25, phase: 0, re: 0.25, im: 0,
},
{
frequency: 2, amplitude: 0.25, phase: 0, re: 0.25, im: 0,
},
{
frequency: 3, amplitude: 0.25, phase: 0, re: 0.25, im: 0,
},
],
},
{
input: [
{ amplitude: 0 },
{ amplitude: 1 },
{ amplitude: 0 },
{ amplitude: 0 },
],
output: [
{
frequency: 0, amplitude: 0.25, phase: 0, re: 0.25, im: 0,
},
{
frequency: 1, amplitude: 0.25, phase: -90, re: 0, im: -0.25,
},
{
frequency: 2, amplitude: 0.25, phase: 180, re: -0.25, im: 0,
},
{
frequency: 3, amplitude: 0.25, phase: 90, re: 0, im: 0.25,
},
],
},
{
input: [
{ amplitude: 0 },
{ amplitude: 0 },
{ amplitude: 1 },
{ amplitude: 0 },
],
output: [
{
frequency: 0, amplitude: 0.25, phase: 0, re: 0.25, im: 0,
},
{
frequency: 1, amplitude: 0.25, phase: 180, re: -0.25, im: 0,
},
{
frequency: 2, amplitude: 0.25, phase: 0, re: 0.25, im: 0,
},
{
frequency: 3, amplitude: 0.25, phase: 180, re: -0.25, im: 0,
},
],
},
{
input: [
{ amplitude: 0 },
{ amplitude: 0 },
{ amplitude: 0 },
{ amplitude: 2 },
],
output: [
{
frequency: 0, amplitude: 0.5, phase: 0, re: 0.5, im: 0,
},
{
frequency: 1, amplitude: 0.5, phase: 90, re: 0, im: 0.5,
},
{
frequency: 2, amplitude: 0.5, phase: 180, re: -0.5, im: 0,
},
{
frequency: 3, amplitude: 0.5, phase: -90, re: 0, im: -0.5,
},
],
},
{
input: [
{ amplitude: 0 },
{ amplitude: 1 },
{ amplitude: 0 },
{ amplitude: 2 },
],
output: [
{
frequency: 0, amplitude: 0.75, phase: 0, re: 0.75, im: 0,
},
{
frequency: 1, amplitude: 0.25, phase: 90, re: 0, im: 0.25,
},
{
frequency: 2, amplitude: 0.75, phase: 180, re: -0.75, im: 0,
},
{
frequency: 3, amplitude: 0.25, phase: -90, re: 0, im: -0.25,
},
],
},
{
input: [
{ amplitude: 4 },
{ amplitude: 1 },
{ amplitude: 0 },
{ amplitude: 2 },
],
output: [
{
frequency: 0, amplitude: 1.75, phase: 0, re: 1.75, im: 0,
},
{
frequency: 1, amplitude: 1.03077, phase: 14.03624, re: 0.99999, im: 0.25,
},
{
frequency: 2, amplitude: 0.25, phase: 0, re: 0.25, im: 0,
},
{
frequency: 3, amplitude: 1.03077, phase: -14.03624, re: 1, im: -0.25,
},
],
},
{
input: [
{ amplitude: 4 },
{ amplitude: 1 },
{ amplitude: -3 },
{ amplitude: 2 },
],
output: [
{
frequency: 0, amplitude: 1, phase: 0, re: 1, im: 0,
},
{
frequency: 1, amplitude: 1.76776, phase: 8.13010, re: 1.75, im: 0.25,
},
{
frequency: 2, amplitude: 0.5, phase: 180, re: -0.5, im: 0,
},
{
frequency: 3, amplitude: 1.76776, phase: -8.13010, re: 1.75, im: -0.24999,
},
],
},
{
input: [
{ amplitude: 1 },
{ amplitude: 2 },
{ amplitude: 3 },
{ amplitude: 4 },
],
output: [
{
frequency: 0, amplitude: 2.5, phase: 0, re: 2.5, im: 0,
},
{
frequency: 1, amplitude: 0.70710, phase: 135, re: -0.5, im: 0.49999,
},
{
frequency: 2, amplitude: 0.5, phase: 180, re: -0.5, im: 0,
},
{
frequency: 3, amplitude: 0.70710, phase: -134.99999, re: -0.49999, im: -0.5,
},
],
},
];
export default class FourierTester {
/**
* @param {function} fourierTransform
*/
static testDirectFourierTransform(fourierTransform) {
fourierTestCases.forEach((testCase) => {
const { input, output: expectedOutput } = testCase;
// Try to split input signal into sequence of pure sinusoids.
const formattedInput = input.map((sample) => sample.amplitude);
const currentOutput = fourierTransform(formattedInput);
// Check the signal has been split into proper amount of sub-signals.
expect(currentOutput.length).toBeGreaterThanOrEqual(formattedInput.length);
// Now go through all the signals and check their frequency, amplitude and phase.
expectedOutput.forEach((expectedSignal, frequency) => {
// Get template data we want to test against.
const currentSignal = currentOutput[frequency];
const currentPolarSignal = currentSignal.getPolarForm(false);
// Check all signal parameters.
expect(frequency).toBe(expectedSignal.frequency);
expect(currentSignal.re).toBeCloseTo(expectedSignal.re, 4);
expect(currentSignal.im).toBeCloseTo(expectedSignal.im, 4);
expect(currentPolarSignal.phase).toBeCloseTo(expectedSignal.phase, 4);
expect(currentPolarSignal.radius).toBeCloseTo(expectedSignal.amplitude, 4);
});
});
}
/**
* @param {function} inverseFourierTransform
*/
static testInverseFourierTransform(inverseFourierTransform) {
fourierTestCases.forEach((testCase) => {
const { input: expectedOutput, output: inputFrequencies } = testCase;
// Try to join frequencies into time signal.
const formattedInput = inputFrequencies.map((frequency) => {
return new ComplexNumber({ re: frequency.re, im: frequency.im });
});
const currentOutput = inverseFourierTransform(formattedInput);
// Check the signal has been combined of proper amount of time samples.
expect(currentOutput.length).toBeLessThanOrEqual(formattedInput.length);
// Now go through all the amplitudes and check their values.
expectedOutput.forEach((expectedAmplitudes, timer) => {
// Get template data we want to test against.
const currentAmplitude = currentOutput[timer];
// Check if current amplitude is close enough to the calculated one.
expect(currentAmplitude).toBeCloseTo(expectedAmplitudes.amplitude, 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/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(inverseDiscreteFourierTransform);
});
});
| 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);
expect(factorialRecursive(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/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 factors.
const factors = [];
// Running the loop till sqrt(n) instead of n to optimise time complexity from O(n) to O(sqrt(n)).
for (let factor = 2; factor <= Math.sqrt(nn); factor += 1) {
// Check that factor divides n without a reminder.
while (nn % factor === 0) {
// Overriding the value of n.
nn /= factor;
// Saving the factor.
factors.push(factor);
}
}
// The ultimate reminder should be a last prime factor,
// unless it is not 1 (since 1 is not a prime number).
if (nn !== 1) {
factors.push(nn);
}
return factors;
}
/**
* Hardy-Ramanujan approximation of prime factors count.
*
* @param {number} n
* @returns {number} - approximate number of prime factors.
*/
export function hardyRamanujan(n) {
return Math.log(Math.log(n));
}
| 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, approximateCount) {
return (Math.abs((exactCount - approximateCount) / exactCount) * 100);
}
describe('primeFactors', () => {
it('should find prime factors', () => {
expect(primeFactors(1)).toEqual([]);
expect(primeFactors(2)).toEqual([2]);
expect(primeFactors(3)).toEqual([3]);
expect(primeFactors(4)).toEqual([2, 2]);
expect(primeFactors(14)).toEqual([2, 7]);
expect(primeFactors(40)).toEqual([2, 2, 2, 5]);
expect(primeFactors(54)).toEqual([2, 3, 3, 3]);
expect(primeFactors(100)).toEqual([2, 2, 5, 5]);
expect(primeFactors(156)).toEqual([2, 2, 3, 13]);
expect(primeFactors(273)).toEqual([3, 7, 13]);
expect(primeFactors(300)).toEqual([2, 2, 3, 5, 5]);
expect(primeFactors(980)).toEqual([2, 2, 5, 7, 7]);
expect(primeFactors(1000)).toEqual([2, 2, 2, 5, 5, 5]);
expect(primeFactors(52734)).toEqual([2, 3, 11, 17, 47]);
expect(primeFactors(343434)).toEqual([2, 3, 7, 13, 17, 37]);
expect(primeFactors(456745)).toEqual([5, 167, 547]);
expect(primeFactors(510510)).toEqual([2, 3, 5, 7, 11, 13, 17]);
expect(primeFactors(8735463)).toEqual([3, 3, 11, 88237]);
expect(primeFactors(873452453)).toEqual([149, 1637, 3581]);
});
it('should give approximate prime factors count using Hardy-Ramanujan theorem', () => {
expect(hardyRamanujan(2)).toBeCloseTo(-0.366, 2);
expect(hardyRamanujan(4)).toBeCloseTo(0.326, 2);
expect(hardyRamanujan(40)).toBeCloseTo(1.305, 2);
expect(hardyRamanujan(156)).toBeCloseTo(1.6193, 2);
expect(hardyRamanujan(980)).toBeCloseTo(1.929, 2);
expect(hardyRamanujan(52734)).toBeCloseTo(2.386, 2);
expect(hardyRamanujan(343434)).toBeCloseTo(2.545, 2);
expect(hardyRamanujan(456745)).toBeCloseTo(2.567, 2);
expect(hardyRamanujan(510510)).toBeCloseTo(2.575, 2);
expect(hardyRamanujan(8735463)).toBeCloseTo(2.771, 2);
expect(hardyRamanujan(873452453)).toBeCloseTo(3.024, 2);
});
it('should give correct deviation between exact and approx counts', () => {
expect(approximationError(primeFactors(2).length, hardyRamanujan(2)))
.toBeCloseTo(136.651, 2);
expect(approximationError(primeFactors(4).length, hardyRamanujan(2)))
.toBeCloseTo(118.325, 2);
expect(approximationError(primeFactors(40).length, hardyRamanujan(2)))
.toBeCloseTo(109.162, 2);
expect(approximationError(primeFactors(156).length, hardyRamanujan(2)))
.toBeCloseTo(109.162, 2);
expect(approximationError(primeFactors(980).length, hardyRamanujan(2)))
.toBeCloseTo(107.330, 2);
expect(approximationError(primeFactors(52734).length, hardyRamanujan(52734)))
.toBeCloseTo(52.274, 2);
expect(approximationError(primeFactors(343434).length, hardyRamanujan(343434)))
.toBeCloseTo(57.578, 2);
expect(approximationError(primeFactors(456745).length, hardyRamanujan(456745)))
.toBeCloseTo(14.420, 2);
expect(approximationError(primeFactors(510510).length, hardyRamanujan(510510)))
.toBeCloseTo(63.201, 2);
expect(approximationError(primeFactors(8735463).length, hardyRamanujan(8735463)))
.toBeCloseTo(30.712, 2);
expect(approximationError(primeFactors(873452453).length, hardyRamanujan(873452453)))
.toBeCloseTo(0.823, 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/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.isArray(dimension)) {
shapes.push(dimension.length);
dimension = (dimension.length && [...dimension][0]) || null;
}
return shapes;
};
/**
* Checks if matrix has a correct type.
*
* @param {Matrix} m
* @throws {Error}
*/
const validateType = (m) => {
if (
!m
|| !Array.isArray(m)
|| !Array.isArray(m[0])
) {
throw new Error('Invalid matrix format');
}
};
/**
* Checks if matrix is two dimensional.
*
* @param {Matrix} m
* @throws {Error}
*/
const validate2D = (m) => {
validateType(m);
const aShape = shape(m);
if (aShape.length !== 2) {
throw new Error('Matrix is not of 2D shape');
}
};
/**
* Validates that matrices are of the same shape.
*
* @param {Matrix} a
* @param {Matrix} b
* @trows {Error}
*/
export const validateSameShape = (a, b) => {
validateType(a);
validateType(b);
const aShape = shape(a);
const bShape = shape(b);
if (aShape.length !== bShape.length) {
throw new Error('Matrices have different dimensions');
}
while (aShape.length && bShape.length) {
if (aShape.pop() !== bShape.pop()) {
throw new Error('Matrices have different shapes');
}
}
};
/**
* Generates the matrix of specific shape with specific values.
*
* @param {Shape} mShape - the shape of the matrix to generate
* @param {function({CellIndex}): Cell} fill - cell values of a generated matrix.
* @returns {Matrix}
*/
export const generate = (mShape, fill) => {
/**
* Generates the matrix recursively.
*
* @param {Shape} recShape - the shape of the matrix to generate
* @param {CellIndices} recIndices
* @returns {Matrix}
*/
const generateRecursively = (recShape, recIndices) => {
if (recShape.length === 1) {
return Array(recShape[0])
.fill(null)
.map((cellValue, cellIndex) => fill([...recIndices, cellIndex]));
}
const m = [];
for (let i = 0; i < recShape[0]; i += 1) {
m.push(generateRecursively(recShape.slice(1), [...recIndices, i]));
}
return m;
};
return generateRecursively(mShape, []);
};
/**
* Generates the matrix of zeros of specified shape.
*
* @param {Shape} mShape - shape of the matrix
* @returns {Matrix}
*/
export const zeros = (mShape) => {
return generate(mShape, () => 0);
};
/**
* @param {Matrix} a
* @param {Matrix} b
* @return Matrix
* @throws {Error}
*/
export const dot = (a, b) => {
// Validate inputs.
validate2D(a);
validate2D(b);
// Check dimensions.
const aShape = shape(a);
const bShape = shape(b);
if (aShape[1] !== bShape[0]) {
throw new Error('Matrices have incompatible shape for multiplication');
}
// Perform matrix multiplication.
const outputShape = [aShape[0], bShape[1]];
const c = zeros(outputShape);
for (let bCol = 0; bCol < b[0].length; bCol += 1) {
for (let aRow = 0; aRow < a.length; aRow += 1) {
let cellSum = 0;
for (let aCol = 0; aCol < a[aRow].length; aCol += 1) {
cellSum += a[aRow][aCol] * b[aCol][bCol];
}
c[aRow][bCol] = cellSum;
}
}
return c;
};
/**
* Transposes the matrix.
*
* @param {Matrix} m
* @returns Matrix
* @throws {Error}
*/
export const t = (m) => {
validate2D(m);
const mShape = shape(m);
const transposed = zeros([mShape[1], mShape[0]]);
for (let row = 0; row < m.length; row += 1) {
for (let col = 0; col < m[0].length; col += 1) {
transposed[col][row] = m[row][col];
}
}
return transposed;
};
/**
* Traverses the matrix.
*
* @param {Matrix} m
* @param {function(indices: CellIndices, c: Cell)} visit
*/
export const walk = (m, visit) => {
/**
* Traverses the matrix recursively.
*
* @param {Matrix} recM
* @param {CellIndices} cellIndices
* @return {Matrix}
*/
const recWalk = (recM, cellIndices) => {
const recMShape = shape(recM);
if (recMShape.length === 1) {
for (let i = 0; i < recM.length; i += 1) {
visit([...cellIndices, i], recM[i]);
}
}
for (let i = 0; i < recM.length; i += 1) {
recWalk(recM[i], [...cellIndices, i]);
}
};
recWalk(m, []);
};
/**
* Gets the matrix cell value at specific index.
*
* @param {Matrix} m - Matrix that contains the cell that needs to be updated
* @param {CellIndices} cellIndices - Array of cell indices
* @return {Cell}
*/
export const getCellAtIndex = (m, cellIndices) => {
// We start from the row at specific index.
let cell = m[cellIndices[0]];
// Going deeper into the next dimensions but not to the last one to preserve
// the pointer to the last dimension array.
for (let dimIdx = 1; dimIdx < cellIndices.length - 1; dimIdx += 1) {
cell = cell[cellIndices[dimIdx]];
}
// At this moment the cell variable points to the array at the last needed dimension.
return cell[cellIndices[cellIndices.length - 1]];
};
/**
* Update the matrix cell at specific index.
*
* @param {Matrix} m - Matrix that contains the cell that needs to be updated
* @param {CellIndices} cellIndices - Array of cell indices
* @param {Cell} cellValue - New cell value
*/
export const updateCellAtIndex = (m, cellIndices, cellValue) => {
// We start from the row at specific index.
let cell = m[cellIndices[0]];
// Going deeper into the next dimensions but not to the last one to preserve
// the pointer to the last dimension array.
for (let dimIdx = 1; dimIdx < cellIndices.length - 1; dimIdx += 1) {
cell = cell[cellIndices[dimIdx]];
}
// At this moment the cell variable points to the array at the last needed dimension.
cell[cellIndices[cellIndices.length - 1]] = cellValue;
};
/**
* Adds two matrices element-wise.
*
* @param {Matrix} a
* @param {Matrix} b
* @return {Matrix}
*/
export const add = (a, b) => {
validateSameShape(a, b);
const result = zeros(shape(a));
walk(a, (cellIndices, cellValue) => {
updateCellAtIndex(result, cellIndices, cellValue);
});
walk(b, (cellIndices, cellValue) => {
const currentCellValue = getCellAtIndex(result, cellIndices);
updateCellAtIndex(result, cellIndices, currentCellValue + cellValue);
});
return result;
};
/**
* Multiplies two matrices element-wise.
*
* @param {Matrix} a
* @param {Matrix} b
* @return {Matrix}
*/
export const mul = (a, b) => {
validateSameShape(a, b);
const result = zeros(shape(a));
walk(a, (cellIndices, cellValue) => {
updateCellAtIndex(result, cellIndices, cellValue);
});
walk(b, (cellIndices, cellValue) => {
const currentCellValue = getCellAtIndex(result, cellIndices);
updateCellAtIndex(result, cellIndices, currentCellValue * cellValue);
});
return result;
};
/**
* Subtract two matrices element-wise.
*
* @param {Matrix} a
* @param {Matrix} b
* @return {Matrix}
*/
export const sub = (a, b) => {
validateSameShape(a, b);
const result = zeros(shape(a));
walk(a, (cellIndices, cellValue) => {
updateCellAtIndex(result, cellIndices, cellValue);
});
walk(b, (cellIndices, cellValue) => {
const currentCellValue = getCellAtIndex(result, cellIndices);
updateCellAtIndex(result, cellIndices, currentCellValue - cellValue);
});
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/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');
expect(
() => mtrx.dot([[[0]]], [[1]]),
).toThrowError('Matrix is not of 2D shape');
expect(
() => mtrx.dot([[0]], [[1], [2]]),
).toThrowError('Matrices have incompatible shape for multiplication');
});
it('should calculate matrices dimensions', () => {
expect(mtrx.shape([])).toEqual([0]);
expect(mtrx.shape([
[],
])).toEqual([1, 0]);
expect(mtrx.shape([
[0],
])).toEqual([1, 1]);
expect(mtrx.shape([
[0, 0],
])).toEqual([1, 2]);
expect(mtrx.shape([
[0, 0],
[0, 0],
])).toEqual([2, 2]);
expect(mtrx.shape([
[0, 0, 0],
[0, 0, 0],
])).toEqual([2, 3]);
expect(mtrx.shape([
[0, 0],
[0, 0],
[0, 0],
])).toEqual([3, 2]);
expect(mtrx.shape([
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
])).toEqual([3, 3]);
expect(mtrx.shape([
[0],
[0],
[0],
])).toEqual([3, 1]);
expect(mtrx.shape([
[[0], [0], [0]],
[[0], [0], [0]],
[[0], [0], [0]],
])).toEqual([3, 3, 1]);
expect(mtrx.shape([
[[0, 0, 0], [0, 0, 0], [0, 0, 0]],
[[0, 0, 0], [0, 0, 0], [0, 0, 0]],
[[0, 0, 0], [0, 0, 0], [0, 0, 0]],
])).toEqual([3, 3, 3]);
});
it('should generate the matrix of zeros', () => {
expect(mtrx.zeros([1, 0])).toEqual([
[],
]);
expect(mtrx.zeros([1, 1])).toEqual([
[0],
]);
expect(mtrx.zeros([1, 3])).toEqual([
[0, 0, 0],
]);
expect(mtrx.zeros([3, 3])).toEqual([
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
]);
expect(mtrx.zeros([3, 3, 1])).toEqual([
[[0], [0], [0]],
[[0], [0], [0]],
[[0], [0], [0]],
]);
});
it('should generate the matrix with custom values', () => {
expect(mtrx.generate([1, 0], () => 1)).toEqual([
[],
]);
expect(mtrx.generate([1, 1], () => 1)).toEqual([
[1],
]);
expect(mtrx.generate([1, 3], () => 1)).toEqual([
[1, 1, 1],
]);
expect(mtrx.generate([3, 3], () => 1)).toEqual([
[1, 1, 1],
[1, 1, 1],
[1, 1, 1],
]);
expect(mtrx.generate([3, 3, 1], () => 1)).toEqual([
[[1], [1], [1]],
[[1], [1], [1]],
[[1], [1], [1]],
]);
});
it('should generate a custom matrix based on specific cell indices', () => {
const indicesCallback = jest.fn((indices) => {
return indices[0] * 10 + indices[1];
});
const m = mtrx.generate([3, 3], indicesCallback);
expect(indicesCallback).toHaveBeenCalledTimes(3 * 3);
expect(indicesCallback.mock.calls[0][0]).toEqual([0, 0]);
expect(indicesCallback.mock.calls[1][0]).toEqual([0, 1]);
expect(indicesCallback.mock.calls[2][0]).toEqual([0, 2]);
expect(indicesCallback.mock.calls[3][0]).toEqual([1, 0]);
expect(indicesCallback.mock.calls[4][0]).toEqual([1, 1]);
expect(indicesCallback.mock.calls[5][0]).toEqual([1, 2]);
expect(indicesCallback.mock.calls[6][0]).toEqual([2, 0]);
expect(indicesCallback.mock.calls[7][0]).toEqual([2, 1]);
expect(indicesCallback.mock.calls[8][0]).toEqual([2, 2]);
expect(m).toEqual([
[0, 1, 2],
[10, 11, 12],
[20, 21, 22],
]);
});
it('should multiply two matrices', () => {
let c;
c = mtrx.dot(
[
[1, 2],
[3, 4],
],
[
[5, 6],
[7, 8],
],
);
expect(mtrx.shape(c)).toEqual([2, 2]);
expect(c).toEqual([
[19, 22],
[43, 50],
]);
c = mtrx.dot(
[
[1, 2],
[3, 4],
],
[
[5],
[6],
],
);
expect(mtrx.shape(c)).toEqual([2, 1]);
expect(c).toEqual([
[17],
[39],
]);
c = mtrx.dot(
[
[1, 2, 3],
[4, 5, 6],
],
[
[7, 8],
[9, 10],
[11, 12],
],
);
expect(mtrx.shape(c)).toEqual([2, 2]);
expect(c).toEqual([
[58, 64],
[139, 154],
]);
c = mtrx.dot(
[
[3, 4, 2],
],
[
[13, 9, 7, 5],
[8, 7, 4, 6],
[6, 4, 0, 3],
],
);
expect(mtrx.shape(c)).toEqual([1, 4]);
expect(c).toEqual([
[83, 63, 37, 45],
]);
});
it('should transpose matrices', () => {
expect(mtrx.t([[1, 2, 3]])).toEqual([
[1],
[2],
[3],
]);
expect(mtrx.t([
[1],
[2],
[3],
])).toEqual([
[1, 2, 3],
]);
expect(mtrx.t([
[1, 2, 3],
[4, 5, 6],
])).toEqual([
[1, 4],
[2, 5],
[3, 6],
]);
expect(mtrx.t([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
])).toEqual([
[1, 4, 7],
[2, 5, 8],
[3, 6, 9],
]);
});
it('should throw when trying to transpose non 2D matrix', () => {
expect(() => {
mtrx.t([[[1]]]);
}).toThrowError('Matrix is not of 2D shape');
});
it('should add two matrices', () => {
expect(mtrx.add([[1]], [[2]])).toEqual([[3]]);
expect(mtrx.add(
[[1, 2, 3]],
[[4, 5, 6]],
))
.toEqual(
[[5, 7, 9]],
);
expect(mtrx.add(
[[1], [2], [3]],
[[4], [5], [6]],
))
.toEqual(
[[5], [7], [9]],
);
expect(mtrx.add(
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
],
[
[10, 11, 12],
[13, 14, 15],
[16, 17, 18],
],
))
.toEqual(
[
[11, 13, 15],
[17, 19, 21],
[23, 25, 27],
],
);
expect(mtrx.add(
[
[[1], [2], [3]],
[[4], [5], [6]],
[[7], [8], [9]],
],
[
[[10], [11], [12]],
[[13], [14], [15]],
[[16], [17], [18]],
],
))
.toEqual(
[
[[11], [13], [15]],
[[17], [19], [21]],
[[23], [25], [27]],
],
);
});
it('should throw when trying to add matrices of different shape', () => {
expect(() => mtrx.add([[0]], [[[0]]])).toThrowError(
'Matrices have different dimensions',
);
expect(() => mtrx.add([[0]], [[0, 0]])).toThrowError(
'Matrices have different shapes',
);
});
it('should do element wise multiplication two matrices', () => {
expect(mtrx.mul([[2]], [[3]])).toEqual([[6]]);
expect(mtrx.mul(
[[1, 2, 3]],
[[4, 5, 6]],
))
.toEqual(
[[4, 10, 18]],
);
expect(mtrx.mul(
[[1], [2], [3]],
[[4], [5], [6]],
))
.toEqual(
[[4], [10], [18]],
);
expect(mtrx.mul(
[
[1, 2],
[3, 4],
],
[
[5, 6],
[7, 8],
],
))
.toEqual(
[
[5, 12],
[21, 32],
],
);
expect(mtrx.mul(
[
[[1], [2]],
[[3], [4]],
],
[
[[5], [6]],
[[7], [8]],
],
))
.toEqual(
[
[[5], [12]],
[[21], [32]],
],
);
});
it('should throw when trying to multiply matrices element-wise of different shape', () => {
expect(() => mtrx.mul([[0]], [[[0]]])).toThrowError(
'Matrices have different dimensions',
);
expect(() => mtrx.mul([[0]], [[0, 0]])).toThrowError(
'Matrices have different shapes',
);
});
it('should do element wise subtraction two matrices', () => {
expect(mtrx.sub([[3]], [[2]])).toEqual([[1]]);
expect(mtrx.sub(
[[10, 12, 14]],
[[4, 5, 6]],
))
.toEqual(
[[6, 7, 8]],
);
expect(mtrx.sub(
[[[10], [12], [14]]],
[[[4], [5], [6]]],
))
.toEqual(
[[[6], [7], [8]]],
);
expect(mtrx.sub(
[
[10, 20],
[30, 40],
],
[
[5, 6],
[7, 8],
],
))
.toEqual(
[
[5, 14],
[23, 32],
],
);
expect(mtrx.sub(
[
[[10], [20]],
[[30], [40]],
],
[
[[5], [6]],
[[7], [8]],
],
))
.toEqual(
[
[[5], [14]],
[[23], [32]],
],
);
});
it('should throw when trying to subtract matrices element-wise of different shape', () => {
expect(() => mtrx.sub([[0]], [[[0]]])).toThrowError(
'Matrices have different dimensions',
);
expect(() => mtrx.sub([[0]], [[0, 0]])).toThrowError(
'Matrices have different shapes',
);
});
});
| 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.
currentLine[numIndex] = (currentLine[numIndex - 1] * (lineNumber - numIndex + 1)) / numIndex;
}
return currentLine;
}
| 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.
const currentLine = [];
// We'll calculate current line based on previous one.
const previousLine = pascalTriangleRecursive(lineNumber - 1);
// Let's go through all elements of current line except the first and
// last one (since they were and will be filled with 1's) and calculate
// current coefficient based on previous line.
for (let numIndex = 0; numIndex < currentLineSize; numIndex += 1) {
const leftCoefficient = (numIndex - 1) >= 0 ? previousLine[numIndex - 1] : 0;
const rightCoefficient = numIndex < previousLineSize ? previousLine[numIndex] : 0;
currentLine[numIndex] = leftCoefficient + rightCoefficient;
}
return currentLine;
}
| 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(pascalTriangleRecursive(2)).toEqual([1, 2, 1]);
expect(pascalTriangleRecursive(3)).toEqual([1, 3, 3, 1]);
expect(pascalTriangleRecursive(4)).toEqual([1, 4, 6, 4, 1]);
expect(pascalTriangleRecursive(5)).toEqual([1, 5, 10, 10, 5, 1]);
expect(pascalTriangleRecursive(6)).toEqual([1, 6, 15, 20, 15, 6, 1]);
expect(pascalTriangleRecursive(7)).toEqual([1, 7, 21, 35, 35, 21, 7, 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/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]);
expect(pascalTriangle(3)).toEqual([1, 3, 3, 1]);
expect(pascalTriangle(4)).toEqual([1, 4, 6, 4, 1]);
expect(pascalTriangle(5)).toEqual([1, 5, 10, 10, 5, 1]);
expect(pascalTriangle(6)).toEqual([1, 6, 15, 20, 15, 6, 1]);
expect(pascalTriangle(7)).toEqual([1, 7, 21, 35, 35, 21, 7, 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/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 {ComplexNumber|number} addend
* @return {ComplexNumber}
*/
add(addend) {
// Make sure we're dealing with complex number.
const complexAddend = this.toComplexNumber(addend);
return new ComplexNumber({
re: this.re + complexAddend.re,
im: this.im + complexAddend.im,
});
}
/**
* @param {ComplexNumber|number} subtrahend
* @return {ComplexNumber}
*/
subtract(subtrahend) {
// Make sure we're dealing with complex number.
const complexSubtrahend = this.toComplexNumber(subtrahend);
return new ComplexNumber({
re: this.re - complexSubtrahend.re,
im: this.im - complexSubtrahend.im,
});
}
/**
* @param {ComplexNumber|number} multiplicand
* @return {ComplexNumber}
*/
multiply(multiplicand) {
// Make sure we're dealing with complex number.
const complexMultiplicand = this.toComplexNumber(multiplicand);
return new ComplexNumber({
re: this.re * complexMultiplicand.re - this.im * complexMultiplicand.im,
im: this.re * complexMultiplicand.im + this.im * complexMultiplicand.re,
});
}
/**
* @param {ComplexNumber|number} divider
* @return {ComplexNumber}
*/
divide(divider) {
// Make sure we're dealing with complex number.
const complexDivider = this.toComplexNumber(divider);
// Get divider conjugate.
const dividerConjugate = this.conjugate(complexDivider);
// Multiply dividend by divider's conjugate.
const finalDivident = this.multiply(dividerConjugate);
// Calculating final divider using formula (a + bi)(a − bi) = a^2 + b^2
const finalDivider = (complexDivider.re ** 2) + (complexDivider.im ** 2);
return new ComplexNumber({
re: finalDivident.re / finalDivider,
im: finalDivident.im / finalDivider,
});
}
/**
* @param {ComplexNumber|number} number
*/
conjugate(number) {
// Make sure we're dealing with complex number.
const complexNumber = this.toComplexNumber(number);
return new ComplexNumber({
re: complexNumber.re,
im: -1 * complexNumber.im,
});
}
/**
* @return {number}
*/
getRadius() {
return Math.sqrt((this.re ** 2) + (this.im ** 2));
}
/**
* @param {boolean} [inRadians]
* @return {number}
*/
getPhase(inRadians = true) {
let phase = Math.atan(Math.abs(this.im) / Math.abs(this.re));
if (this.re < 0 && this.im > 0) {
phase = Math.PI - phase;
} else if (this.re < 0 && this.im < 0) {
phase = -(Math.PI - phase);
} else if (this.re > 0 && this.im < 0) {
phase = -phase;
} else if (this.re === 0 && this.im > 0) {
phase = Math.PI / 2;
} else if (this.re === 0 && this.im < 0) {
phase = -Math.PI / 2;
} else if (this.re < 0 && this.im === 0) {
phase = Math.PI;
} else if (this.re > 0 && this.im === 0) {
phase = 0;
} else if (this.re === 0 && this.im === 0) {
// More correctly would be to set 'indeterminate'.
// But just for simplicity reasons let's set zero.
phase = 0;
}
if (!inRadians) {
phase = radianToDegree(phase);
}
return phase;
}
/**
* @param {boolean} [inRadians]
* @return {{radius: number, phase: number}}
*/
getPolarForm(inRadians = true) {
return {
radius: this.getRadius(),
phase: this.getPhase(inRadians),
};
}
/**
* Convert real numbers to complex number.
* In case if complex number is provided then lefts it as is.
*
* @param {ComplexNumber|number} number
* @return {ComplexNumber}
*/
toComplexNumber(number) {
if (number instanceof ComplexNumber) {
return number;
}
return new ComplexNumber({ re: 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/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 defaultComplexNumber = new ComplexNumber();
expect(defaultComplexNumber.re).toBe(0);
expect(defaultComplexNumber.im).toBe(0);
});
it('should add complex numbers', () => {
const complexNumber1 = new ComplexNumber({ re: 1, im: 2 });
const complexNumber2 = new ComplexNumber({ re: 3, im: 8 });
const complexNumber3 = complexNumber1.add(complexNumber2);
const complexNumber4 = complexNumber2.add(complexNumber1);
expect(complexNumber3.re).toBe(1 + 3);
expect(complexNumber3.im).toBe(2 + 8);
expect(complexNumber4.re).toBe(1 + 3);
expect(complexNumber4.im).toBe(2 + 8);
});
it('should add complex and natural numbers', () => {
const complexNumber = new ComplexNumber({ re: 1, im: 2 });
const realNumber = new ComplexNumber({ re: 3 });
const complexNumber3 = complexNumber.add(realNumber);
const complexNumber4 = realNumber.add(complexNumber);
const complexNumber5 = complexNumber.add(3);
expect(complexNumber3.re).toBe(1 + 3);
expect(complexNumber3.im).toBe(2);
expect(complexNumber4.re).toBe(1 + 3);
expect(complexNumber4.im).toBe(2);
expect(complexNumber5.re).toBe(1 + 3);
expect(complexNumber5.im).toBe(2);
});
it('should subtract complex numbers', () => {
const complexNumber1 = new ComplexNumber({ re: 1, im: 2 });
const complexNumber2 = new ComplexNumber({ re: 3, im: 8 });
const complexNumber3 = complexNumber1.subtract(complexNumber2);
const complexNumber4 = complexNumber2.subtract(complexNumber1);
expect(complexNumber3.re).toBe(1 - 3);
expect(complexNumber3.im).toBe(2 - 8);
expect(complexNumber4.re).toBe(3 - 1);
expect(complexNumber4.im).toBe(8 - 2);
});
it('should subtract complex and natural numbers', () => {
const complexNumber = new ComplexNumber({ re: 1, im: 2 });
const realNumber = new ComplexNumber({ re: 3 });
const complexNumber3 = complexNumber.subtract(realNumber);
const complexNumber4 = realNumber.subtract(complexNumber);
const complexNumber5 = complexNumber.subtract(3);
expect(complexNumber3.re).toBe(1 - 3);
expect(complexNumber3.im).toBe(2);
expect(complexNumber4.re).toBe(3 - 1);
expect(complexNumber4.im).toBe(-2);
expect(complexNumber5.re).toBe(1 - 3);
expect(complexNumber5.im).toBe(2);
});
it('should multiply complex numbers', () => {
const complexNumber1 = new ComplexNumber({ re: 3, im: 2 });
const complexNumber2 = new ComplexNumber({ re: 1, im: 7 });
const complexNumber3 = complexNumber1.multiply(complexNumber2);
const complexNumber4 = complexNumber2.multiply(complexNumber1);
const complexNumber5 = complexNumber1.multiply(5);
expect(complexNumber3.re).toBe(-11);
expect(complexNumber3.im).toBe(23);
expect(complexNumber4.re).toBe(-11);
expect(complexNumber4.im).toBe(23);
expect(complexNumber5.re).toBe(15);
expect(complexNumber5.im).toBe(10);
});
it('should multiply complex numbers by themselves', () => {
const complexNumber = new ComplexNumber({ re: 1, im: 1 });
const result = complexNumber.multiply(complexNumber);
expect(result.re).toBe(0);
expect(result.im).toBe(2);
});
it('should calculate i in power of two', () => {
const complexNumber = new ComplexNumber({ re: 0, im: 1 });
const result = complexNumber.multiply(complexNumber);
expect(result.re).toBe(-1);
expect(result.im).toBe(0);
});
it('should divide complex numbers', () => {
const complexNumber1 = new ComplexNumber({ re: 2, im: 3 });
const complexNumber2 = new ComplexNumber({ re: 4, im: -5 });
const complexNumber3 = complexNumber1.divide(complexNumber2);
const complexNumber4 = complexNumber1.divide(2);
expect(complexNumber3.re).toBe(-7 / 41);
expect(complexNumber3.im).toBe(22 / 41);
expect(complexNumber4.re).toBe(1);
expect(complexNumber4.im).toBe(1.5);
});
it('should return complex number in polar form', () => {
const complexNumber1 = new ComplexNumber({ re: 3, im: 3 });
expect(complexNumber1.getPolarForm().radius).toBe(Math.sqrt((3 ** 2) + (3 ** 2)));
expect(complexNumber1.getPolarForm().phase).toBe(Math.PI / 4);
expect(complexNumber1.getPolarForm(false).phase).toBe(45);
const complexNumber2 = new ComplexNumber({ re: -3, im: 3 });
expect(complexNumber2.getPolarForm().radius).toBe(Math.sqrt((3 ** 2) + (3 ** 2)));
expect(complexNumber2.getPolarForm().phase).toBe(3 * (Math.PI / 4));
expect(complexNumber2.getPolarForm(false).phase).toBe(135);
const complexNumber3 = new ComplexNumber({ re: -3, im: -3 });
expect(complexNumber3.getPolarForm().radius).toBe(Math.sqrt((3 ** 2) + (3 ** 2)));
expect(complexNumber3.getPolarForm().phase).toBe(-3 * (Math.PI / 4));
expect(complexNumber3.getPolarForm(false).phase).toBe(-135);
const complexNumber4 = new ComplexNumber({ re: 3, im: -3 });
expect(complexNumber4.getPolarForm().radius).toBe(Math.sqrt((3 ** 2) + (3 ** 2)));
expect(complexNumber4.getPolarForm().phase).toBe(-1 * (Math.PI / 4));
expect(complexNumber4.getPolarForm(false).phase).toBe(-45);
const complexNumber5 = new ComplexNumber({ re: 5, im: 7 });
expect(complexNumber5.getPolarForm().radius).toBeCloseTo(8.60);
expect(complexNumber5.getPolarForm().phase).toBeCloseTo(0.95);
expect(complexNumber5.getPolarForm(false).phase).toBeCloseTo(54.46);
const complexNumber6 = new ComplexNumber({ re: 0, im: 0.25 });
expect(complexNumber6.getPolarForm().radius).toBeCloseTo(0.25);
expect(complexNumber6.getPolarForm().phase).toBeCloseTo(1.57);
expect(complexNumber6.getPolarForm(false).phase).toBeCloseTo(90);
const complexNumber7 = new ComplexNumber({ re: 0, im: -0.25 });
expect(complexNumber7.getPolarForm().radius).toBeCloseTo(0.25);
expect(complexNumber7.getPolarForm().phase).toBeCloseTo(-1.57);
expect(complexNumber7.getPolarForm(false).phase).toBeCloseTo(-90);
const complexNumber8 = new ComplexNumber();
expect(complexNumber8.getPolarForm().radius).toBeCloseTo(0);
expect(complexNumber8.getPolarForm().phase).toBeCloseTo(0);
expect(complexNumber8.getPolarForm(false).phase).toBeCloseTo(0);
const complexNumber9 = new ComplexNumber({ re: -0.25, im: 0 });
expect(complexNumber9.getPolarForm().radius).toBeCloseTo(0.25);
expect(complexNumber9.getPolarForm().phase).toBeCloseTo(Math.PI);
expect(complexNumber9.getPolarForm(false).phase).toBeCloseTo(180);
const complexNumber10 = new ComplexNumber({ re: 0.25, im: 0 });
expect(complexNumber10.getPolarForm().radius).toBeCloseTo(0.25);
expect(complexNumber10.getPolarForm().phase).toBeCloseTo(0);
expect(complexNumber10.getPolarForm(false).phase).toBeCloseTo(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/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, '1010111001100110'],
[0, '0000000000000000'],
[5.9604644775390625e-8, '0000000000000001'],
[0.000004529, '0000000001001100'],
[0.0999755859375, '0010111001100110'],
[0.199951171875, '0011001001100110'],
[0.300048828125, '0011010011001101'],
[1, '0011110000000000'],
[1.5, '0011111000000000'],
[1.75, '0011111100000000'],
[1.875, '0011111110000000'],
[65504, '0111101111111111'],
];
/**
* @type {TestCase[]}
*/
export const testCases32Bits = [
[-3.40282346638528859812e+38, '11111111011111111111111111111111'],
[-10345.5595703125, '11000110001000011010011000111101'],
[-27.15625, '11000001110110010100000000000000'],
[-1, '10111111100000000000000000000000'],
[-0.1, '10111101110011001100110011001101'],
[0, '00000000000000000000000000000000'],
[1.40129846432481707092e-45, '00000000000000000000000000000001'],
[0.000004560, '00110110100110010000001000011010'],
[0.1, '00111101110011001100110011001101'],
[0.2, '00111110010011001100110011001101'],
[0.3, '00111110100110011001100110011010'],
[1, '00111111100000000000000000000000'],
[1.5, '00111111110000000000000000000000'],
[1.75, '00111111111000000000000000000000'],
[1.875, '00111111111100000000000000000000'],
[3.40282346638528859812e+38, '01111111011111111111111111111111'],
];
/**
* @type {TestCase[]}
*/
export const testCases64Bits = [
[-1.79769313486231570815e+308, '1111111111101111111111111111111111111111111111111111111111111111'],
[-10345.5595703125, '1100000011000100001101001100011110100000000000000000000000000000'],
[-27.15625, '1100000000111011001010000000000000000000000000000000000000000000'],
[-1, '1011111111110000000000000000000000000000000000000000000000000000'],
[-0.1, '1011111110111001100110011001100110011001100110011001100110011010'],
[0, '0000000000000000000000000000000000000000000000000000000000000000'],
[4.94065645841246544177e-324, '0000000000000000000000000000000000000000000000000000000000000001'],
[0.000004560, '0011111011010011001000000100001101000001011100110011110011100100'],
[0.1, '0011111110111001100110011001100110011001100110011001100110011010'],
[0.2, '0011111111001001100110011001100110011001100110011001100110011010'],
[0.3, '0011111111010011001100110011001100110011001100110011001100110011'],
[1, '0011111111110000000000000000000000000000000000000000000000000000'],
[1.5, '0011111111111000000000000000000000000000000000000000000000000000'],
[1.75, '0011111111111100000000000000000000000000000000000000000000000000'],
[1.875, '0011111111111110000000000000000000000000000000000000000000000000'],
[1.79769313486231570815e+308, '0111111111101111111111111111111111111111111111111111111111111111'],
];
| 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
* }} PrecisionConfigs
*/
/**
* ┌───────────────── sign bit
* │ ┌───────────── exponent bits
* │ │ ┌───── fraction bits
* │ │ │
* X XXXXX XXXXXXXXXX
*
* @type {PrecisionConfigs}
*/
const precisionConfigs = {
// @see: https://en.wikipedia.org/wiki/Half-precision_floating-point_format
half: {
signBitsCount: 1,
exponentBitsCount: 5,
fractionBitsCount: 10,
},
// @see: https://en.wikipedia.org/wiki/Single-precision_floating-point_format
single: {
signBitsCount: 1,
exponentBitsCount: 8,
fractionBitsCount: 23,
},
// @see: https://en.wikipedia.org/wiki/Double-precision_floating-point_format
double: {
signBitsCount: 1,
exponentBitsCount: 11,
fractionBitsCount: 52,
},
};
/**
* Converts the binary representation of the floating point number to decimal float number.
*
* @param {Bits} bits - sequence of bits that represents the floating point number.
* @param {PrecisionConfig} precisionConfig - half/single/double precision config.
* @return {number} - floating point number decoded from its binary representation.
*/
function bitsToFloat(bits, precisionConfig) {
const { signBitsCount, exponentBitsCount } = precisionConfig;
// Figuring out the sign.
const sign = (-1) ** bits[0]; // -1^1 = -1, -1^0 = 1
// Calculating the exponent value.
const exponentBias = 2 ** (exponentBitsCount - 1) - 1;
const exponentBits = bits.slice(signBitsCount, signBitsCount + exponentBitsCount);
const exponentUnbiased = exponentBits.reduce(
(exponentSoFar, currentBit, bitIndex) => {
const bitPowerOfTwo = 2 ** (exponentBitsCount - bitIndex - 1);
return exponentSoFar + currentBit * bitPowerOfTwo;
},
0,
);
const exponent = exponentUnbiased - exponentBias;
// Calculating the fraction value.
const fractionBits = bits.slice(signBitsCount + exponentBitsCount);
const fraction = fractionBits.reduce(
(fractionSoFar, currentBit, bitIndex) => {
const bitPowerOfTwo = 2 ** -(bitIndex + 1);
return fractionSoFar + currentBit * bitPowerOfTwo;
},
0,
);
// Putting all parts together to calculate the final number.
return sign * (2 ** exponent) * (1 + fraction);
}
/**
* Converts the 16-bit binary representation of the floating point number to decimal float number.
*
* @param {Bits} bits - sequence of bits that represents the floating point number.
* @return {number} - floating point number decoded from its binary representation.
*/
export function bitsToFloat16(bits) {
return bitsToFloat(bits, precisionConfigs.half);
}
/**
* Converts the 32-bit binary representation of the floating point number to decimal float number.
*
* @param {Bits} bits - sequence of bits that represents the floating point number.
* @return {number} - floating point number decoded from its binary representation.
*/
export function bitsToFloat32(bits) {
return bitsToFloat(bits, precisionConfigs.single);
}
/**
* Converts the 64-bit binary representation of the floating point number to decimal float number.
*
* @param {Bits} bits - sequence of bits that represents the floating point number.
* @return {number} - floating point number decoded from its binary representation.
*/
export function bitsToFloat64(bits) {
return bitsToFloat(bits, precisionConfigs.double);
}
| 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 IEEE 754 binary representation.
* @see: https://en.wikipedia.org/wiki/IEEE_754
*
* @param {number} floatNumber - float number in decimal format.
* @param {number} byteLength - number of bytes to use to store the float number.
* @return {string} - binary string representation of the float number.
*/
function floatAsBinaryString(floatNumber, byteLength) {
let numberAsBinaryString = '';
const arrayBuffer = new ArrayBuffer(byteLength);
const dataView = new DataView(arrayBuffer);
const byteOffset = 0;
const littleEndian = false;
if (byteLength === singlePrecisionBytesLength) {
dataView.setFloat32(byteOffset, floatNumber, littleEndian);
} else {
dataView.setFloat64(byteOffset, floatNumber, littleEndian);
}
for (let byteIndex = 0; byteIndex < byteLength; byteIndex += 1) {
let bits = dataView.getUint8(byteIndex).toString(2);
if (bits.length < bitsInByte) {
bits = new Array(bitsInByte - bits.length).fill('0').join('') + bits;
}
numberAsBinaryString += bits;
}
return numberAsBinaryString;
}
/**
* Converts the float number into its IEEE 754 64-bits binary representation.
*
* @param {number} floatNumber - float number in decimal format.
* @return {string} - 64 bits binary string representation of the float number.
*/
export function floatAs64BinaryString(floatNumber) {
return floatAsBinaryString(floatNumber, doublePrecisionBytesLength);
}
/**
* Converts the float number into its IEEE 754 32-bits binary representation.
*
* @param {number} floatNumber - float number in decimal format.
* @return {string} - 32 bits binary string representation of the float number.
*/
export function floatAs32BinaryString(floatNumber) {
return floatAsBinaryString(floatNumber, singlePrecisionBytesLength);
}
| 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; testCaseIndex < testCases16Bits.length; testCaseIndex += 1) {
const [decimal, binary] = testCases16Bits[testCaseIndex];
const bits = binary.split('').map((bitString) => parseInt(bitString, 10));
expect(bitsToFloat16(bits)).toBeCloseTo(decimal, 4);
}
});
});
describe('bitsToFloat32', () => {
it('should convert floating point binary bits to floating point decimal number', () => {
for (let testCaseIndex = 0; testCaseIndex < testCases32Bits.length; testCaseIndex += 1) {
const [decimal, binary] = testCases32Bits[testCaseIndex];
const bits = binary.split('').map((bitString) => parseInt(bitString, 10));
expect(bitsToFloat32(bits)).toBeCloseTo(decimal, 7);
}
});
});
describe('bitsToFloat64', () => {
it('should convert floating point binary bits to floating point decimal number', () => {
for (let testCaseIndex = 0; testCaseIndex < testCases64Bits.length; testCaseIndex += 1) {
const [decimal, binary] = testCases64Bits[testCaseIndex];
const bits = binary.split('').map((bitString) => parseInt(bitString, 10));
expect(bitsToFloat64(bits)).toBeCloseTo(decimal, 14);
}
});
});
| 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 < testCases32Bits.length; testCaseIndex += 1) {
const [decimal, binary] = testCases32Bits[testCaseIndex];
expect(floatAs32BinaryString(decimal)).toBe(binary);
}
});
});
describe('floatAs64Binary', () => {
it('should create a binary representation of the floating numbers', () => {
for (let testCaseIndex = 0; testCaseIndex < testCases64Bits.length; testCaseIndex += 1) {
const [decimal, binary] = testCases64Bits[testCaseIndex];
expect(floatAs64BinaryString(decimal)).toBe(binary);
}
});
});
| 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 coefficients.reverse().reduce(
(accumulator, currentCoefficient, index) => {
return accumulator + currentCoefficient * (xVal ** index);
},
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/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(
(accumulator, currentCoefficient) => {
return accumulator * xVal + currentCoefficient;
},
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/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);
expect(hornerMethod([2, 4, 2, 5], 0.75)).toBe(9.59375);
expect(hornerMethod([1, 1, 1, 1, 1], 1.75)).toBe(20.55078125);
expect(hornerMethod([15, 3.5, 0, 2, 1.42, 0.41], 0.315)).toBe(1.136730065140625);
expect(hornerMethod([0, 0, 2.77, 1.42, 0.41], 1.35)).toBe(7.375325000000001);
expect(hornerMethod([0, 0, 2.77, 1.42, 2.3311], 1.35)).toBe(9.296425000000001);
expect(hornerMethod([2, 0, 0, 5.757, 5.31412, 12.3213], 3.141)).toBe(697.2731167035034);
});
it('should evaluate the same polynomial value as classical approach', () => {
expect(hornerMethod([8], 0.1)).toBe(classicPolynome([8], 0.1));
expect(hornerMethod([2, 4, 2, 5], 0.555)).toBe(classicPolynome([2, 4, 2, 5], 0.555));
expect(hornerMethod([2, 4, 2, 5], 0.75)).toBe(classicPolynome([2, 4, 2, 5], 0.75));
});
});
| 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, 2, 5], 0.75)).toBe(9.59375);
expect(classicPolynome([1, 1, 1, 1, 1], 1.75)).toBe(20.55078125);
expect(classicPolynome([15, 3.5, 0, 2, 1.42, 0.41], 0.315)).toBe(1.1367300651406251);
expect(classicPolynome([0, 0, 2.77, 1.42, 0.41], 1.35)).toBe(7.375325000000001);
expect(classicPolynome([0, 0, 2.77, 1.42, 2.3311], 1.35)).toBe(9.296425000000001);
expect(classicPolynome([2, 0, 0, 5.757, 5.31412, 12.3213], 3.141)).toBe(697.2731167035034);
});
});
| 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) {
// All numbers from 2 to 3 are prime.
return true;
}
// If the number is not divided by 2 then we may eliminate all further even dividers.
if (number % 2 === 0) {
return false;
}
// If there is no dividers up to square root of n then there is no higher dividers as well.
const dividerLimit = Math.sqrt(number);
for (let divider = 3; divider <= dividerLimit; divider += 2) {
if (number % divider === 0) {
return false;
}
}
return true;
}
| 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)).toBe(true);
expect(testFunction(191)).toBe(true);
expect(testFunction(191)).toBe(true);
expect(testFunction(199)).toBe(true);
expect(testFunction(-1)).toBe(false);
expect(testFunction(0)).toBe(false);
expect(testFunction(4)).toBe(false);
expect(testFunction(6)).toBe(false);
expect(testFunction(12)).toBe(false);
expect(testFunction(14)).toBe(false);
expect(testFunction(25)).toBe(false);
expect(testFunction(192)).toBe(false);
expect(testFunction(200)).toBe(false);
expect(testFunction(400)).toBe(false);
// It should also deal with floats.
expect(testFunction(0.5)).toBe(false);
expect(testFunction(1.3)).toBe(false);
expect(testFunction(10.5)).toBe(false);
}
describe('trialDivision', () => {
it('should detect prime numbers', () => {
primalityTest(trialDivision);
});
});
| 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.validateSameShape(a, b);
let squaresTotal = 0;
mtrx.walk(a, (indices, aCellValue) => {
const bCellValue = mtrx.getCellAtIndex(b, indices);
squaresTotal += (aCellValue - bCellValue) ** 2;
});
return Number(Math.sqrt(squaresTotal).toFixed(2));
};
export default euclideanDistance;
| 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]])).toEqual(5.39);
expect(euclideanDistance([[5], [8]], [[7], [3]])).toEqual(5.39);
expect(euclideanDistance([[8, 2, 6]], [[3, 5, 7]])).toEqual(5.92);
expect(euclideanDistance([[8], [2], [6]], [[3], [5], [7]])).toEqual(5.92);
expect(euclideanDistance([[[8]], [[2]], [[6]]], [[[3]], [[5]], [[7]]])).toEqual(5.92);
});
it('should throw an error in case if two matrices are of different shapes', () => {
expect(() => euclideanDistance([[1]], [[[2]]])).toThrowError(
'Matrices have different dimensions',
);
expect(() => euclideanDistance([[1]], [[2, 3]])).toThrowError(
'Matrices have different shapes',
);
});
});
| 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);
expect(degreeToRadian(270)).toBe((3 * Math.PI) / 2);
expect(degreeToRadian(360)).toBe(2 * 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);
expect(radianToDegree((3 * Math.PI) / 2)).toBe(270);
expect(radianToDegree(2 * Math.PI)).toBe(360);
});
});
| 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 (dividedNumber !== 1) {
if (dividedNumber % 2 !== 0) {
// For every case when remainder isn't zero we can say that this number
// couldn't be a result of power of two.
return false;
}
dividedNumber /= 2;
}
return true;
}
| 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 there is always exactly 1 bit set. The only exception is with a signed integer.
* e.g. An 8-bit signed integer with a value of -128 looks like:
* 10000000
*
* So after checking that the number is greater than zero, we can use a clever little bit
* hack to test that one and only one bit is set.
*/
return (number & (number - 1)) === 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/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);
expect(isPowerOfTwo(3)).toBe(false);
expect(isPowerOfTwo(4)).toBe(true);
expect(isPowerOfTwo(5)).toBe(false);
expect(isPowerOfTwo(6)).toBe(false);
expect(isPowerOfTwo(7)).toBe(false);
expect(isPowerOfTwo(8)).toBe(true);
expect(isPowerOfTwo(10)).toBe(false);
expect(isPowerOfTwo(12)).toBe(false);
expect(isPowerOfTwo(16)).toBe(true);
expect(isPowerOfTwo(31)).toBe(false);
expect(isPowerOfTwo(64)).toBe(true);
expect(isPowerOfTwo(1024)).toBe(true);
expect(isPowerOfTwo(1023)).toBe(false);
});
});
| 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);
expect(isPowerOfTwoBitwise(2)).toBe(true);
expect(isPowerOfTwoBitwise(3)).toBe(false);
expect(isPowerOfTwoBitwise(4)).toBe(true);
expect(isPowerOfTwoBitwise(5)).toBe(false);
expect(isPowerOfTwoBitwise(6)).toBe(false);
expect(isPowerOfTwoBitwise(7)).toBe(false);
expect(isPowerOfTwoBitwise(8)).toBe(true);
expect(isPowerOfTwoBitwise(10)).toBe(false);
expect(isPowerOfTwoBitwise(12)).toBe(false);
expect(isPowerOfTwoBitwise(16)).toBe(true);
expect(isPowerOfTwoBitwise(31)).toBe(false);
expect(isPowerOfTwoBitwise(64)).toBe(true);
expect(isPowerOfTwoBitwise(1024)).toBe(true);
expect(isPowerOfTwoBitwise(1023)).toBe(false);
});
});
| 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] === true) {
primes.push(number);
/*
* Optimisation.
* Start marking multiples of `p` from `p * p`, and not from `2 * p`.
* The reason why this works is because, at that point, smaller multiples
* of `p` will have already been marked `false`.
*
* Warning: When working with really big numbers, the following line may cause overflow
* In that case, it can be changed to:
* let nextNumber = 2 * number;
*/
let nextNumber = number * number;
while (nextNumber <= maxNumber) {
isPrime[nextNumber] = false;
nextNumber += number;
}
}
}
return primes;
}
| 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([
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,
]);
});
});
| 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) {
return sideLength;
}
const halfSide = sideLength / 2;
// Liu Hui used the Gou Gu (Pythagorean theorem) theorem repetitively.
const perpendicular = Math.sqrt((circleRadius ** 2) - (halfSide ** 2));
const excessRadius = circleRadius - perpendicular;
const splitSideLength = Math.sqrt((excessRadius ** 2) + (halfSide ** 2));
return getNGonSideLength(splitSideLength, splitCounter - 1);
}
/**
* @param {number} splitCount
* @return {number}
*/
function getNGonSideCount(splitCount) {
// Liu Hui began with an inscribed hexagon (6-gon).
const hexagonSidesCount = 6;
// On every split iteration we make N-gons: 6-gon, 12-gon, 24-gon, 48-gon and so on.
return hexagonSidesCount * (splitCount ? 2 ** splitCount : 1);
}
/**
* Calculate the π value using Liu Hui's π algorithm
*
* @param {number} splitCount - number of times we're going to split 6-gon.
* On each split we will receive 12-gon, 24-gon and so on.
* @return {number}
*/
export default function liuHui(splitCount = 1) {
const nGonSideLength = getNGonSideLength(circleRadius, splitCount - 1);
const nGonSideCount = getNGonSideCount(splitCount - 1);
const nGonPerimeter = nGonSideLength * nGonSideCount;
const approximateCircleArea = (nGonPerimeter / 2) * circleRadius;
// Return approximate value of pi.
return approximateCircleArea / (circleRadius ** 2);
}
| javascript | MIT | 1503325329d63f7fead7f455fda5a4338b4e93bb | 2026-01-04T14:56:49.187241Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.