mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 08:16:50 +08:00
Javascript/Math: editing file name
This commit is contained in:
26
Maths/Abs.js
Normal file
26
Maths/Abs.js
Normal file
@ -0,0 +1,26 @@
|
||||
/*
|
||||
author: PatOnTheBack
|
||||
license: GPL-3.0 or later
|
||||
|
||||
Modified from:
|
||||
https://github.com/TheAlgorithms/Python/blob/master/maths/abs.py
|
||||
|
||||
This script will find the absolute value of a number.
|
||||
|
||||
More about absolute values:
|
||||
https://en.wikipedia.org/wiki/Absolute_value
|
||||
*/
|
||||
|
||||
function absVal (num) {
|
||||
// Find absolute value of `num`.
|
||||
'use strict'
|
||||
if (num < 0) {
|
||||
return -num
|
||||
}
|
||||
// Executes if condition is not met.
|
||||
return num
|
||||
}
|
||||
|
||||
// Run `abs` function to find absolute value of two numbers.
|
||||
console.log('The absolute value of -34 is ' + absVal(-34))
|
||||
console.log('The absolute value of 34 is ' + absVal(34))
|
30
Maths/AverageMean.js
Normal file
30
Maths/AverageMean.js
Normal file
@ -0,0 +1,30 @@
|
||||
/*
|
||||
author: PatOnTheBack
|
||||
license: GPL-3.0 or later
|
||||
|
||||
Modified from:
|
||||
https://github.com/TheAlgorithms/Python/blob/master/maths/average.py
|
||||
|
||||
This script will find the average (mean) of an array of numbers.
|
||||
|
||||
More about mean:
|
||||
https://en.wikipedia.org/wiki/Mean
|
||||
*/
|
||||
|
||||
function mean (nums) {
|
||||
'use strict'
|
||||
var sum = 0
|
||||
var avg
|
||||
|
||||
// This loop sums all values in the 'nums' array.
|
||||
nums.forEach(function (current) {
|
||||
sum += current
|
||||
})
|
||||
|
||||
// Divide sum by the length of the 'nums' array.
|
||||
avg = sum / nums.length
|
||||
return avg
|
||||
}
|
||||
|
||||
// Run `mean` Function to find average of a list of numbers.
|
||||
console.log(mean([2, 4, 6, 8, 20, 50, 70]))
|
111
Maths/DijkstraSmallestPath.js
Normal file
111
Maths/DijkstraSmallestPath.js
Normal file
@ -0,0 +1,111 @@
|
||||
// starting at s
|
||||
function solve (graph, s) {
|
||||
var solutions = {}
|
||||
solutions[s] = []
|
||||
solutions[s].dist = 0
|
||||
|
||||
while (true) {
|
||||
var p = null
|
||||
var neighbor = null
|
||||
var dist = Infinity
|
||||
|
||||
for (var n in solutions) {
|
||||
if (!solutions[n]) { continue }
|
||||
var ndist = solutions[n].dist
|
||||
var adj = graph[n]
|
||||
|
||||
for (var a in adj) {
|
||||
if (solutions[a]) { continue }
|
||||
|
||||
var d = adj[a] + ndist
|
||||
if (d < dist) {
|
||||
p = solutions[n]
|
||||
neighbor = a
|
||||
dist = d
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// no more solutions
|
||||
if (dist === Infinity) {
|
||||
break
|
||||
}
|
||||
|
||||
// extend parent's solution path
|
||||
solutions[neighbor] = p.concat(neighbor)
|
||||
// extend parent's cost
|
||||
solutions[neighbor].dist = dist
|
||||
}
|
||||
|
||||
return solutions
|
||||
}
|
||||
// create graph
|
||||
var graph = {}
|
||||
|
||||
var layout = {
|
||||
R: ['2'],
|
||||
2: ['3', '4'],
|
||||
3: ['4', '6', '13'],
|
||||
4: ['5', '8'],
|
||||
5: ['7', '11'],
|
||||
6: ['13', '15'],
|
||||
7: ['10'],
|
||||
8: ['11', '13'],
|
||||
9: ['14'],
|
||||
10: [],
|
||||
11: ['12'],
|
||||
12: [],
|
||||
13: ['14'],
|
||||
14: [],
|
||||
15: []
|
||||
}
|
||||
|
||||
// convert uni-directional to bi-directional graph
|
||||
// var graph = {
|
||||
// a: {e:1, b:1, g:3},
|
||||
// b: {a:1, c:1},
|
||||
// c: {b:1, d:1},
|
||||
// d: {c:1, e:1},
|
||||
// e: {d:1, a:1},
|
||||
// f: {g:1, h:1},
|
||||
// g: {a:3, f:1},
|
||||
// h: {f:1}
|
||||
// };
|
||||
|
||||
for (var id in layout) {
|
||||
if (!graph[id]) { graph[id] = {} }
|
||||
layout[id].forEach(function (aid) {
|
||||
graph[id][aid] = 1
|
||||
if (!graph[aid]) { graph[aid] = {} }
|
||||
graph[aid][id] = 1
|
||||
})
|
||||
}
|
||||
|
||||
// choose start node
|
||||
var start = '10'
|
||||
// get all solutions
|
||||
var solutions = solve(graph, start)
|
||||
|
||||
console.log("From '" + start + "' to")
|
||||
// display solutions
|
||||
for (var s in solutions) {
|
||||
if (!solutions[s]) continue
|
||||
console.log(' -> ' + s + ': [' + solutions[s].join(', ') + '] (dist:' + solutions[s].dist + ')')
|
||||
}
|
||||
|
||||
// From '10' to
|
||||
// -> 2: [7, 5, 4, 2] (dist:4)
|
||||
// -> 3: [7, 5, 4, 3] (dist:4)
|
||||
// -> 4: [7, 5, 4] (dist:3)
|
||||
// -> 5: [7, 5] (dist:2)
|
||||
// -> 6: [7, 5, 4, 3, 6] (dist:5)
|
||||
// -> 7: [7] (dist:1)
|
||||
// -> 8: [7, 5, 4, 8] (dist:4)
|
||||
// -> 9: [7, 5, 4, 3, 13, 14, 9] (dist:7)
|
||||
// -> 10: [] (dist:0)
|
||||
// -> 11: [7, 5, 11] (dist:3)
|
||||
// -> 12: [7, 5, 11, 12] (dist:4)
|
||||
// -> 13: [7, 5, 4, 3, 13] (dist:5)
|
||||
// -> 14: [7, 5, 4, 3, 13, 14] (dist:6)
|
||||
// -> 15: [7, 5, 4, 3, 6, 15] (dist:6)
|
||||
// -> R: [7, 5, 4, 2, R] (dist:5)
|
53
Maths/Factorial.js
Normal file
53
Maths/Factorial.js
Normal file
@ -0,0 +1,53 @@
|
||||
/*
|
||||
author: PatOnTheBack
|
||||
license: GPL-3.0 or later
|
||||
|
||||
Modified from:
|
||||
https://github.com/TheAlgorithms/Python/blob/master/maths/factorial_python.py
|
||||
|
||||
This script will find the factorial of a number provided by the user.
|
||||
|
||||
More about factorials:
|
||||
https://en.wikipedia.org/wiki/factorial
|
||||
*/
|
||||
|
||||
'use strict'
|
||||
|
||||
function calcRange (num) {
|
||||
// Generate a range of numbers from 1 to `num`.
|
||||
var i = 1
|
||||
var range = []
|
||||
while (i <= num) {
|
||||
range.push(i)
|
||||
i += 1
|
||||
}
|
||||
return range
|
||||
}
|
||||
|
||||
function calcFactorial (num) {
|
||||
var factorial
|
||||
var range = calcRange(num)
|
||||
|
||||
// Check if the number is negative, positive, null, undefined, or zero
|
||||
if (num < 0) {
|
||||
return 'Sorry, factorial does not exist for negative numbers.'
|
||||
}
|
||||
if (num === null || num === undefined) {
|
||||
return 'Sorry, factorial does not exist for null or undefined numbers.'
|
||||
}
|
||||
if (num === 0) {
|
||||
return 'The factorial of 0 is 1.'
|
||||
}
|
||||
if (num > 0) {
|
||||
factorial = 1
|
||||
range.forEach(function (i) {
|
||||
factorial = factorial * i
|
||||
})
|
||||
return 'The factorial of ' + num + ' is ' + factorial
|
||||
}
|
||||
}
|
||||
|
||||
// Run `factorial` Function to find average of a list of numbers.
|
||||
|
||||
var num = console.log('Enter a number: ')
|
||||
console.log(calcFactorial(num))
|
59
Maths/Fibonacci.js
Normal file
59
Maths/Fibonacci.js
Normal file
@ -0,0 +1,59 @@
|
||||
const list = []
|
||||
|
||||
const FibonacciIterative = (nth) => {
|
||||
const sequence = []
|
||||
|
||||
if (nth >= 1) sequence.push(1)
|
||||
if (nth >= 2) sequence.push(1)
|
||||
|
||||
for (let i = 2; i < nth; i++) {
|
||||
sequence.push(sequence[i - 1] + sequence[i - 2])
|
||||
}
|
||||
|
||||
return sequence
|
||||
}
|
||||
|
||||
const FibonacciRecursive = (number) => {
|
||||
return (() => {
|
||||
switch (list.length) {
|
||||
case 0:
|
||||
list.push(1)
|
||||
return FibonacciRecursive(number)
|
||||
case 1:
|
||||
list.push(1)
|
||||
return FibonacciRecursive(number)
|
||||
case number:
|
||||
return list
|
||||
default:
|
||||
list.push(list[list.length - 1] + list[list.length - 2])
|
||||
return FibonacciRecursive(number)
|
||||
}
|
||||
})()
|
||||
}
|
||||
|
||||
const dict = new Map()
|
||||
|
||||
const FibonacciRecursiveDP = (stairs) => {
|
||||
if (stairs <= 0) return 0
|
||||
if (stairs === 1) return 1
|
||||
|
||||
// Memoize stair count
|
||||
if (dict.has(stairs)) return dict.get(stairs)
|
||||
|
||||
const res =
|
||||
FibonacciRecursiveDP(stairs - 1) + FibonacciRecursiveDP(stairs - 2)
|
||||
|
||||
dict.set(stairs, res)
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
// testing
|
||||
|
||||
console.log(FibonacciIterative(5))
|
||||
// Output: [ 1, 1, 2, 3, 5 ]
|
||||
console.log(FibonacciRecursive(5))
|
||||
// Output: [ 1, 1, 2, 3, 5 ]
|
||||
|
||||
console.log(FibonacciRecursiveDP(5))
|
||||
// Output: 5
|
30
Maths/FindHcf.js
Normal file
30
Maths/FindHcf.js
Normal file
@ -0,0 +1,30 @@
|
||||
/*
|
||||
author: redfly1
|
||||
More about HCF:
|
||||
https://en.wikipedia.org/wiki/Greatest_common_divisor
|
||||
*/
|
||||
|
||||
function findHCF (x, y) {
|
||||
// If the input numbers are less than 1 return an error message.
|
||||
if (x < 1 || y < 1) {
|
||||
return 'Please enter values greater than zero.'
|
||||
}
|
||||
|
||||
// If the input numbers are not integers return an error message.
|
||||
if (x !== Math.round(x) || y !== Math.round(y)) {
|
||||
return 'Please enter whole numbers.'
|
||||
}
|
||||
|
||||
// Now apply Euclid's algorithm to the two numbers.
|
||||
while (Math.max(x, y) % Math.min(x, y) !== 0) {
|
||||
if (x > y) {
|
||||
x %= y
|
||||
} else {
|
||||
y %= x
|
||||
}
|
||||
}
|
||||
|
||||
// When the while loop finishes the minimum of x and y is the HCF.
|
||||
return Math.min(x, y)
|
||||
}
|
||||
console.log(findHCF(27, 36))
|
38
Maths/FindLcm.js
Normal file
38
Maths/FindLcm.js
Normal file
@ -0,0 +1,38 @@
|
||||
/*
|
||||
author: PatOnTheBack
|
||||
license: GPL-3.0 or later
|
||||
|
||||
Modified from:
|
||||
https://github.com/TheAlgorithms/Python/blob/master/maths/findLcm.py
|
||||
|
||||
More about LCM:
|
||||
https://en.wikipedia.org/wiki/Least_common_multiple
|
||||
*/
|
||||
|
||||
'use strict'
|
||||
|
||||
// Find the LCM of two numbers.
|
||||
function findLcm (num1, num2) {
|
||||
var maxNum
|
||||
var lcm
|
||||
// Check to see whether num1 or num2 is larger.
|
||||
if (num1 > num2) {
|
||||
maxNum = num1
|
||||
} else {
|
||||
maxNum = num2
|
||||
}
|
||||
lcm = maxNum
|
||||
|
||||
while (true) {
|
||||
if ((lcm % num1 === 0) && (lcm % num2 === 0)) {
|
||||
break
|
||||
}
|
||||
lcm += maxNum
|
||||
}
|
||||
return lcm
|
||||
}
|
||||
|
||||
// Run `findLcm` Function
|
||||
var num1 = 12
|
||||
var num2 = 76
|
||||
console.log(findLcm(num1, num2))
|
88
Maths/Graph.js
Normal file
88
Maths/Graph.js
Normal file
@ -0,0 +1,88 @@
|
||||
// create a graph class
|
||||
class Graph {
|
||||
// defining vertex array and
|
||||
// adjacent list
|
||||
constructor (noOfVertices) {
|
||||
this.noOfVertices = noOfVertices
|
||||
this.AdjList = new Map()
|
||||
}
|
||||
|
||||
// functions to be implemented
|
||||
|
||||
// addVertex(v)
|
||||
// addEdge(v, w)
|
||||
// printGraph()
|
||||
|
||||
// bfs(v)
|
||||
// dfs(v)
|
||||
|
||||
// add vertex to the graph
|
||||
addVertex (v) {
|
||||
// initialize the adjacent list with a
|
||||
// null array
|
||||
|
||||
this.AdjList.set(v, [])
|
||||
}
|
||||
|
||||
// add edge to the graph
|
||||
addEdge (v, w) {
|
||||
// get the list for vertex v and put the
|
||||
// vertex w denoting edge between v and w
|
||||
this.AdjList.get(v).push(w)
|
||||
|
||||
// Since graph is undirected,
|
||||
// add an edge from w to v also
|
||||
this.AdjList.get(w).push(v)
|
||||
}
|
||||
|
||||
// Prints the vertex and adjacency list
|
||||
printGraph () {
|
||||
// get all the vertices
|
||||
const getKeys = this.AdjList.keys()
|
||||
|
||||
// iterate over the vertices
|
||||
for (const i of getKeys) {
|
||||
// great the corresponding adjacency list
|
||||
// for the vertex
|
||||
const getValues = this.AdjList.get(i)
|
||||
let conc = ''
|
||||
|
||||
// iterate over the adjacency list
|
||||
// concatenate the values into a string
|
||||
for (const j of getValues) {
|
||||
conc += j + ' '
|
||||
}
|
||||
|
||||
// print the vertex and its adjacency list
|
||||
console.log(i + ' -> ' + conc)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Example
|
||||
const graph = new Graph(6)
|
||||
const vertices = ['A', 'B', 'C', 'D', 'E', 'F']
|
||||
|
||||
// adding vertices
|
||||
for (let i = 0; i < vertices.length; i++) {
|
||||
graph.addVertex(vertices[i])
|
||||
}
|
||||
|
||||
// adding edges
|
||||
graph.addEdge('A', 'B')
|
||||
graph.addEdge('A', 'D')
|
||||
graph.addEdge('A', 'E')
|
||||
graph.addEdge('B', 'C')
|
||||
graph.addEdge('D', 'E')
|
||||
graph.addEdge('E', 'F')
|
||||
graph.addEdge('E', 'C')
|
||||
graph.addEdge('C', 'F')
|
||||
|
||||
// prints all vertex and
|
||||
// its adjacency list
|
||||
// A -> B D E
|
||||
// B -> A C
|
||||
// C -> B E F
|
||||
// D -> A E
|
||||
// E -> A D F C
|
||||
// F -> E C
|
||||
graph.printGraph()
|
51
Maths/Palindrome.js
Normal file
51
Maths/Palindrome.js
Normal file
@ -0,0 +1,51 @@
|
||||
/**
|
||||
* A palindrome is any string that can be reversed and still be the same.
|
||||
* An example of one is 'radar', since it is spelled the same even after
|
||||
* being reversed. One method to check if a
|
||||
*
|
||||
* Here's how this works recursively:
|
||||
*
|
||||
* Palindrome('radar')
|
||||
* true && Palindrome('ada')
|
||||
* true && true && Palindrome('d')
|
||||
* true && true && true && true
|
||||
*
|
||||
* @flow
|
||||
* @complexity: O(n)
|
||||
*/
|
||||
|
||||
function PalindromeRecursive (string) {
|
||||
// Base case
|
||||
if (string.length < 2) return true
|
||||
|
||||
// Check outermost keys
|
||||
if (string[0] !== string[string.length - 1]) {
|
||||
return false
|
||||
}
|
||||
|
||||
return PalindromeRecursive(string.slice(1, string.length - 1))
|
||||
}
|
||||
|
||||
function PalindromeIterative (string) {
|
||||
const _string = string
|
||||
.toLowerCase()
|
||||
.replace(/ /g, '')
|
||||
.replace(/,/g, '')
|
||||
.replace(/'.'/g, '')
|
||||
.replace(/:/g, '')
|
||||
.split('')
|
||||
|
||||
// A word of only 1 character is already a palindrome, so we skip to check it
|
||||
while (_string.length > 1) {
|
||||
if (_string.shift() !== _string.pop()) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// testing
|
||||
|
||||
console.log(PalindromeRecursive('Javascript Community'))
|
||||
console.log(PalindromeIterative('mom'))
|
31
Maths/PascalTriangle.js
Normal file
31
Maths/PascalTriangle.js
Normal file
@ -0,0 +1,31 @@
|
||||
const numRows = 5
|
||||
|
||||
var generate = function (numRows) {
|
||||
const triangle = [[1], [1, 1]]
|
||||
|
||||
if (numRows === 0) {
|
||||
return []
|
||||
} else if (numRows === 1) {
|
||||
return [[1]]
|
||||
} else if (numRows === 2) {
|
||||
return [[1], [1, 1]]
|
||||
} else {
|
||||
for (let i = 2; i < numRows; i++) {
|
||||
addRow(triangle)
|
||||
}
|
||||
}
|
||||
return triangle
|
||||
}
|
||||
var addRow = function (triangle) {
|
||||
const previous = triangle[triangle.length - 1]
|
||||
const newRow = [1]
|
||||
for (let i = 0; i < previous.length - 1; i++) {
|
||||
const current = previous[i]
|
||||
const next = previous[i + 1]
|
||||
newRow.push(current + next)
|
||||
}
|
||||
newRow.push(1)
|
||||
return triangle.push(newRow)
|
||||
}
|
||||
|
||||
generate(numRows)
|
Reference in New Issue
Block a user