Skip to content

Commit e24706e

Browse files
committed
2 parents 63e451e + 9f83862 commit e24706e

38 files changed

+1765
-111
lines changed

README.md

Lines changed: 24 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,17 @@
66
This repository contains JavaScript based examples of many
77
popular algorithms and data structures.
88

9-
Each algorithm and data structure have its own separate README
10-
with related explanations and links for further reading and YouTube
11-
videos.
9+
Each algorithm and data structure has its own separate README
10+
with related explanations and links for further reading (including ones
11+
to YouTube videos).
1212

1313
_Read this in other languages:_
1414
[简体中文](https://github.com/trekhleb/javascript-algorithms/blob/master/README.zh-CN.md),
1515
[繁體中文](https://github.com/trekhleb/javascript-algorithms/blob/master/README.zh-TW.md)
1616

1717
## Data Structures
1818

19-
Data structure is a particular way of organizing and storing data in a computer so that it can
19+
A data structure is a particular way of organizing and storing data in a computer so that it can
2020
be accessed and modified efficiently. More precisely, a data structure is a collection of data
2121
values, the relationships among them, and the functions or operations that can be applied to
2222
the data.
@@ -31,17 +31,15 @@ the data.
3131
* [Tree](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/tree)
3232
* [Binary Search Tree](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/tree/binary-search-tree)
3333
* [AVL Tree](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/tree/avl-tree)
34-
* Red-Black Tree
35-
* Suffix Tree
36-
* Segment Tree or Interval Tree
37-
* Binary Indexed Tree or Fenwick Tree
34+
* [Red-Black Tree](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/tree/red-black-tree)
35+
* [Segment Tree](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/tree/segment-tree) - with min/max/sum range queries examples
3836
* [Graph](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/graph) (both directed and undirected)
3937
* [Disjoint Set](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/disjoint-set)
4038

4139
## Algorithms
4240

43-
Algorithm is an unambiguous specification of how to solve a class of problems. Algorithm is
44-
a set of rules that precisely defines a sequence of operations.
41+
An algorithm is an unambiguous specification of how to solve a class of problems. It is
42+
a set of rules that precisely define a sequence of operations.
4543

4644
### Algorithms by Topic
4745

@@ -52,9 +50,11 @@ a set of rules that precisely defines a sequence of operations.
5250
* [Euclidean Algorithm](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/math/euclidean-algorithm) - calculate the Greatest Common Divisor (GCD)
5351
* [Least Common Multiple](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/math/least-common-multiple) (LCM)
5452
* [Integer Partition](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/math/integer-partition)
53+
* [Sieve of Eratosthenes](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/math/sieve-of-eratosthenes) - finding all prime numbers up to any given limit
54+
* [Is Power of Two](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/math/is-power-of-two) - check if the number is power of two (naive and bitwise algorithms)
5555
* **Sets**
5656
* [Cartesian Product](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/sets/cartesian-product) - product of multiple sets
57-
* [Power Set](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/sets/power-set) - all subsets of the set
57+
* [Power Set](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/sets/power-set) - all subsets of a set
5858
* [Permutations](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/sets/permutations) (with and without repetitions)
5959
* [Combinations](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/sets/combinations) (with and without repetitions)
6060
* [Fisher–Yates Shuffle](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/sets/fisher-yates) - random permutation of a finite sequence
@@ -63,13 +63,13 @@ a set of rules that precisely defines a sequence of operations.
6363
* [Shortest Common Supersequence](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/sets/shortest-common-supersequence) (SCS)
6464
* [Knapsack Problem](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/sets/knapsack-problem) - "0/1" and "Unbound" ones
6565
* [Maximum Subarray](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/sets/maximum-subarray) - "Brute Force" and "Dynamic Programming" (Kadane's) versions
66-
* **String**
66+
* **Strings**
6767
* [Levenshtein Distance](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/string/levenshtein-distance) - minimum edit distance between two sequences
6868
* [Hamming Distance](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/string/hamming-distance) - number of positions at which the symbols are different
6969
* [Knuth–Morris–Pratt Algorithm](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/string/knuth-morris-pratt) - substring search
7070
* [Rabin Karp Algorithm](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/string/rabin-karp) - substring search
7171
* [Longest Common Substring](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/string/longest-common-substring)
72-
* **Search**
72+
* **Searches**
7373
* [Linear Search](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/search/linear-search)
7474
* [Binary Search](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/search/binary-search)
7575
* **Sorting**
@@ -82,10 +82,10 @@ a set of rules that precisely defines a sequence of operations.
8282
* [Shellsort](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/sorting/shell-sort)
8383
* [Counting Sort](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/sorting/counting-sort)
8484
* [Radix Sort](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/sorting/radix-sort)
85-
* **Tree**
85+
* **Trees**
8686
* [Depth-First Search](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/tree/depth-first-search) (DFS)
8787
* [Breadth-First Search](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/tree/breadth-first-search) (BFS)
88-
* **Graph**
88+
* **Graphs**
8989
* [Depth-First Search](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/graph/depth-first-search) (DFS)
9090
* [Breadth-First Search](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/graph/breadth-first-search) (BFS)
9191
* [Dijkstra Algorithm](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/graph/dijkstra) - finding shortest path to all graph vertices
@@ -129,7 +129,7 @@ algorithm is an abstraction higher than a computer program.
129129
* [Quicksort](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/sorting/quick-sort)
130130
* [Tree Depth-First Search](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/tree/depth-first-search) (DFS)
131131
* [Graph Depth-First Search](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/graph/depth-first-search) (DFS)
132-
* **Dynamic Programming** - build up to a solution using previously found sub-solutions
132+
* **Dynamic Programming** - build up a solution using previously found sub-solutions
133133
* [Fibonacci Number](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/math/fibonacci)
134134
* [Levenshtein Distance](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/string/levenshtein-distance) - minimum edit distance between two sequences
135135
* [Longest Common Subsequence](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/sets/longest-common-subsequnce) (LCS)
@@ -140,13 +140,17 @@ algorithm is an abstraction higher than a computer program.
140140
* [Integer Partition](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/math/integer-partition)
141141
* [Maximum Subarray](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/sets/maximum-subarray)
142142
* [Bellman-Ford Algorithm](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/graph/bellman-ford) - finding shortest path to all graph vertices
143-
* **Backtracking** - similarly to brute force try to generate all possible solutions but each time you generate a solution test
144-
if it satisfies all conditions, and only then continue generating subsequent solutions. Otherwise backtrack and go on a
145-
different path of finding solution
143+
* **Backtracking** - similarly to brute force, try to generate all possible solutions, but each time you generate next solution you test
144+
if it satisfies all conditions, and only then continue generating subsequent solutions. Otherwise, backtrack, and go on a
145+
different path of finding a solution. Normally the DFS traversal of state-space is being used.
146146
* [Hamiltonian Cycle](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/graph/hamiltonian-cycle) - Visit every vertex exactly once
147147
* [N-Queens Problem](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/uncategorized/n-queens)
148148
* [Knight's Tour](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/uncategorized/knight-tour)
149-
* **Branch & Bound**
149+
* **Branch & Bound** - remember the lowest-cost solution found at each stage of the backtracking
150+
search, and use the cost of the lowest-cost solution found so far as a lower bound on the cost of
151+
a least-cost solution to the problem, in order to discard partial solutions with costs larger than the
152+
lowest-cost solution found so far. Normally BFS traversal in combination with DFS traversal of state-space
153+
tree is being used.
150154

151155
## How to use this repository
152156

README.zh-CN.md

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,7 @@ _Read this in other languages:_
2525
* [](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/tree)
2626
* [二分查找](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/tree/binary-search-tree)
2727
* [AVL 树](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/tree/avl-tree)
28-
* 红黑树
29-
* 后缀树
30-
* 线段树 或 间隔树
31-
* 二叉索引树
28+
* [红黑树](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/tree/red-black-tree)
3229
* [](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/graph) (有向图与无向图)
3330
* [并查集](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/disjoint-set)
3431

README.zh-TW.md

Lines changed: 13 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -14,22 +14,19 @@ _Read this in other languages:_
1414

1515
資料結構是一個電腦用來組織和排序資料的特定方式,透過這樣的方式資料可以有效率地被讀取以及修改。更精確地說,一個資料結構是一個資料值的集合、彼此間的關係,函數或者運作可以應用於資料上。
1616

17-
* [Linked List 鏈結串列](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/linked-list)
18-
* [Queue 貯列](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/queue)
19-
* [Stack 堆疊](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/stack)
20-
* [Hash Table 雜湊表](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/hash-table)
21-
* [Heap 堆](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/heap)
22-
* [Priority Queue 優先貯列](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/priority-queue)
23-
* [Trie 字典樹](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/trie)
24-
* [Tree 樹](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/tree)
25-
* [Binary Search Tree 二元搜尋樹](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/tree/binary-search-tree)
26-
* [AVL Tree AVL樹](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/tree/avl-tree)
27-
* 紅黑樹
28-
* 後綴樹
29-
* 線段樹 或 間隔樹
30-
* 樹狀數組或二叉索引樹
31-
* [Graph 圖](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/graph) (有向跟無向皆包含)
32-
* [Disjoint Set 互斥集](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/disjoint-set)
17+
* [鏈結串列](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/linked-list)
18+
* [貯列](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/queue)
19+
* [堆疊](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/stack)
20+
* [雜湊表](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/hash-table)
21+
* [](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/heap)
22+
* [優先貯列](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/priority-queue)
23+
* [字典樹](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/trie)
24+
* [](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/tree)
25+
* [二元搜尋樹](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/tree/binary-search-tree)
26+
* [AVL樹](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/tree/avl-tree)
27+
* [紅黑樹](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/tree/red-black-tree)
28+
* [](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/graph) (有向跟無向皆包含)
29+
* [互斥集](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/disjoint-set)
3330

3431
## 演算法
3532

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "javascript-algorithms-and-data-structures",
3-
"version": "0.0.3",
3+
"version": "0.0.4",
44
"description": "Algorithms and data-structures implemented on JavaScript",
55
"main": "index.js",
66
"scripts": {

src/algorithms/math/factorial/factorial.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
export default function factorial(number) {
66
let result = 1;
77

8-
for (let i = 1; i <= number; i += 1) {
8+
for (let i = 2; i <= number; i += 1) {
99
result *= i;
1010
}
1111

src/algorithms/math/fibonacci/__test__/fibonacci.test.js

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,13 @@ import fibonacci from '../fibonacci';
22

33
describe('fibonacci', () => {
44
it('should calculate fibonacci correctly', () => {
5-
expect(fibonacci(1)).toBe(1);
6-
expect(fibonacci(2)).toBe(1);
7-
expect(fibonacci(3)).toBe(2);
8-
expect(fibonacci(4)).toBe(3);
9-
expect(fibonacci(5)).toBe(5);
10-
expect(fibonacci(6)).toBe(8);
11-
expect(fibonacci(7)).toBe(13);
12-
expect(fibonacci(8)).toBe(21);
13-
expect(fibonacci(20)).toBe(6765);
5+
expect(fibonacci(1)).toEqual([1]);
6+
expect(fibonacci(2)).toEqual([1, 1]);
7+
expect(fibonacci(3)).toEqual([1, 1, 2]);
8+
expect(fibonacci(4)).toEqual([1, 1, 2, 3]);
9+
expect(fibonacci(5)).toEqual([1, 1, 2, 3, 5]);
10+
expect(fibonacci(6)).toEqual([1, 1, 2, 3, 5, 8]);
11+
expect(fibonacci(7)).toEqual([1, 1, 2, 3, 5, 8, 13]);
12+
expect(fibonacci(8)).toEqual([1, 1, 2, 3, 5, 8, 13, 21]);
1413
});
1514
});
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import fibonacciNth from '../fibonacciNth';
2+
3+
describe('fibonacciNth', () => {
4+
it('should calculate fibonacci correctly', () => {
5+
expect(fibonacciNth(1)).toBe(1);
6+
expect(fibonacciNth(2)).toBe(1);
7+
expect(fibonacciNth(3)).toBe(2);
8+
expect(fibonacciNth(4)).toBe(3);
9+
expect(fibonacciNth(5)).toBe(5);
10+
expect(fibonacciNth(6)).toBe(8);
11+
expect(fibonacciNth(7)).toBe(13);
12+
expect(fibonacciNth(8)).toBe(21);
13+
expect(fibonacciNth(20)).toBe(6765);
14+
});
15+
});
Lines changed: 21 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,29 @@
1-
// Calculate fibonacci number at specific position using Dynamic Programming approach.
2-
export default function fibonacci(numberPosition) {
3-
if (numberPosition === 1) {
4-
return 1;
5-
}
1+
/**
2+
* Return a fibonacci sequence as an array.
3+
*
4+
* @param n
5+
* @return {number[]}
6+
*/
7+
export default function fibonacci(n) {
8+
const fibSequence = [1];
9+
10+
let currentValue = 1;
11+
let previousValue = 0;
612

7-
let iterationsCounter = numberPosition - 1;
13+
if (n === 1) {
14+
return fibSequence;
15+
}
816

9-
// Calculated fibonacci number.
10-
let fib = null;
11-
// Previous fibonacci number.
12-
let fibPrev = 1;
13-
// Before previous fibonacci number.
14-
let fibPrevPrev = 0;
17+
let iterationsCounter = n - 1;
1518

1619
while (iterationsCounter) {
17-
// Calculate current value using two previous ones.
18-
fib = fibPrev + fibPrevPrev;
19-
// Shift previous values.
20-
fibPrevPrev = fibPrev;
21-
fibPrev = fib;
20+
currentValue += previousValue;
21+
previousValue = (currentValue - previousValue);
22+
23+
fibSequence.push(currentValue);
24+
2225
iterationsCounter -= 1;
2326
}
2427

25-
return fib;
28+
return fibSequence;
2629
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* Calculate fibonacci number at specific position using Dynamic Programming approach.
3+
*
4+
* @param n
5+
* @return {number}
6+
*/
7+
export default function fibonacciNth(n) {
8+
let currentValue = 1;
9+
let previousValue = 0;
10+
11+
if (n === 1) {
12+
return 1;
13+
}
14+
15+
let iterationsCounter = n - 1;
16+
17+
while (iterationsCounter) {
18+
currentValue += previousValue;
19+
previousValue = (currentValue - previousValue);
20+
21+
iterationsCounter -= 1;
22+
}
23+
24+
return currentValue;
25+
}
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# Is a power of two
2+
3+
Given a positive integer, write a function to find if it is
4+
a power of two or not.
5+
6+
**Naive solution**
7+
8+
In naive solution we just keep dividing the number by two
9+
unless the number becomes `1` and every time we do so we
10+
check that remainder after division is always `0`. Otherwise
11+
the number can't be a power of two.
12+
13+
**Bitwise solution**
14+
15+
Powers of two in binary form always have just one bit.
16+
The only exception is with a signed integer (e.g. an 8-bit
17+
signed integer with a value of -128 looks like: `10000000`)
18+
19+
```
20+
1: 0001
21+
2: 0010
22+
4: 0100
23+
8: 1000
24+
```
25+
26+
So after checking that the number is greater than zero,
27+
we can use a bitwise hack to test that one and only one
28+
bit is set.
29+
30+
```
31+
number & (number - 1)
32+
```
33+
34+
For example for number `8` that operations will look like:
35+
36+
```
37+
1000
38+
- 0001
39+
----
40+
0111
41+
42+
1000
43+
& 0111
44+
----
45+
0000
46+
```
47+
48+
## References
49+
50+
- [GeeksForGeeks](https://www.geeksforgeeks.org/program-to-find-whether-a-no-is-power-of-two/)
51+
- [Bitwise Solution on Stanford](http://www.graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2)
52+
- [Binary number subtraction on YouTube](https://www.youtube.com/watch?v=S9LJknZTyos&t=0s&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8&index=66)
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import isPowerOfTwo from '../isPowerOfTwo';
2+
3+
describe('isPowerOfTwo', () => {
4+
it('should throw an exception when trying to apply function to negative number', () => {
5+
const isNegativePowerOfTwo = () => {
6+
isPowerOfTwo(-1);
7+
};
8+
9+
expect(isNegativePowerOfTwo).toThrowError();
10+
});
11+
12+
it('should check if the number is made by multiplying twos', () => {
13+
expect(isPowerOfTwo(0)).toBeFalsy();
14+
expect(isPowerOfTwo(1)).toBeFalsy();
15+
expect(isPowerOfTwo(2)).toBeTruthy();
16+
expect(isPowerOfTwo(3)).toBeFalsy();
17+
expect(isPowerOfTwo(4)).toBeTruthy();
18+
expect(isPowerOfTwo(5)).toBeFalsy();
19+
expect(isPowerOfTwo(6)).toBeFalsy();
20+
expect(isPowerOfTwo(7)).toBeFalsy();
21+
expect(isPowerOfTwo(8)).toBeTruthy();
22+
expect(isPowerOfTwo(10)).toBeFalsy();
23+
expect(isPowerOfTwo(12)).toBeFalsy();
24+
expect(isPowerOfTwo(16)).toBeTruthy();
25+
expect(isPowerOfTwo(31)).toBeFalsy();
26+
expect(isPowerOfTwo(64)).toBeTruthy();
27+
expect(isPowerOfTwo(1024)).toBeTruthy();
28+
expect(isPowerOfTwo(1023)).toBeFalsy();
29+
});
30+
});

0 commit comments

Comments
 (0)