mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 08:16:50 +08:00
chore: Merge pull request #739 from keshav-bohr/spell-check
fixed some spellings
This commit is contained in:
@ -4,7 +4,7 @@
|
|||||||
*
|
*
|
||||||
* Given an ordered set W of non-negative integers and a value K,
|
* Given an ordered set W of non-negative integers and a value K,
|
||||||
* determine all possible subsets from the given set W whose sum
|
* determine all possible subsets from the given set W whose sum
|
||||||
* of its elemets equals to the given value K.
|
* of its elements equals to the given value K.
|
||||||
*
|
*
|
||||||
* More info: https://www.geeksforgeeks.org/subset-sum-backtracking-4/
|
* More info: https://www.geeksforgeeks.org/subset-sum-backtracking-4/
|
||||||
*/
|
*/
|
||||||
@ -53,7 +53,7 @@ const sumOfSubset = (set, subset, setindex, sum, targetSum) => {
|
|||||||
targetSum
|
targetSum
|
||||||
)
|
)
|
||||||
|
|
||||||
// Concat the recursive result with current result arary
|
// Concat the recursive result with current result array
|
||||||
results = [...results, ...subsetResult]
|
results = [...results, ...subsetResult]
|
||||||
})
|
})
|
||||||
|
|
||||||
|
@ -3,13 +3,13 @@
|
|||||||
license: GPL-3.0 or later
|
license: GPL-3.0 or later
|
||||||
|
|
||||||
This script will find number of 1's
|
This script will find number of 1's
|
||||||
in binary representain of given number
|
in binary representation of given number
|
||||||
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
function BinaryCountSetBits (a) {
|
function BinaryCountSetBits (a) {
|
||||||
'use strict'
|
'use strict'
|
||||||
// convert number into binary representation and return number of set bits in binary representaion
|
// convert number into binary representation and return number of set bits in binary representation
|
||||||
return a.toString(2).split('1').length - 1
|
return a.toString(2).split('1').length - 1
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -48,7 +48,7 @@ function keyFinder (str) { // str is used to get the input of encrypted string
|
|||||||
// console.log( k + outStrElement + wordBank[i] );//debug
|
// console.log( k + outStrElement + wordBank[i] );//debug
|
||||||
|
|
||||||
// this part need to be optimize with the calculation of the number of occurrence of word's probabilities
|
// this part need to be optimize with the calculation of the number of occurrence of word's probabilities
|
||||||
// linked list will be used in the next stage of development to calculate the number of occurace of the key
|
// linked list will be used in the next stage of development to calculate the number of occurrence of the key
|
||||||
if (wordBank[i] === outStrElement) {
|
if (wordBank[i] === outStrElement) {
|
||||||
return k // return the key number if founded
|
return k // return the key number if founded
|
||||||
}
|
}
|
||||||
|
@ -22,9 +22,9 @@ const DateDayDifference = (date1, date2) => {
|
|||||||
if (typeof date1 !== 'string' && typeof date2 !== 'string') {
|
if (typeof date1 !== 'string' && typeof date2 !== 'string') {
|
||||||
return new TypeError('Argument is not a string.')
|
return new TypeError('Argument is not a string.')
|
||||||
}
|
}
|
||||||
// extarct the first date
|
// extract the first date
|
||||||
const [firstDateDay, firstDateMonth, firstDateYear] = date1.split('/').map((ele) => Number(ele))
|
const [firstDateDay, firstDateMonth, firstDateYear] = date1.split('/').map((ele) => Number(ele))
|
||||||
// extarct the second date
|
// extract the second date
|
||||||
const [secondDateDay, secondDateMonth, secondDateYear] = date2.split('/').map((ele) => Number(ele))
|
const [secondDateDay, secondDateMonth, secondDateYear] = date2.split('/').map((ele) => Number(ele))
|
||||||
// check the both data are valid or not.
|
// check the both data are valid or not.
|
||||||
if (firstDateDay < 0 || firstDateDay > 31 ||
|
if (firstDateDay < 0 || firstDateDay > 31 ||
|
||||||
|
@ -44,7 +44,7 @@ const DateToDay = (date) => {
|
|||||||
if (typeof date !== 'string') {
|
if (typeof date !== 'string') {
|
||||||
return new TypeError('Argument is not a string.')
|
return new TypeError('Argument is not a string.')
|
||||||
}
|
}
|
||||||
// extarct the date
|
// extract the date
|
||||||
const [day, month, year] = date.split('/').map((x) => Number(x))
|
const [day, month, year] = date.split('/').map((x) => Number(x))
|
||||||
// check the data are valid or not.
|
// check the data are valid or not.
|
||||||
if (day < 0 || day > 31 || month > 12 || month < 0) {
|
if (day < 0 || day > 31 || month > 12 || month < 0) {
|
||||||
|
@ -5,7 +5,7 @@
|
|||||||
want some changes in hour value.
|
want some changes in hour value.
|
||||||
|
|
||||||
Input Formate -> 07:05:45PM
|
Input Formate -> 07:05:45PM
|
||||||
Output Fromate -> 19:05:45
|
Output Formate -> 19:05:45
|
||||||
|
|
||||||
Problem & Explanation Source : https://www.mathsisfun.com/time.html
|
Problem & Explanation Source : https://www.mathsisfun.com/time.html
|
||||||
*/
|
*/
|
||||||
|
@ -2,7 +2,7 @@
|
|||||||
Problem statement and Explanation : https://www.codeproject.com/Tips/162540/Letter-Case-Conversion-Algorithms-Title-Case-Toggl.
|
Problem statement and Explanation : https://www.codeproject.com/Tips/162540/Letter-Case-Conversion-Algorithms-Title-Case-Toggl.
|
||||||
[Title case](https://en.wikipedia.org/wiki/Title_case) is a style where all words are capitalized. Officially, title case
|
[Title case](https://en.wikipedia.org/wiki/Title_case) is a style where all words are capitalized. Officially, title case
|
||||||
does not capitalize some words, such as very short words like "a" or "is", but for the purposes of this function, a general approach
|
does not capitalize some words, such as very short words like "a" or "is", but for the purposes of this function, a general approach
|
||||||
is taken where all words are capitalized regarless of length.
|
is taken where all words are capitalized regardless of length.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -12,7 +12,7 @@
|
|||||||
*/
|
*/
|
||||||
const titleCaseConversion = (inputString) => {
|
const titleCaseConversion = (inputString) => {
|
||||||
if (inputString === '') return ''
|
if (inputString === '') return ''
|
||||||
// Extact all space seprated string.
|
// Extract all space separated string.
|
||||||
const stringCollections = inputString.split(' ').map(word => {
|
const stringCollections = inputString.split(' ').map(word => {
|
||||||
let firstChar = ''
|
let firstChar = ''
|
||||||
// Get the [ASCII](https://en.wikipedia.org/wiki/ASCII) character code by the use charCodeAt method.
|
// Get the [ASCII](https://en.wikipedia.org/wiki/ASCII) character code by the use charCodeAt method.
|
||||||
|
@ -11,7 +11,7 @@ function main () {
|
|||||||
Note:
|
Note:
|
||||||
* While Solving the problem in given link below, don't use main() function.
|
* While Solving the problem in given link below, don't use main() function.
|
||||||
* Just use only the code inside main() function.
|
* Just use only the code inside main() function.
|
||||||
* The purpose of using main() function here is to aviod global variables.
|
* The purpose of using main() function here is to avoid global variables.
|
||||||
|
|
||||||
Link for the Problem: https://leetcode.com/problems/linked-list-cycle/
|
Link for the Problem: https://leetcode.com/problems/linked-list-cycle/
|
||||||
*/
|
*/
|
||||||
|
@ -10,7 +10,7 @@ function main () {
|
|||||||
Note:
|
Note:
|
||||||
* While Solving the problem in given link below, don't use main() function.
|
* While Solving the problem in given link below, don't use main() function.
|
||||||
* Just use only the code inside main() function.
|
* Just use only the code inside main() function.
|
||||||
* The purpose of using main() function here is to aviod global variables.
|
* The purpose of using main() function here is to avoid global variables.
|
||||||
|
|
||||||
Link for the Problem: https://leetcode.com/problems/rotate-list/
|
Link for the Problem: https://leetcode.com/problems/rotate-list/
|
||||||
*/
|
*/
|
||||||
|
@ -37,7 +37,7 @@ let utils;
|
|||||||
*/
|
*/
|
||||||
const AVLTree = (function () {
|
const AVLTree = (function () {
|
||||||
function _avl (comp) {
|
function _avl (comp) {
|
||||||
/** @public compartor function */
|
/** @public comparator function */
|
||||||
this._comp = undefined
|
this._comp = undefined
|
||||||
if (comp !== undefined) {
|
if (comp !== undefined) {
|
||||||
this._comp = comp
|
this._comp = comp
|
||||||
@ -119,7 +119,7 @@ const AVLTree = (function () {
|
|||||||
node._right = rightRotate(node._right)
|
node._right = rightRotate(node._right)
|
||||||
return leftRotate(node) // Right Left
|
return leftRotate(node) // Right Left
|
||||||
}
|
}
|
||||||
return leftRotate(node) // Rigth Right
|
return leftRotate(node) // Right Right
|
||||||
}
|
}
|
||||||
// implement avl tree insertion
|
// implement avl tree insertion
|
||||||
const insert = function (root, val, tree) {
|
const insert = function (root, val, tree) {
|
||||||
@ -202,7 +202,7 @@ const AVLTree = (function () {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* TO check is a particluar element exists or not
|
* TO check is a particular element exists or not
|
||||||
* @param {any} _val
|
* @param {any} _val
|
||||||
* @returns {Boolean} exists or not
|
* @returns {Boolean} exists or not
|
||||||
*/
|
*/
|
||||||
|
@ -14,7 +14,7 @@ function Trie () {
|
|||||||
this.root = new TrieNode(null, null)
|
this.root = new TrieNode(null, null)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Recursively finds the occurence of all words in a given node
|
// Recursively finds the occurrence of all words in a given node
|
||||||
Trie.findAllWords = function (root, word, output) {
|
Trie.findAllWords = function (root, word, output) {
|
||||||
if (root === null) return
|
if (root === null) return
|
||||||
if (root.count > 0) {
|
if (root.count > 0) {
|
||||||
@ -79,11 +79,11 @@ Trie.prototype.remove = function (word, count) {
|
|||||||
child = child.children[key]
|
child = child.children[key]
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete no of occurences specified
|
// Delete no of occurrences specified
|
||||||
if (child.count >= count) child.count -= count
|
if (child.count >= count) child.count -= count
|
||||||
else child.count = 0
|
else child.count = 0
|
||||||
|
|
||||||
// If some occurences are left we dont delete it or else
|
// If some occurrences are left we dont delete it or else
|
||||||
// if the object forms some other objects prefix we dont delete it
|
// if the object forms some other objects prefix we dont delete it
|
||||||
// For checking an empty object
|
// For checking an empty object
|
||||||
// https://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object
|
// https://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object
|
||||||
|
@ -10,7 +10,7 @@ function KadaneAlgo (array) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
return maxSum
|
return maxSum
|
||||||
// This function returns largest sum contigous sum in a array
|
// This function returns largest sum contiguous sum in a array
|
||||||
}
|
}
|
||||||
function main () {
|
function main () {
|
||||||
const myArray = [1, 2, 3, 4, -6]
|
const myArray = [1, 2, 3, 4, -6]
|
||||||
|
@ -2,7 +2,7 @@ function sieveOfEratosthenes (n) {
|
|||||||
/*
|
/*
|
||||||
* Calculates prime numbers till a number n
|
* Calculates prime numbers till a number n
|
||||||
* :param n: Number upto which to calculate primes
|
* :param n: Number upto which to calculate primes
|
||||||
* :return: A boolean list contaning only primes
|
* :return: A boolean list containing only primes
|
||||||
*/
|
*/
|
||||||
const primes = new Array(n + 1)
|
const primes = new Array(n + 1)
|
||||||
primes.fill(true) // set all as true initially
|
primes.fill(true) // set all as true initially
|
||||||
|
@ -1,19 +1,19 @@
|
|||||||
import { longestPalindromeSubsequence } from '../LongestPalindromicSubsequence'
|
import { longestPalindromeSubsequence } from '../LongestPalindromicSubsequence'
|
||||||
|
|
||||||
describe('LongestPalindromicSubsequence', () => {
|
describe('LongestPalindromicSubsequence', () => {
|
||||||
it('expects to return 1 as longest pallindromic subsequence', () => {
|
it('expects to return 1 as longest palindromic subsequence', () => {
|
||||||
expect(longestPalindromeSubsequence('abcdefgh')).toBe(1)
|
expect(longestPalindromeSubsequence('abcdefgh')).toBe(1)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('expects to return 4 as longest pallindromic subsequence', () => {
|
it('expects to return 4 as longest palindromic subsequence', () => {
|
||||||
expect(longestPalindromeSubsequence('bbbab')).toBe(4)
|
expect(longestPalindromeSubsequence('bbbab')).toBe(4)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('expects to return 2 as longest pallindromic subsequence', () => {
|
it('expects to return 2 as longest palindromic subsequence', () => {
|
||||||
expect(longestPalindromeSubsequence('cbbd')).toBe(2)
|
expect(longestPalindromeSubsequence('cbbd')).toBe(2)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('expects to return 7 as longest pallindromic subsequence', () => {
|
it('expects to return 7 as longest palindromic subsequence', () => {
|
||||||
expect(longestPalindromeSubsequence('racexyzcxar')).toBe(7)
|
expect(longestPalindromeSubsequence('racexyzcxar')).toBe(7)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
@ -33,7 +33,7 @@ function convexHull (points) {
|
|||||||
points.sort(compare)
|
points.sort(compare)
|
||||||
const p1 = points[0]; const p2 = points[pointsLen - 1]
|
const p1 = points[0]; const p2 = points[pointsLen - 1]
|
||||||
|
|
||||||
// Divide Hull in two halfs
|
// Divide Hull in two halves
|
||||||
const upperPoints = []; const lowerPoints = []
|
const upperPoints = []; const lowerPoints = []
|
||||||
|
|
||||||
upperPoints.push(p1)
|
upperPoints.push(p1)
|
||||||
|
@ -2,7 +2,7 @@
|
|||||||
* Author: Samarth Jain
|
* Author: Samarth Jain
|
||||||
* Dijkstra's Algorithm implementation in JavaScript
|
* Dijkstra's Algorithm implementation in JavaScript
|
||||||
* Dijkstra's Algorithm calculates the minimum distance between two nodes.
|
* Dijkstra's Algorithm calculates the minimum distance between two nodes.
|
||||||
* It is used to find the shortes path.
|
* It is used to find the shortest path.
|
||||||
* It uses graph data structure.
|
* It uses graph data structure.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
@ -2,8 +2,8 @@
|
|||||||
https://dev.to/rattanakchea/amazons-interview-question-count-island-21h6
|
https://dev.to/rattanakchea/amazons-interview-question-count-island-21h6
|
||||||
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
|
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
|
||||||
|
|
||||||
two a dimensial grid map
|
a two dimensional grid map
|
||||||
each element is going to represent a peice of land
|
each element is going to represent a piece of land
|
||||||
1 is land,
|
1 is land,
|
||||||
0 is water
|
0 is water
|
||||||
output a number which is the number of islands
|
output a number which is the number of islands
|
||||||
|
@ -9,11 +9,11 @@
|
|||||||
const CHAR_SIZE = 8
|
const CHAR_SIZE = 8
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Adds padding to binary/hex string represention
|
* Adds padding to binary/hex string representation
|
||||||
*
|
*
|
||||||
* @param {string} str - string represention (binary/hex)
|
* @param {string} str - string representation (binary/hex)
|
||||||
* @param {int} bits - total number of bits wanted
|
* @param {int} bits - total number of bits wanted
|
||||||
* @return {string} - string represention padding with empty (0) bits
|
* @return {string} - string representation padding with empty (0) bits
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
* pad("10011", 8); // "00010011"
|
* pad("10011", 8); // "00010011"
|
||||||
|
@ -20,11 +20,11 @@ const K = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Adds padding to binary/hex string represention
|
* Adds padding to binary/hex string representation
|
||||||
*
|
*
|
||||||
* @param {string} str - string represention (binary/hex)
|
* @param {string} str - string representation (binary/hex)
|
||||||
* @param {int} bits - total number of bits wanted
|
* @param {int} bits - total number of bits wanted
|
||||||
* @return {string} - string represention padding with empty (0) bits
|
* @return {string} - string representation padding with empty (0) bits
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
* pad("10011", 8); // "00010011"
|
* pad("10011", 8); // "00010011"
|
||||||
@ -56,7 +56,7 @@ function chunkify (str, size) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Rotates string represention of bits to th left
|
* Rotates string representation of bits to th left
|
||||||
*
|
*
|
||||||
* @param {string} bits - string representation of bits
|
* @param {string} bits - string representation of bits
|
||||||
* @param {int} turns - number of rotations to make
|
* @param {int} turns - number of rotations to make
|
||||||
|
@ -26,7 +26,7 @@ let LinearAlgebra;
|
|||||||
if (N === comps.length) {
|
if (N === comps.length) {
|
||||||
this.components = comps
|
this.components = comps
|
||||||
} else {
|
} else {
|
||||||
throw new Error('Vector: invalide size!')
|
throw new Error('Vector: invalid size!')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} // end of constructor
|
} // end of constructor
|
||||||
|
@ -2,7 +2,7 @@
|
|||||||
Modified from:
|
Modified from:
|
||||||
https://github.com/TheAlgorithms/Python/blob/master/maths/binary_exponentiation.py
|
https://github.com/TheAlgorithms/Python/blob/master/maths/binary_exponentiation.py
|
||||||
|
|
||||||
Explaination:
|
Explanation:
|
||||||
https://en.wikipedia.org/wiki/Exponentiation_by_squaring
|
https://en.wikipedia.org/wiki/Exponentiation_by_squaring
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
@ -1,11 +1,11 @@
|
|||||||
/*
|
/*
|
||||||
Problem statement and Explanation : https://www.geeksforgeeks.org/check-if-a-number-is-a-krishnamurthy-number-or-not-2/
|
Problem statement and Explanation : https://www.geeksforgeeks.org/check-if-a-number-is-a-krishnamurthy-number-or-not-2/
|
||||||
|
|
||||||
krishnamurthy number is a number the sum of the all fectorial of the all dights is equal to the number itself.
|
krishnamurthy number is a number the sum of the all factorial of the all dights is equal to the number itself.
|
||||||
145 => 1! + 4! + 5! = 1 + 24 + 120 = 145
|
145 => 1! + 4! + 5! = 1 + 24 + 120 = 145
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// factorail utility method.
|
// factorial utility method.
|
||||||
const factorial = (n) => {
|
const factorial = (n) => {
|
||||||
let fact = 1
|
let fact = 1
|
||||||
while (n !== 0) {
|
while (n !== 0) {
|
||||||
@ -18,7 +18,7 @@ const factorial = (n) => {
|
|||||||
/**
|
/**
|
||||||
* krishnamurthy number is a number the sum of the factorial of the all dights is equal to the number itself.
|
* krishnamurthy number is a number the sum of the factorial of the all dights is equal to the number itself.
|
||||||
* @param {Number} number a number for checking is krishnamurthy number or not.
|
* @param {Number} number a number for checking is krishnamurthy number or not.
|
||||||
* @returns return correspond boolean vlaue, if the number is krishnamurthy number return `true` else return `false`.
|
* @returns return correspond boolean value, if the number is krishnamurthy number return `true` else return `false`.
|
||||||
* @example 145 => 1! + 4! + 5! = 1 + 24 + 120 = 145
|
* @example 145 => 1! + 4! + 5! = 1 + 24 + 120 = 145
|
||||||
*/
|
*/
|
||||||
const CheckKishnamurthyNumber = (number) => {
|
const CheckKishnamurthyNumber = (number) => {
|
||||||
|
@ -4,7 +4,7 @@
|
|||||||
const digitSum = (num) => {
|
const digitSum = (num) => {
|
||||||
// sum will store sum of digits of a number
|
// sum will store sum of digits of a number
|
||||||
let sum = 0
|
let sum = 0
|
||||||
// while will run untill num become 0
|
// while will run until num become 0
|
||||||
while (num) {
|
while (num) {
|
||||||
sum += num % 10
|
sum += num % 10
|
||||||
num = parseInt(num / 10)
|
num = parseInt(num / 10)
|
||||||
|
@ -2,7 +2,7 @@
|
|||||||
Modified from:
|
Modified from:
|
||||||
https://github.com/TheAlgorithms/Python/blob/master/maths/binary_exp_mod.py
|
https://github.com/TheAlgorithms/Python/blob/master/maths/binary_exp_mod.py
|
||||||
|
|
||||||
Explaination:
|
Explanation:
|
||||||
https://en.wikipedia.org/wiki/Exponentiation_by_squaring
|
https://en.wikipedia.org/wiki/Exponentiation_by_squaring
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
// Wikipedia: https://en.wikipedia.org/wiki/Monte_Carlo_method
|
// Wikipedia: https://en.wikipedia.org/wiki/Monte_Carlo_method
|
||||||
// Video Explaination: https://www.youtube.com/watch?v=ELetCV_wX_c
|
// Video Explanation: https://www.youtube.com/watch?v=ELetCV_wX_c
|
||||||
|
|
||||||
const piEstimation = (iterations = 100000) => {
|
const piEstimation = (iterations = 100000) => {
|
||||||
let circleCounter = 0
|
let circleCounter = 0
|
||||||
|
@ -2,7 +2,7 @@ const sieveOfEratosthenes = (n) => {
|
|||||||
/*
|
/*
|
||||||
* Calculates prime numbers till a number n
|
* Calculates prime numbers till a number n
|
||||||
* :param n: Number upto which to calculate primes
|
* :param n: Number upto which to calculate primes
|
||||||
* :return: A boolean list contaning only primes
|
* :return: A boolean list containing only primes
|
||||||
*/
|
*/
|
||||||
const primes = new Array(n + 1)
|
const primes = new Array(n + 1)
|
||||||
primes.fill(true) // set all as true initially
|
primes.fill(true) // set all as true initially
|
||||||
|
@ -17,7 +17,7 @@ function sumOfDigitsUsingString (number) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
The input is divided by 10 in each iteraction, till the input is equal to 0
|
The input is divided by 10 in each iteration, till the input is equal to 0
|
||||||
The sum of all the digits is returned (The res variable acts as a collector, taking the remainders on each iteration)
|
The sum of all the digits is returned (The res variable acts as a collector, taking the remainders on each iteration)
|
||||||
*/
|
*/
|
||||||
function sumOfDigitsUsingLoop (number) {
|
function sumOfDigitsUsingLoop (number) {
|
||||||
|
@ -6,20 +6,20 @@ import {
|
|||||||
FibonacciMatrixExpo
|
FibonacciMatrixExpo
|
||||||
} from '../Fibonacci'
|
} from '../Fibonacci'
|
||||||
|
|
||||||
describe('Fibonanci', () => {
|
describe('Fibonacci', () => {
|
||||||
it('should return an array of numbers for FibonnaciIterative', () => {
|
it('should return an array of numbers for FibonacciIterative', () => {
|
||||||
expect(FibonacciIterative(5)).toEqual(
|
expect(FibonacciIterative(5)).toEqual(
|
||||||
expect.arrayContaining([1, 1, 2, 3, 5])
|
expect.arrayContaining([1, 1, 2, 3, 5])
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should return an array of numbers for FibonnaciRecursive', () => {
|
it('should return an array of numbers for FibonacciRecursive', () => {
|
||||||
expect(FibonacciRecursive(5)).toEqual(
|
expect(FibonacciRecursive(5)).toEqual(
|
||||||
expect.arrayContaining([1, 1, 2, 3, 5])
|
expect.arrayContaining([1, 1, 2, 3, 5])
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should return number for FibonnaciRecursiveDP', () => {
|
it('should return number for FibonacciRecursiveDP', () => {
|
||||||
expect(FibonacciRecursiveDP(5)).toBe(5)
|
expect(FibonacciRecursiveDP(5)).toBe(5)
|
||||||
})
|
})
|
||||||
|
|
||||||
@ -29,7 +29,7 @@ describe('Fibonanci', () => {
|
|||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should return number for FibonnaciMatrixExpo', () => {
|
it('should return number for FibonacciMatrixExpo', () => {
|
||||||
expect(FibonacciMatrixExpo(0)).toBe(0)
|
expect(FibonacciMatrixExpo(0)).toBe(0)
|
||||||
expect(FibonacciMatrixExpo(1)).toBe(1)
|
expect(FibonacciMatrixExpo(1)).toBe(1)
|
||||||
expect(FibonacciMatrixExpo(2)).toBe(1)
|
expect(FibonacciMatrixExpo(2)).toBe(1)
|
||||||
|
@ -33,12 +33,12 @@ const getCollatzSequenceLength = (num, seqLength) => {
|
|||||||
|
|
||||||
const findLongestCollatzSequence = () => {
|
const findLongestCollatzSequence = () => {
|
||||||
let startingPointForLargestSequence = 1
|
let startingPointForLargestSequence = 1
|
||||||
let largestSequnceLength = 1
|
let largestSequenceLength = 1
|
||||||
for (let i = 2; i < 1000000; i++) {
|
for (let i = 2; i < 1000000; i++) {
|
||||||
const currentSequenceLength = getCollatzSequenceLength(i, 1)
|
const currentSequenceLength = getCollatzSequenceLength(i, 1)
|
||||||
if (currentSequenceLength > largestSequnceLength) {
|
if (currentSequenceLength > largestSequenceLength) {
|
||||||
startingPointForLargestSequence = i
|
startingPointForLargestSequence = i
|
||||||
largestSequnceLength = currentSequenceLength
|
largestSequenceLength = currentSequenceLength
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return startingPointForLargestSequence
|
return startingPointForLargestSequence
|
||||||
|
@ -15,7 +15,7 @@ function makeTable (str) {
|
|||||||
// case 1. the current character doesn't match the last character of the longest prefix
|
// case 1. the current character doesn't match the last character of the longest prefix
|
||||||
while (maxPrefix > 0 && str.charAt(i) !== str.charAt(maxPrefix)) {
|
while (maxPrefix > 0 && str.charAt(i) !== str.charAt(maxPrefix)) {
|
||||||
// if that is the case, we have to backtrack, and try find a character that will be equal to the current character
|
// if that is the case, we have to backtrack, and try find a character that will be equal to the current character
|
||||||
// if we reach 0, then we couldn't find a chracter
|
// if we reach 0, then we couldn't find a character
|
||||||
maxPrefix = table[maxPrefix - 1]
|
maxPrefix = table[maxPrefix - 1]
|
||||||
}
|
}
|
||||||
// case 2. The last character of the longest prefix matches the current character in `str`
|
// case 2. The last character of the longest prefix matches the current character in `str`
|
||||||
|
@ -54,11 +54,11 @@ function bucketSort (list, size) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Testing
|
// Testing
|
||||||
const arrOrignal = [5, 6, 7, 8, 1, 2, 12, 14]
|
const arrOriginal = [5, 6, 7, 8, 1, 2, 12, 14]
|
||||||
// > bucketSort(arrOrignal)
|
// > bucketSort(arrOriginal)
|
||||||
// [1, 2, 5, 6, 7, 8, 12, 14]
|
// [1, 2, 5, 6, 7, 8, 12, 14]
|
||||||
// Array before Sort
|
// Array before Sort
|
||||||
console.log(arrOrignal)
|
console.log(arrOriginal)
|
||||||
const arrSorted = bucketSort(arrOrignal)
|
const arrSorted = bucketSort(arrOriginal)
|
||||||
// Array after sort
|
// Array after sort
|
||||||
console.log(arrSorted)
|
console.log(arrSorted)
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
/**
|
/**
|
||||||
* @function Intosort (As implemented in STD C++ Lib)
|
* @function Intosort (As implemented in STD C++ Lib)
|
||||||
* The function performs introsort which is used in
|
* The function performs introsort which is used in
|
||||||
* C++ Standard LIbrary, the implemntation is inspired from]
|
* C++ Standard LIbrary, the implementation is inspired from]
|
||||||
* library routine itself.
|
* library routine itself.
|
||||||
* ALGORITHM:
|
* ALGORITHM:
|
||||||
* 1) It performs quicksort on array until the recursion depth
|
* 1) It performs quicksort on array until the recursion depth
|
||||||
@ -111,7 +111,7 @@ function introsort (array, compare) {
|
|||||||
*/
|
*/
|
||||||
quickSort(0, len, maxDepth)
|
quickSort(0, len, maxDepth)
|
||||||
/**
|
/**
|
||||||
* A final checlk call to insertion sort
|
* A final check call to insertion sort
|
||||||
* on sorted array
|
* on sorted array
|
||||||
*/
|
*/
|
||||||
insertionSort(0, len)
|
insertionSort(0, len)
|
||||||
@ -140,7 +140,7 @@ function introsort (array, compare) {
|
|||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* @function Helper function to quicksort
|
* @function Helper function to quicksort
|
||||||
* @param {Number} start the start of array segment to partitiion
|
* @param {Number} start the start of array segment to partition
|
||||||
* @param {Number} last one more than last index of the array segment
|
* @param {Number} last one more than last index of the array segment
|
||||||
* @param {Number} pivot the index of pivot to be used
|
* @param {Number} pivot the index of pivot to be used
|
||||||
* @returns {Number} the index of pivot after partition
|
* @returns {Number} the index of pivot after partition
|
||||||
|
@ -37,7 +37,7 @@ const quickSort = (inputList, low, high) => {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Partition In Place method.
|
* Partition In Place method.
|
||||||
* @param {number[]} partitionList list for partiting.
|
* @param {number[]} partitionList list for partitioning.
|
||||||
* @param {number} low lower index for partition.
|
* @param {number} low lower index for partition.
|
||||||
* @param {number} high higher index for partition.
|
* @param {number} high higher index for partition.
|
||||||
* @returns {number} `pIndex` pivot index value.
|
* @returns {number} `pIndex` pivot index value.
|
||||||
|
@ -30,7 +30,7 @@ const Timsort = (array) => {
|
|||||||
/**
|
/**
|
||||||
* @function performs insertion sort on the partition
|
* @function performs insertion sort on the partition
|
||||||
* @param {Array} array array to be sorted
|
* @param {Array} array array to be sorted
|
||||||
* @param {Number} left left index of partiton
|
* @param {Number} left left index of partition
|
||||||
* @param {Number} right right index of partition
|
* @param {Number} right right index of partition
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
@ -14,24 +14,24 @@ const AlternativeStringArrange = (str1, str2) => {
|
|||||||
return 'Not string(s)'
|
return 'Not string(s)'
|
||||||
}
|
}
|
||||||
|
|
||||||
// output string vlaue.
|
// output string value.
|
||||||
let outStr = ''
|
let outStr = ''
|
||||||
|
|
||||||
// get first string length.
|
// get first string length.
|
||||||
const firstStringLength = str1.length
|
const firstStringLength = str1.length
|
||||||
// get second string length.
|
// get second string length.
|
||||||
const secondStringLength = str2.length
|
const secondStringLength = str2.length
|
||||||
// absolute length for oparetion.
|
// absolute length for operation.
|
||||||
const absLenght = firstStringLength > secondStringLength ? firstStringLength : secondStringLength
|
const absLength = firstStringLength > secondStringLength ? firstStringLength : secondStringLength
|
||||||
|
|
||||||
// Iterate the character count until the absolute count is reached.
|
// Iterate the character count until the absolute count is reached.
|
||||||
for (let charCount = 0; charCount < absLenght; charCount++) {
|
for (let charCount = 0; charCount < absLength; charCount++) {
|
||||||
// If firstStringLength is lesser than the charCount it means they are able to re-arange.
|
// If firstStringLength is lesser than the charCount it means they are able to re-arrange.
|
||||||
if (charCount < firstStringLength) {
|
if (charCount < firstStringLength) {
|
||||||
outStr += str1[charCount]
|
outStr += str1[charCount]
|
||||||
}
|
}
|
||||||
|
|
||||||
// If secondStringLength is lesser than the charCount it means they are able to re-arange.
|
// If secondStringLength is lesser than the charCount it means they are able to re-arrange.
|
||||||
if (charCount < secondStringLength) {
|
if (charCount < secondStringLength) {
|
||||||
outStr += str2[charCount]
|
outStr += str2[charCount]
|
||||||
}
|
}
|
||||||
|
@ -8,7 +8,7 @@ const checkPalindrome = (str) => {
|
|||||||
if (str.length === 0) {
|
if (str.length === 0) {
|
||||||
return 'Empty string'
|
return 'Empty string'
|
||||||
}
|
}
|
||||||
// Reverse only works with array, thus conevert the string to array, reverse it and convert back to string
|
// Reverse only works with array, thus convert the string to array, reverse it and convert back to string
|
||||||
// return as palindrome if the reversed string is equal to the input string
|
// return as palindrome if the reversed string is equal to the input string
|
||||||
const reversed = [...str].reverse().join('')
|
const reversed = [...str].reverse().join('')
|
||||||
return str === reversed ? 'Palindrome' : 'Not a Palindrome'
|
return str === reversed ? 'Palindrome' : 'Not a Palindrome'
|
||||||
|
@ -15,12 +15,12 @@ const levenshteinDistance = (a, b) => {
|
|||||||
.fill(null)
|
.fill(null)
|
||||||
.map(() => Array(a.length + 1).fill(null))
|
.map(() => Array(a.length + 1).fill(null))
|
||||||
|
|
||||||
// Initialising first column:
|
// Initializing first column:
|
||||||
for (let i = 0; i <= a.length; i += 1) {
|
for (let i = 0; i <= a.length; i += 1) {
|
||||||
distanceMatrix[0][i] = i
|
distanceMatrix[0][i] = i
|
||||||
}
|
}
|
||||||
|
|
||||||
// Initialising first row:
|
// Initializing first row:
|
||||||
for (let j = 0; j <= b.length; j += 1) {
|
for (let j = 0; j <= b.length; j += 1) {
|
||||||
distanceMatrix[j][0] = j
|
distanceMatrix[j][0] = j
|
||||||
}
|
}
|
||||||
|
@ -1,15 +1,15 @@
|
|||||||
// Given a sentence, return the most occuring word
|
// Given a sentence, return the most occurring word
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {string} sentence - the sentence you want to find the most occuring word
|
* @param {string} sentence - the sentence you want to find the most occurring word
|
||||||
* @returns {string} - the most occuring word
|
* @returns {string} - the most occurring word
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
* - maxWord('lala lili lala'); // lala
|
* - maxWord('lala lili lala'); // lala
|
||||||
*/
|
*/
|
||||||
const maxWord = (sentence = '') => {
|
const maxWord = (sentence = '') => {
|
||||||
if (typeof sentence !== 'string') {
|
if (typeof sentence !== 'string') {
|
||||||
throw new TypeError('the param sould be string')
|
throw new TypeError('the param should be string')
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!sentence) {
|
if (!sentence) {
|
||||||
|
@ -6,7 +6,7 @@ describe('Testing the maxWord function', () => {
|
|||||||
})
|
})
|
||||||
it('get the max word', () => {
|
it('get the max word', () => {
|
||||||
const string = 'ba ba ba ba banana'
|
const string = 'ba ba ba ba banana'
|
||||||
const mostOccuringWord = maxWord(string)
|
const mostOccurringWord = maxWord(string)
|
||||||
expect(mostOccuringWord).toBe('ba')
|
expect(mostOccurringWord).toBe('ba')
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
@ -18,7 +18,7 @@ describe('checkIfPatternExists', () => {
|
|||||||
const SUT = checkIfPatternExists(text, pattern)
|
const SUT = checkIfPatternExists(text, pattern)
|
||||||
expect(SUT).toBe(undefined)
|
expect(SUT).toBe(undefined)
|
||||||
})
|
})
|
||||||
it('expects to throw an error message when given inpuut is not a string', () => {
|
it('expects to throw an error message when given input is not a string', () => {
|
||||||
const text = 123444456
|
const text = 123444456
|
||||||
const pattern = 123
|
const pattern = 123
|
||||||
expect(() => checkIfPatternExists(text, pattern)).toThrow(
|
expect(() => checkIfPatternExists(text, pattern)).toThrow(
|
||||||
|
@ -25,7 +25,7 @@ class BinaryTree {
|
|||||||
return this.traversal.toLocaleString()
|
return this.traversal.toLocaleString()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Compputing the height of the tree
|
// Computing the height of the tree
|
||||||
getHeight (node) {
|
getHeight (node) {
|
||||||
if (node == null) {
|
if (node == null) {
|
||||||
return 0
|
return 0
|
||||||
|
Reference in New Issue
Block a user