Skip to content

Commit 4b08560

Browse files
committed
2 parents 8035c13 + 51cf96c commit 4b08560

File tree

7 files changed

+252
-16
lines changed

7 files changed

+252
-16
lines changed

DIRECTORY.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242
* [StackES6](https://github.com/TheAlgorithms/Javascript/blob/master/Data-Structures/Stack/StackES6.js)
4343
* Tree
4444
* [BinarySearchTree](https://github.com/TheAlgorithms/Javascript/blob/master/Data-Structures/Tree/BinarySearchTree.js)
45+
* [Trie](https://github.com/TheAlgorithms/Javascript/blob/master/Data-Structures/Tree/Trie.js)
4546

4647
## Dynamic-Programming
4748
* [CoinChange](https://github.com/TheAlgorithms/Javascript/blob/master/Dynamic-Programming/CoinChange.js)
@@ -73,18 +74,22 @@
7374
## Maths
7475
* [Abs](https://github.com/TheAlgorithms/Javascript/blob/master/Maths/Abs.js)
7576
* [AverageMean](https://github.com/TheAlgorithms/Javascript/blob/master/Maths/AverageMean.js)
77+
* [digitSum](https://github.com/TheAlgorithms/Javascript/blob/master/Maths/digitSum.js)
7678
* [Factorial](https://github.com/TheAlgorithms/Javascript/blob/master/Maths/Factorial.js)
7779
* [Fibonacci](https://github.com/TheAlgorithms/Javascript/blob/master/Maths/Fibonacci.js)
7880
* [FindHcf](https://github.com/TheAlgorithms/Javascript/blob/master/Maths/FindHcf.js)
7981
* [FindLcm](https://github.com/TheAlgorithms/Javascript/blob/master/Maths/FindLcm.js)
8082
* [GridGet](https://github.com/TheAlgorithms/Javascript/blob/master/Maths/GridGet.js)
83+
* [ModularBinaryExponentiationRecursive](https://github.com/TheAlgorithms/Javascript/blob/master/Maths/ModularBinaryExponentiationRecursive.js)
8184
* [Palindrome](https://github.com/TheAlgorithms/Javascript/blob/master/Maths/Palindrome.js)
8285
* [PascalTriangle](https://github.com/TheAlgorithms/Javascript/blob/master/Maths/PascalTriangle.js)
8386
* [PiApproximationMonteCarlo](https://github.com/TheAlgorithms/Javascript/blob/master/Maths/PiApproximationMonteCarlo.js)
87+
* [PrimeCheck](https://github.com/TheAlgorithms/Javascript/blob/master/Maths/PrimeCheck.js)
8488
* [SieveOfEratosthenes](https://github.com/TheAlgorithms/Javascript/blob/master/Maths/SieveOfEratosthenes.js)
8589

8690
## Recursive
8791
* [EucledianGCD](https://github.com/TheAlgorithms/Javascript/blob/master/Recursive/EucledianGCD.js)
92+
* [TowerOfHanoi](https://github.com/TheAlgorithms/Javascript/blob/master/Recursive/TowerOfHanoi.js)
8893

8994
## Search
9095
* [BinarySearch](https://github.com/TheAlgorithms/Javascript/blob/master/Search/BinarySearch.js)

Data-Structures/Tree/Trie.js

Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
var TrieNode = function TrieNode (key, parent) {
2+
this.key = key
3+
this.count = 0
4+
this.children = Object.create(null)
5+
if (parent === undefined) {
6+
this.parent = null
7+
} else {
8+
this.parent = parent
9+
}
10+
}
11+
12+
function Trie () {
13+
// create only root with null key and parent
14+
this.root = new TrieNode(null, null)
15+
}
16+
17+
// Recursively finds the occurence of all words in a given node
18+
Trie.findAllWords = function (root, word, output) {
19+
if (root === null) return
20+
if (root.count > 0) {
21+
if (typeof output === 'object') { output.push({ word: word, count: root.count }) }
22+
}
23+
var key
24+
for (key in root.children) {
25+
word += key
26+
this.findAllWords(root.children[key], word, output)
27+
word = word.slice(0, -1)
28+
}
29+
}
30+
31+
Trie.prototype.insert = function (word) {
32+
if (typeof word !== 'string') return
33+
if (word === '') {
34+
this.root.count += 1
35+
return
36+
}
37+
var node = this.root
38+
var len = word.length
39+
var i
40+
for (i = 0; i < len; i++) {
41+
if (node.children[word.charAt(i)] === undefined) { node.children[word.charAt(i)] = new TrieNode(word.charAt(i), node) }
42+
node = node.children[word.charAt(i)]
43+
}
44+
node.count += 1
45+
}
46+
47+
Trie.prototype.findPrefix = function (word) {
48+
if (typeof word !== 'string') return null
49+
var node = this.root
50+
var len = word.length
51+
var i
52+
// After end of this loop node will be at desired prefix
53+
for (i = 0; i < len; i++) {
54+
if (node.children[word.charAt(i)] === undefined) return null // No such prefix exists
55+
node = node.children[word.charAt(i)]
56+
}
57+
return node
58+
}
59+
60+
Trie.prototype.remove = function (word, count) {
61+
if (typeof word !== 'string') return
62+
if (typeof count !== 'number') count = 1
63+
else if (count <= 0) return
64+
65+
// for empty string just delete count of root
66+
if (word === '') {
67+
if (this.root.count >= count) this.root.count -= count
68+
else this.root.count = 0
69+
return
70+
}
71+
72+
var child = this.root
73+
var len = word.length
74+
var i, key
75+
// child: node which is to be deleted
76+
for (i = 0; i < len; i++) {
77+
key = word.charAt(i)
78+
if (child.children[key] === undefined) return
79+
child = child.children[key]
80+
}
81+
82+
// Delete no of occurences specified
83+
if (child.count >= count) child.count -= count
84+
else child.count = 0
85+
86+
// If some occurences are left we dont delete it or else
87+
// if the object forms some other objects prefix we dont delete it
88+
// For checking an empty object
89+
// https://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object
90+
if (child.count <= 0 && (Object.keys(child.children).length && child.childre.constructor === Object)) {
91+
child.parent.children[child.key] = undefined
92+
}
93+
}
94+
95+
Trie.prototype.findAllWords = function (prefix) {
96+
var output = []
97+
// find the node with provided prefix
98+
var node = this.findPrefix(prefix)
99+
// No such prefix exists
100+
if (node === null) return output
101+
Trie.findAllWords(node, prefix, output)
102+
return output
103+
}
104+
105+
Trie.prototype.contains = function (word) {
106+
// find the node with given prefix
107+
var node = this.findPrefix(word)
108+
// No such word exists
109+
if (node === null || node.count === 0) return false
110+
return true
111+
}
112+
113+
Trie.prototype.findOccurences = function (word) {
114+
// find the node with given prefix
115+
var node = this.findPrefix(word)
116+
// No such word exists
117+
if (node === null) return 0
118+
return node.count
119+
};
120+
121+
// To test
122+
(function demo () {
123+
var x = new Trie()
124+
x.insert('sheldon')
125+
x.insert('hello')
126+
x.insert('anyword')
127+
x.insert('sheldoncooper')
128+
console.log(x.findOccurences('sheldon'))
129+
x.remove('anything')
130+
x.insert('sheldon')
131+
console.log(x.findOccurences('sheldon'))
132+
console.log(x.findAllWords('sheldon'))
133+
x.insert('anything')
134+
x.remove('sheldoncooper')
135+
console.log(x.contains('sheldoncooper'))
136+
console.log(x.findAllWords('sheldon'))
137+
})()

Graphs/DijkstraSmallestPath.js

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,23 @@
11
// starting at s
22
function solve (graph, s) {
3-
var solutions = {}
3+
const solutions = {}
44
solutions[s] = []
55
solutions[s].dist = 0
66

77
while (true) {
8-
var p = null
9-
var neighbor = null
10-
var dist = Infinity
8+
let p = null
9+
let neighbor = null
10+
let dist = Infinity
1111

12-
for (var n in solutions) {
12+
for (const n in solutions) {
1313
if (!solutions[n]) { continue }
14-
var ndist = solutions[n].dist
15-
var adj = graph[n]
14+
const ndist = solutions[n].dist
15+
const adj = graph[n]
1616

17-
for (var a in adj) {
17+
for (const a in adj) {
1818
if (solutions[a]) { continue }
1919

20-
var d = adj[a] + ndist
20+
const d = adj[a] + ndist
2121
if (d < dist) {
2222
p = solutions[n]
2323
neighbor = a
@@ -40,9 +40,9 @@ function solve (graph, s) {
4040
return solutions
4141
}
4242
// create graph
43-
var graph = {}
43+
const graph = {}
4444

45-
var layout = {
45+
const layout = {
4646
R: ['2'],
4747
2: ['3', '4'],
4848
3: ['4', '6', '13'],
@@ -61,7 +61,7 @@ var layout = {
6161
}
6262

6363
// convert uni-directional to bi-directional graph
64-
// var graph = {
64+
// let graph = {
6565
// a: {e:1, b:1, g:3},
6666
// b: {a:1, c:1},
6767
// c: {b:1, d:1},
@@ -72,7 +72,7 @@ var layout = {
7272
// h: {f:1}
7373
// };
7474

75-
for (var id in layout) {
75+
for (const id in layout) {
7676
if (!graph[id]) { graph[id] = {} }
7777
layout[id].forEach(function (aid) {
7878
graph[id][aid] = 1
@@ -82,13 +82,13 @@ for (var id in layout) {
8282
}
8383

8484
// choose start node
85-
var start = '10'
85+
const start = '10'
8686
// get all solutions
87-
var solutions = solve(graph, start)
87+
const solutions = solve(graph, start)
8888

8989
console.log("From '" + start + "' to")
9090
// display solutions
91-
for (var s in solutions) {
91+
for (const s in solutions) {
9292
if (!solutions[s]) continue
9393
console.log(' -> ' + s + ': [' + solutions[s].join(', ') + '] (dist:' + solutions[s].dist + ')')
9494
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/*
2+
Modified from:
3+
https://github.com/TheAlgorithms/Python/blob/master/maths/binary_exp_mod.py
4+
5+
Explaination:
6+
https://en.wikipedia.org/wiki/Exponentiation_by_squaring
7+
*/
8+
9+
const modularBinaryExponentiation = (a, n, m) => {
10+
// input: a: int, n: int, m: int
11+
// returns: (a^n) % m: int
12+
if (n === 0) {
13+
return 1
14+
} else if (n % 2 === 1) {
15+
return (modularBinaryExponentiation(a, n - 1, m) * a) % m
16+
} else {
17+
const b = modularBinaryExponentiation(a, n / 2, m)
18+
return (b * b) % m
19+
}
20+
}
21+
22+
const main = () => {
23+
// binary_exponentiation(2, 10, 17)
24+
// > 4
25+
console.log(modularBinaryExponentiation(2, 10, 17))
26+
// binary_exponentiation(3, 9, 12)
27+
// > 3
28+
console.log(modularBinaryExponentiation(3, 9, 12))
29+
}
30+
31+
main()

Maths/PrimeCheck.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/*
2+
Modified from:
3+
https://github.com/TheAlgorithms/Python/blob/master/maths/prime_check.py
4+
5+
Complexity:
6+
O(sqrt(n))
7+
*/
8+
9+
const PrimeCheck = (n) => {
10+
// input: n: int
11+
// output: boolean
12+
for (let i = 2; i * i <= n; i++) {
13+
if (n % i === 0) {
14+
return false
15+
}
16+
}
17+
return true
18+
}
19+
20+
const main = () => {
21+
// PrimeCheck(1000003)
22+
// > true
23+
console.log(PrimeCheck(1000003))
24+
// PrimeCheck(1000001)
25+
// > false
26+
console.log(PrimeCheck(1000001))
27+
}
28+
29+
main()

Maths/digitSum.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// program to find sum of digits of a number
2+
3+
// function which would calculate sum and return it
4+
function digitSum (num) {
5+
// sum will store sum of digits of a number
6+
let sum = 0
7+
// while will run untill num become 0
8+
while (num) {
9+
sum += (num % 10)
10+
num = parseInt(num / 10)
11+
}
12+
13+
return sum
14+
}
15+
16+
// assigning number
17+
const num = 12345
18+
console.log(digitSum(num))

Recursive/TowerOfHanoi.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// wiki - https://en.wikipedia.org/wiki/Tower_of_Hanoi
2+
// Recursive Javascript function to solve tower of hanoi
3+
4+
function TowerOfHanoi (n, fromRod, toRod, auxRod) {
5+
if (n === 1) {
6+
console.log(`Move disk 1 from rod ${fromRod} to rod ${toRod}`)
7+
return
8+
}
9+
TowerOfHanoi(n - 1, fromRod, auxRod, toRod)
10+
console.log(`Move disk ${n} from rod ${fromRod} to rod ${toRod}`)
11+
TowerOfHanoi(n - 1, auxRod, toRod, fromRod)
12+
}
13+
// Driver code
14+
const n = 4
15+
TowerOfHanoi(n, 'A', 'C', 'B')
16+
// A, C, B are the name of rods

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy