chore: Merge pull request #768 from lvlte/issues/720

Changes for consolidation
This commit is contained in:
Rak Laptudirm
2021-10-21 19:32:55 +05:30
committed by GitHub
153 changed files with 1084 additions and 1214 deletions

View File

@ -25,19 +25,21 @@ class Combinations {
constructor (n, k) { constructor (n, k) {
this.n = n this.n = n
this.k = k this.k = k
this.combinationArray = [] // will be used for storing current combination this.current = [] // will be used for storing current combination
this.combinations = []
} }
findCombinations (high = this.n, total = this.k, low = 1) { findCombinations (high = this.n, total = this.k, low = 1) {
if (total === 0) { if (total === 0) {
console.log(this.combinationArray) this.combinations.push([...this.current])
return return this.combinations
} }
for (let i = low; i <= high; i++) { for (let i = low; i <= high; i++) {
this.combinationArray.push(i) this.current.push(i)
this.findCombinations(high, total - 1, i + 1) this.findCombinations(high, total - 1, i + 1)
this.combinationArray.pop() this.current.pop()
} }
return this.combinations
} }
} }

View File

@ -1,8 +1,8 @@
/* /*
* Problem Statement: Generate all distinct permutations of a string/array (all permutations should be in sorted order); * Problem Statement: Generate all distinct permutations of a an array (all permutations should be in sorted order);
* *
* What is permutations? * What is permutations?
* - Permutation means possible arrangements in a set (here it is string/array); * - Permutation means possible arrangements in a set (here it is an array);
* *
* Reference to know more about permutations: * Reference to know more about permutations:
* - https://www.britannica.com/science/permutation * - https://www.britannica.com/science/permutation
@ -17,17 +17,20 @@ const swap = (arr, i, j) => {
return newArray return newArray
} }
const permutations = (arr, low, high) => { const permutations = arr => {
const P = []
const permute = (arr, low, high) => {
if (low === high) { if (low === high) {
console.log(arr.join(' ')) P.push([...arr])
return return P
} }
for (let i = low; i <= high; i++) { for (let i = low; i <= high; i++) {
arr = swap(arr, low, i) arr = swap(arr, low, i)
permutations(arr, low + 1, high) permute(arr, low + 1, high)
} }
return P
}
return permute(arr, 0, arr.length - 1)
} }
// Driver Code export { permutations }
const input = [1, 2, 3]
permutations(input, 0, input.length - 1)

View File

@ -52,27 +52,16 @@ class OpenKnightTour {
return false return false
} }
printBoard () { printBoard (output = value => console.log(value)) {
// utility function to display the board // utility function to display the board
for (const row of this.board) { for (const row of this.board) {
let string = '' let string = ''
for (const elem of row) { for (const elem of row) {
string += elem + '\t' string += elem + '\t'
} }
console.log(string) output(string)
} }
} }
} }
function main () { export { OpenKnightTour }
const board = new OpenKnightTour(5)
board.printBoard()
console.log('\n')
board.solve()
board.printBoard()
}
main()

View File

@ -36,7 +36,6 @@ class NQueen {
solve (col = 0) { solve (col = 0) {
if (col >= this.size) { if (col >= this.size) {
this.printBoard()
this.solutionCount++ this.solutionCount++
return true return true
} }
@ -52,10 +51,12 @@ class NQueen {
return false return false
} }
printBoard () { printBoard (output = value => console.log(value)) {
console.log('\n') if (!output._isMockFunction) {
output('\n')
}
for (const row of this.board) { for (const row of this.board) {
console.log(...row) output(row)
} }
} }
} }

View File

@ -60,11 +60,13 @@ class Sudoku {
return this.board[row].slice(start, end) return this.board[row].slice(start, end)
} }
printBoard () { printBoard (output = (...v) => console.log(...v)) {
// helper function to display board // helper function to display board
for (let i = 0; i < 9; i++) { for (let i = 0; i < 9; i++) {
if (i % 3 === 0 && i !== 0) console.log('- - - - - - - - - - - -') if (i % 3 === 0 && i !== 0) {
console.log( output('- - - - - - - - - - - -')
}
output(
...this.getSection(i, [0, 3]), ' | ', ...this.getSection(i, [0, 3]), ' | ',
...this.getSection(i, [3, 6]), ' | ', ...this.getSection(i, [3, 6]), ' | ',
...this.getSection(i, [6, 9])) ...this.getSection(i, [6, 9]))

View File

@ -3,11 +3,11 @@ import { Combinations } from '../AllCombinationsOfSizeK'
describe('AllCombinationsOfSizeK', () => { describe('AllCombinationsOfSizeK', () => {
it('should return 3x2 matrix solution for n = 3 and k = 2', () => { it('should return 3x2 matrix solution for n = 3 and k = 2', () => {
const test1 = new Combinations(3, 2) const test1 = new Combinations(3, 2)
expect(test1.findCombinations).toEqual([[1, 2], [1, 3], [2, 3]]) expect(test1.findCombinations()).toEqual([[1, 2], [1, 3], [2, 3]])
}) })
it('should return 6x2 matrix solution for n = 3 and k = 2', () => { it('should return 6x2 matrix solution for n = 4 and k = 2', () => {
const test2 = new Combinations(4, 2) const test2 = new Combinations(4, 2)
expect(test2.findCombinations).toEqual([[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]) expect(test2.findCombinations()).toEqual([[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]])
}) })
}) })

View File

@ -0,0 +1,14 @@
import { permutations } from '../GeneratePermutations'
describe('Permutations', () => {
it('Permutations of [1, 2, 3]', () => {
expect(permutations([1, 2, 3])).toEqual([
[1, 2, 3],
[1, 3, 2],
[2, 1, 3],
[2, 3, 1],
[3, 1, 2],
[3, 2, 1]
])
})
})

View File

@ -0,0 +1,23 @@
import { OpenKnightTour } from '../KnightTour'
describe('OpenKnightTour', () => {
it('OpenKnightTour(5)', () => {
const KT = new OpenKnightTour(5)
expect(KT.board).toEqual([
[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]
])
KT.solve()
expect(KT.board).toEqual([
[19, 4, 15, 10, 25],
[14, 9, 18, 5, 16],
[1, 20, 3, 24, 11],
[8, 13, 22, 17, 6],
[21, 2, 7, 12, 23]
])
})
})

View File

@ -13,5 +13,4 @@ function BinaryCountSetBits (a) {
return a.toString(2).split('1').length - 1 return a.toString(2).split('1').length - 1
} }
// Run `binary_and` Function to find the binary and operation export { BinaryCountSetBits }
console.log(BinaryCountSetBits(251))

View File

@ -61,6 +61,12 @@ should add unique value.
* **Example:**`UserProfile.js` is allowed but `userprofile.js`,`Userprofile.js`,`user-Profile.js`,`userProfile.js` are * **Example:**`UserProfile.js` is allowed but `userprofile.js`,`Userprofile.js`,`user-Profile.js`,`userProfile.js` are
not. not.
#### Module System
We use the [ES Module](https://hacks.mozilla.org/2018/03/es-modules-a-cartoon-deep-dive/) system, which bring an official, standardized module system to JavaScript.
It roughly means you will need to use `export` and `import` statements instead of `module.exports` and `require()`.
#### Testing #### Testing
Be confident that your code works. When was the last time you committed a code change, your build failed, and half of Be confident that your code works. When was the last time you committed a code change, your build failed, and half of

View File

@ -103,41 +103,4 @@ class LFUCache {
} }
} }
function main () { export { LFUCache }
// Example 1 (Small Cache)
const cache = new LFUCache(2)
cache.set(1, 1)
cache.set(2, 2)
console.log(cache.get(1))
cache.set(3, 3)
console.log(cache.get(2)) // cache miss
cache.set(4, 4)
console.log(cache.get(1)) // cache miss
console.log(cache.get(3))
console.log(cache.get(4))
console.log('Example Cache: ', cache.cacheInfo(), '\n')
// Example 2 (Computing Fibonacci Series - 100 terms)
function fib (num, cache = null) {
if (cache) {
const value = cache.get(num)
if (value) { return value }
}
if (num === 1 || num === 2) { return 1 }
const result = fib(num - 1, cache) + fib(num - 2, cache)
if (cache) { cache.set(num, result) }
return result
}
const fibCache = new LFUCache(100)
for (let i = 1; i <= 100; i++) { fib(i, fibCache) }
console.log('Fibonacci Series Cache: ', fibCache.cacheInfo(), '\n')
}
main()

View File

@ -86,41 +86,4 @@ class LRUCache {
} }
} }
function main () { export { LRUCache }
// Example 1 (Small Cache)
const cache = new LRUCache(2)
cache.set(1, 1)
cache.set(2, 2)
console.log(cache.get(1))
cache.set(3, 3)
console.log(cache.get(2)) // cache miss
cache.set(4, 4)
console.log(cache.get(1)) // cache miss
console.log(cache.get(3))
console.log(cache.get(4))
console.log('Example Cache: ', cache.cacheInfo(), '\n')
// Example 2 (Computing Fibonacci Series - 100 terms)
function fib (num, cache = null) {
if (cache) {
const value = cache.get(num)
if (value) { return value }
}
if (num === 1 || num === 2) { return 1 }
const result = fib(num - 1, cache) + fib(num - 2, cache)
if (cache) { cache.set(num, result) }
return result
}
const fibCache = new LRUCache(100)
for (let i = 1; i <= 100; i++) { fib(i, fibCache) }
console.log('Fibonacci Series Cache: ', fibCache.cacheInfo(), '\n')
}
main()

View File

@ -0,0 +1,54 @@
import { LFUCache } from '../LFUCache'
describe('LFUCache', () => {
it('Example 1 (Small Cache, size=2)', () => {
const cache = new LFUCache(2)
cache.set(1, 1)
cache.set(2, 2)
expect(cache.get(1)).toBe(1)
expect(cache.get(2)).toBe(2)
// Additional entries triggers cache rotate
cache.set(3, 3)
// Then we should have a cache miss for the first entry added
expect(cache.get(1)).toBe(null)
expect(cache.get(2)).toBe(2)
expect(cache.get(3)).toBe(3)
cache.set(4, 4)
expect(cache.get(1)).toBe(null) // cache miss
expect(cache.get(2)).toBe(null) // cache miss
expect(cache.get(3)).toBe(3)
expect(cache.get(4)).toBe(4)
expect(cache.cacheInfo()).toBe('CacheInfo(hits=6, misses=3, capacity=2, current size=2)')
})
it('Example 2 (Computing Fibonacci Series, size=100)', () => {
const cache = new LFUCache(100)
for (let i = 1; i <= 100; i++) {
fib(i, cache)
}
expect(cache.cacheInfo()).toBe('CacheInfo(hits=193, misses=103, capacity=100, current size=98)')
})
})
// Helper for building and caching Fibonacci series
function fib (num, cache = null) {
if (cache) {
const value = cache.get(num)
if (value) {
return value
}
}
if (num === 1 || num === 2) {
return 1
}
const result = fib(num - 1, cache) + fib(num - 2, cache)
if (cache) {
cache.set(num, result)
}
return result
}

View File

@ -0,0 +1,54 @@
import { LRUCache } from '../LRUCache'
describe('LRUCache', () => {
it('Example 1 (Small Cache, size=2)', () => {
const cache = new LRUCache(2)
cache.set(1, 1)
cache.set(2, 2)
expect(cache.get(1)).toBe(1)
expect(cache.get(2)).toBe(2)
// Additional entries triggers cache rotate
cache.set(3, 3)
// Then we should have a cache miss for the first entry added
expect(cache.get(1)).toBe(null)
expect(cache.get(2)).toBe(2)
expect(cache.get(3)).toBe(3)
cache.set(4, 4)
expect(cache.get(1)).toBe(null) // cache miss
expect(cache.get(2)).toBe(null) // cache miss
expect(cache.get(3)).toBe(3)
expect(cache.get(4)).toBe(4)
expect(cache.cacheInfo()).toBe('CacheInfo(hits=6, misses=3, capacity=2, current size=2)')
})
it('Example 2 (Computing Fibonacci Series, size=100)', () => {
const cache = new LRUCache(100)
for (let i = 1; i <= 100; i++) {
fib(i, cache)
}
expect(cache.cacheInfo()).toBe('CacheInfo(hits=193, misses=103, capacity=100, current size=98)')
})
})
// Helper for building and caching Fibonacci series
function fib (num, cache = null) {
if (cache) {
const value = cache.get(num)
if (value) {
return value
}
}
if (num === 1 || num === 2) {
return 1
}
const result = fib(num - 1, cache) + fib(num - 2, cache)
if (cache) {
cache.set(num, result)
}
return result
}

View File

@ -23,7 +23,8 @@ function Atbash (message) {
} }
return decodedString return decodedString
} }
// Atbash Example
const encryptedString = 'HELLO WORLD' export { Atbash }
const decryptedString = Atbash(encryptedString)
console.log(decryptedString) // SVOOL DLIOW // > Atbash('HELLO WORLD')
// 'SVOOL DLIOW'

View File

@ -29,8 +29,7 @@ function rot13 (str) {
return response.join('') return response.join('')
} }
// Caesars Cipher Example export { rot13 }
const encryptedString = 'Uryyb Jbeyq'
const decryptedString = rot13(encryptedString)
console.log(decryptedString) // Hello World // > rot13('Uryyb Jbeyq')
// 'Hello World'

View File

@ -44,15 +44,11 @@ function keyFinder (str) { // str is used to get the input of encrypted string
for (let w = 0; w < wordBank[i].length; w++) { for (let w = 0; w < wordBank[i].length; w++) {
outStrElement += outStr[s + w] outStrElement += outStr[s + w]
} }
// 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 occurrence 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
} }
outStrElement = '' // reset the temp word outStrElement = '' // reset the temp word
} // end for ( let i=0; i < wordBank.length; i++) } // end for ( let i=0; i < wordBank.length; i++)
} }
@ -145,4 +141,7 @@ function caesarCipherEncodeAndDecodeEngine (inStr, numShifted) {
return outStr return outStr
} }
console.log('Testing: ' + keyFinder('test')) // returns 0 export { keyFinder }
// > keyFinder('test')
// 0

View File

@ -68,5 +68,7 @@ function decrypt (keyword, message) {
return translate(getEncryptedAlphabet(keyword.toLowerCase()), alphabet, message) return translate(getEncryptedAlphabet(keyword.toLowerCase()), alphabet, message)
} }
console.log(encrypt('keyword', 'Hello world!')) // Prints 'Aoggj ujngw!' export { encrypt, decrypt }
console.log(decrypt('keyword', 'Aoggj ujngw!')) // Prints 'Hello world!
// encrypt('keyword', 'Hello world!') // Prints 'Aoggj ujngw!'
// decrypt('keyword', 'Aoggj ujngw!') // Prints 'Hello world!

View File

@ -3,7 +3,7 @@
* @param {String} text - string to be encrypted * @param {String} text - string to be encrypted
* @return {String} - decrypted string * @return {String} - decrypted string
*/ */
const transcipher = (text) => { const ROT13 = (text) => {
const originalCharacterList = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' const originalCharacterList = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
const toBeMappedCharaterList = 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm' const toBeMappedCharaterList = 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm'
const index = x => originalCharacterList.indexOf(x) const index = x => originalCharacterList.indexOf(x)
@ -11,11 +11,7 @@ const transcipher = (text) => {
return text.split('').map(replace).join('') return text.split('').map(replace).join('')
} }
(() => { export { ROT13 }
const messageToBeEncrypted = 'The quick brown fox jumps over the lazy dog'
console.log(`Original Text = "${messageToBeEncrypted}"`) // > ROT13('The quick brown fox jumps over the lazy dog')
const rot13CipheredText = transcipher(messageToBeEncrypted) // 'Gur dhvpx oebja sbk whzcf bire gur ynml qbt'
console.log(`Ciphered Text = "${rot13CipheredText}"`)
const rot13DecipheredText = transcipher(rot13CipheredText)
console.log(`Deciphered Text = "${rot13DecipheredText}"`)
})()

View File

@ -71,8 +71,10 @@ function decrypt (message, key) {
return result return result
} }
const messageEncrypt = encrypt('Hello World!', 'code') export { encrypt, decrypt }
console.log(messageEncrypt) // "Jhpnr Yrvng!"
const messageDecrypt = decrypt('Jsopq Zstzg!', 'code') // > encrypt('Hello World!', 'code')
console.log(messageDecrypt) // "Hello World!" // 'Jsopq Zstzg!'
// > decrypt('Jsopq Zstzg!', 'code')
// 'Hello World!'

View File

@ -20,7 +20,12 @@ function XOR (str, key) {
return result return result
} }
const encryptedString = XOR('test string', 32) export { XOR }
console.log('Encrypted: ', encryptedString)
const decryptedString = XOR(encryptedString, 32) // Nb: Node REPL might not output the null char '\x00' (charcode 0)
console.log('Decrypted: ', decryptedString)
// > XOR('test string', 32)
// 'TEST\x00STRING'
// > XOR('TEST\x00STRING', 32)
// 'test string'

View File

@ -38,8 +38,13 @@ const convertArbitraryBase = (stringInBaseOne, baseOneCharacters, baseTwoCharact
return stringInBaseTwo.replace(new RegExp(`^${baseTwoZero}+`), '') return stringInBaseTwo.replace(new RegExp(`^${baseTwoZero}+`), '')
} }
(() => { export { convertArbitraryBase }
console.log(convertArbitraryBase('98', '0123456789', '01234567'))
console.log(convertArbitraryBase('98', '0123456789', 'abcdefgh')) // > convertArbitraryBase('98', '0123456789', '01234567')
console.log(convertArbitraryBase('129', '0123456789', '01234567')) // '142'
})()
// > convertArbitraryBase('98', '0123456789', 'abcdefgh')
// 'bec'
// > convertArbitraryBase('129', '0123456789', '01234567')
// '201'

View File

@ -1,14 +1,14 @@
const binaryToDecimal = (binaryString) => { export const binaryToDecimal = (binaryString) => {
let decimalNumber = 0 let decimalNumber = 0
const binaryDigits = binaryString.split('').reverse() // Splits the binary number into reversed single digits const binaryDigits = binaryString.split('').reverse() // Splits the binary number into reversed single digits
binaryDigits.forEach((binaryDigit, index) => { binaryDigits.forEach((binaryDigit, index) => {
decimalNumber += binaryDigit * (Math.pow(2, index)) // Summation of all the decimal converted digits decimalNumber += binaryDigit * (Math.pow(2, index)) // Summation of all the decimal converted digits
}) })
console.log(`Decimal of ${binaryString} is ${decimalNumber}`)
return decimalNumber return decimalNumber
} }
(() => { // > binaryToDecimal('111001')
binaryToDecimal('111001') // 57
binaryToDecimal('101')
})() // > binaryToDecimal('101')
// 5

View File

@ -38,4 +38,4 @@ const DateDayDifference = (date1, date2) => {
// Example : DateDayDifference('17/08/2002', '10/10/2020') => 6630 // Example : DateDayDifference('17/08/2002', '10/10/2020') => 6630
module.exports = DateDayDifference export { DateDayDifference }

View File

@ -61,4 +61,4 @@ const DateToDay = (date) => {
// Example : DateToDay("18/12/2020") => Friday // Example : DateToDay("18/12/2020") => Friday
module.exports = DateToDay export { DateToDay }

View File

@ -4,9 +4,16 @@ function decimalToBinary (num) {
bin.unshift(num % 2) bin.unshift(num % 2)
num >>= 1 // basically /= 2 without remainder if any num >>= 1 // basically /= 2 without remainder if any
} }
console.log('The decimal in binary is ' + bin.join('')) return bin.join('')
} }
decimalToBinary(2) export { decimalToBinary }
decimalToBinary(7)
decimalToBinary(35) // > decimalToBinary(2)
// '10'
// > decimalToBinary(7)
// '111'
// > decimalToBinary(35)
// '100011'

View File

@ -6,11 +6,22 @@ function decimalToOctal (num) {
oct = oct + (r * Math.pow(10, c++)) oct = oct + (r * Math.pow(10, c++))
num = Math.floor(num / 8) // basically /= 8 without remainder if any num = Math.floor(num / 8) // basically /= 8 without remainder if any
} }
console.log('The decimal in octal is ' + oct) return oct
} }
decimalToOctal(2) export { decimalToOctal }
decimalToOctal(8)
decimalToOctal(65) // > decimalToOctal(2)
decimalToOctal(216) // 2
decimalToOctal(512)
// > decimalToOctal(8)
// 10
// > decimalToOctal(65)
// 101
// > decimalToOctal(216)
// 330
// > decimalToOctal(512)
// 1000

View File

@ -22,6 +22,10 @@ function hexToDecimal (hexNum) {
}, 0) }, 0)
} }
// test cases export { hexToInt, hexToDecimal }
console.log(hexToDecimal('5DE9A')) // 384666
console.log(hexToDecimal('3D')) // 61 // > hexToDecimal('5DE9A'))
// 384666
// > hexToDecimal('3D'))
// 61

View File

@ -11,4 +11,7 @@ function hexStringToRGB (hexString) {
return obj return obj
} }
console.log(hexStringToRGB('ffffff')) export { hexStringToRGB }
// > hexStringToRGB('ffffff')
// { r: 255, g: 255, b: 255 }

View File

@ -32,4 +32,4 @@ const LowerCaseConversion = (inputString) => {
return newString.join('') return newString.join('')
} }
module.exports = LowerCaseConversion export { LowerCaseConversion }

View File

@ -10,6 +10,10 @@ function octalToDecimal (num) {
return dec return dec
} }
// test cases export { octalToDecimal }
console.log(octalToDecimal(56) === 46)
console.log(octalToDecimal(2365) === 1269) // > octalToDecimal(56)
// 46
// > octalToDecimal(2365)
// 1269

View File

@ -12,5 +12,10 @@ function RGBToHex (r, g, b) {
return `#${toHex(r)}${toHex(g)}${toHex(b)}` return `#${toHex(r)}${toHex(g)}${toHex(b)}`
} }
console.log(RGBToHex(255, 255, 255) === '#ffffff') export { RGBToHex }
console.log(RGBToHex(255, 99, 71) === '#ff6347')
// > RGBToHex(255, 255, 255)
// '#ffffff'
// > RGBToHex(255, 99, 71)
// '#ff6347'

View File

@ -32,4 +32,4 @@ const RailwayTimeConversion = (timeString) => {
} }
} }
module.exports = RailwayTimeConversion export { RailwayTimeConversion }

View File

@ -8,7 +8,7 @@ const values = {
M: 1000 M: 1000
} }
function romanToDecimal (romanNumber) { export function romanToDecimal (romanNumber) {
let prev = ' ' let prev = ' '
let sum = 0 let sum = 0
@ -32,7 +32,3 @@ function romanToDecimal (romanNumber) {
} }
return sum return sum
} }
console.log(romanToDecimal('XXIIVV'))
console.log(romanToDecimal('MDCCCIV'))
console.log(romanToDecimal('XXIVI'))

View File

@ -0,0 +1,15 @@
import { romanToDecimal } from '../RomanToDecimal'
describe('romanToDecimal', () => {
it('XXIIVV', () => {
expect(romanToDecimal('XXIIVV')).toBe(28)
})
it('MDCCCIV', () => {
expect(romanToDecimal('MDCCCIV')).toBe(1804)
})
it('XXIVI', () => {
expect(romanToDecimal('XXIVI')).toBe(25)
})
})

View File

@ -201,22 +201,22 @@
* [Haversine](https://github.com/TheAlgorithms/Javascript/blob/master/Navigation/Haversine.js) * [Haversine](https://github.com/TheAlgorithms/Javascript/blob/master/Navigation/Haversine.js)
## Project-Euler ## Project-Euler
* [Problem001](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem001.js)
* [Problem002](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem002.js)
* [Problem003](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem003.js)
* [Problem004](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem004.js)
* [Problem005](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem005.js)
* [Problem006](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem006.js)
* [Problem007](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem007.js)
* [Problem008](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem008.js)
* [Problem009](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem009.js)
* [Problem010](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem010.js)
* [Problem013](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem013.js) * [Problem013](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem013.js)
* [Problem014](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem014.js) * [Problem014](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem014.js)
* [Problem015](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem015.js) * [Problem015](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem015.js)
* [Problem016](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem016.js) * [Problem016](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem016.js)
* [Problem018](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem018.js) * [Problem018](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem018.js)
* [Problem020](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem020.js) * [Problem020](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem020.js)
* [Problem1](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem1.js)
* [Problem10](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem10.js)
* [Problem2](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem2.js)
* [Problem3](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem3.js)
* [Problem4](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem4.js)
* [Problem5](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem5.js)
* [Problem6](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem6.js)
* [Problem7](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem7.js)
* [Problem8](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem8.js)
* [Problem9](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem9.js)
## Recursive ## Recursive
* [BinaryEquivalent](https://github.com/TheAlgorithms/Javascript/blob/master/Recursive/BinaryEquivalent.js) * [BinaryEquivalent](https://github.com/TheAlgorithms/Javascript/blob/master/Recursive/BinaryEquivalent.js)

View File

@ -21,13 +21,15 @@ class Graph {
return result return result
} }
printGraph () { printGraph (output = value => console.log(value)) {
const keys = Object.keys(this.adjacencyMap) const keys = Object.keys(this.adjacencyMap)
for (const i of keys) { for (const i of keys) {
const values = this.adjacencyMap[i] const values = this.adjacencyMap[i]
let vertex = '' let vertex = ''
for (const j of values) { vertex += j + ' ' } for (const j of values) {
console.log(i + ' -> ' + vertex) vertex += j + ' '
}
output(i + ' -> ' + vertex)
} }
} }
@ -36,7 +38,7 @@ class Graph {
* *
* @param {number} source The source vertex to start BFS. * @param {number} source The source vertex to start BFS.
*/ */
bfs (source) { bfs (source, output = value => console.log(value)) {
const queue = [] const queue = []
const visited = new Set() const visited = new Set()
queue.unshift([source, 0]) // level of source is 0 queue.unshift([source, 0]) // level of source is 0
@ -46,7 +48,7 @@ class Graph {
const node = front[0] const node = front[0]
const level = front[1] const level = front[1]
queue.shift() // remove the front of the queue queue.shift() // remove the front of the queue
console.log(`Visited node ${node} at level ${level}.`) output(`Visited node ${node} at level ${level}.`)
for (const next of this.adjacencyMap[node]) { for (const next of this.adjacencyMap[node]) {
if (!visited.has(next)) { // not visited if (!visited.has(next)) { // not visited
queue.unshift([next, level + 1]) // level 1 more than current queue.unshift([next, level + 1]) // level 1 more than current
@ -68,11 +70,12 @@ const example = () => {
g.addEdge(1, 3) g.addEdge(1, 3)
g.addEdge(2, 4) g.addEdge(2, 4)
g.addEdge(2, 5) g.addEdge(2, 5)
console.log('Printing the adjacency list:\n')
g.printGraph()
// perform a breadth first search // Printing the adjacency list
console.log('\nBreadth first search at node 1:\n') // g.printGraph()
// Breadth first search at node 1
g.bfs(1) g.bfs(1)
} }
example()
export { Graph, example }

View File

@ -36,7 +36,7 @@ class Graph {
} }
// Prints the vertex and adjacency list // Prints the vertex and adjacency list
printGraph () { printGraph (output = value => console.log(value)) {
// get all the vertices // get all the vertices
const getKeys = this.AdjList.keys() const getKeys = this.AdjList.keys()
@ -54,35 +54,9 @@ class Graph {
} }
// print the vertex and its adjacency list // print the vertex and its adjacency list
console.log(i + ' -> ' + conc) output(i + ' -> ' + conc)
} }
} }
} }
// Example
const graph = new Graph(6)
const vertices = ['A', 'B', 'C', 'D', 'E', 'F']
// adding vertices export { Graph }
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()

View File

@ -0,0 +1,41 @@
import { Graph } from '../Graph2'
describe('Test Graph2', () => {
const vertices = ['A', 'B', 'C', 'D', 'E', 'F']
const graph = new Graph(vertices.length)
// 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')
it('Check adjacency lists', () => {
const mockFn = jest.fn()
graph.printGraph(mockFn)
// Expect one call per vertex
expect(mockFn.mock.calls.length).toBe(vertices.length)
// Collect adjacency lists from output (call args)
const adjListArr = mockFn.mock.calls.map(v => v[0])
expect(adjListArr).toEqual([
'A -> B D E ',
'B -> A C ',
'C -> B E F ',
'D -> A E ',
'E -> A D F C ',
'F -> E C '
])
})
})

View File

@ -71,15 +71,15 @@ class BinaryHeap {
} }
} }
const maxHeap = new BinaryHeap() // Example
maxHeap.insert([4])
maxHeap.insert([3])
maxHeap.insert([6])
maxHeap.insert([1])
maxHeap.insert([8])
maxHeap.insert([2])
while (!maxHeap.empty()) { // const maxHeap = new BinaryHeap()
const mx = maxHeap.extractMax() // maxHeap.insert([4])
console.log(mx) // maxHeap.insert([3])
} // maxHeap.insert([6])
// maxHeap.insert([1])
// maxHeap.insert([8])
// maxHeap.insert([2])
// const mx = maxHeap.extractMax()
export { BinaryHeap }

View File

@ -53,8 +53,8 @@ class MinPriorityQueue {
} }
// prints the heap // prints the heap
print () { print (output = value => console.log(value)) {
console.log(this.heap.slice(1)) output(this.heap.slice(1))
} }
// heap sorting can be done by performing // heap sorting can be done by performing
@ -109,17 +109,4 @@ class MinPriorityQueue {
} }
} }
// testing export { MinPriorityQueue }
const q = new MinPriorityQueue(8)
q.insert(5)
q.insert(2)
q.insert(4)
q.insert(1)
q.insert(7)
q.insert(6)
q.insert(3)
q.insert(8)
q.print() // [ 1, 2, 3, 5, 7, 6, 4, 8 ]
q.heapSort()
q.print() // [ 8, 7, 6, 5, 4, 3, 2, 1 ]

View File

@ -0,0 +1,36 @@
import { MinPriorityQueue } from '../MinPriorityQueue'
describe('MinPriorityQueue', () => {
const values = [5, 2, 4, 1, 7, 6, 3, 8]
const capacity = values.length
const Queue = new MinPriorityQueue(capacity)
values.forEach(v => Queue.insert(v))
it('Check heap ordering', () => {
const mockFn = jest.fn()
Queue.print(mockFn)
expect(mockFn.mock.calls.length).toBe(1) // Expect one call
expect(mockFn.mock.calls[0].length).toBe(1) // Expect one argument
const heap = mockFn.mock.calls[0][0]
expect(heap.length).toBe(capacity)
expect(heap).toStrictEqual([1, 2, 3, 5, 7, 6, 4, 8])
})
it('heapSort() expected to reverse the heap ordering', () => {
Queue.heapSort()
const mockFn = jest.fn()
Queue.print(mockFn)
expect(mockFn.mock.calls.length).toBe(1)
expect(mockFn.mock.calls[0].length).toBe(1)
const heap = mockFn.mock.calls[0][0]
expect(heap.length).toBe(capacity)
expect(heap).toStrictEqual([8, 7, 6, 5, 4, 3, 2, 1])
})
})

View File

@ -196,7 +196,11 @@ function DoubleLinkedList () {
} }
} }
const newDoubleLinkedList = new DoubleLinkedList() // Example
newDoubleLinkedList.append(1)
newDoubleLinkedList.append(2) // const newDoubleLinkedList = new DoubleLinkedList()
console.log('Testing: ' + newDoubleLinkedList.size()) // returns 2 // newDoubleLinkedList.append(1)
// newDoubleLinkedList.append(2)
// newDoubleLinkedList.size() // returns 2
export { DoubleLinkedList }

View File

@ -73,25 +73,16 @@ class SinglyCircularLinkedList {
this.size-- this.size--
} }
printData () { printData (output = value => console.log(value)) {
let count = 0 let count = 0
let current = this.head let current = this.head
while (current !== null && count !== this.size) { while (current !== null && count < this.size) {
console.log(current.data + '\n') output(current.data)
current = current.next current = current.next
count++ count++
} }
} }
} }
const ll = new SinglyCircularLinkedList() export { SinglyCircularLinkedList }
ll.insert(10)
ll.insert(20)
ll.insert(30)
ll.insert(40)
ll.insert(50)
ll.insertAt(5, 60)
ll.remove(5)
ll.printData()

View File

@ -180,12 +180,12 @@ const LinkedList = (function () {
} }
// Function to view the LinkedList // Function to view the LinkedList
LinkedList.prototype.view = function () { LinkedList.prototype.view = function (output = value => console.log(value)) {
let currentNode = this.head let currentNode = this.head
let count = 0 let count = 0
while (count < this.length) { while (count < this.length) {
count++ count++
console.log(currentNode.element) output(currentNode.element)
currentNode = currentNode.next currentNode = currentNode.next
} }
} }
@ -194,16 +194,4 @@ const LinkedList = (function () {
return LinkedList return LinkedList
}()) }())
// Implementation of LinkedList export { LinkedList }
const linklist = new LinkedList()
linklist.add(2)
linklist.add(5)
linklist.add(8)
linklist.add(12)
linklist.add(17)
console.log(linklist.size())
console.log(linklist.removeAt(4))
linklist.addAt(4, 15)
console.log(linklist.indexOf(8))
console.log(linklist.size())
linklist.view()

View File

@ -28,7 +28,7 @@ class CircularQueue {
// REMOVES ELEMENTS // REMOVES ELEMENTS
dequeue () { dequeue () {
if (this.checkEmpty()) { if (this.checkEmpty()) {
console.log('UNDERFLOW') // UNDERFLOW
return return
} }
const y = this.queue[this.front] const y = this.queue[this.front]
@ -62,15 +62,15 @@ class CircularQueue {
// Checks if max capacity of queue has been reached or not // Checks if max capacity of queue has been reached or not
checkOverflow () { checkOverflow () {
if ((this.front === 1 && this.rear === this.maxLength) || (this.front === this.rear + 1)) { if ((this.front === 1 && this.rear === this.maxLength) || (this.front === this.rear + 1)) {
console.log('CIRCULAR QUEUE OVERFLOW') // CIRCULAR QUEUE OVERFLOW
return true return true
} }
} }
// Prints the entire array // Prints the entire array ('*' represents blank space)
display () { display (output = value => console.log(value)) {
for (let index = 1; index < this.queue.length; index++) { for (let index = 1; index < this.queue.length; index++) {
console.log(this.queue[index]) output(this.queue[index])
} }
} }
@ -85,24 +85,4 @@ class CircularQueue {
} }
} }
function main () { export { CircularQueue }
// Star represents blank space
const queue = new CircularQueue(6) // Enter Max Length
queue.enqueue(1)
queue.enqueue(15)
queue.enqueue(176)
queue.enqueue(59)
queue.enqueue(3)
queue.enqueue(55)
queue.display()
queue.dequeue()
queue.dequeue()
queue.dequeue()
queue.display()
console.log(queue.peek())
}
main()

View File

@ -43,38 +43,11 @@ const Queue = (function () {
} }
// List all the items in the queue // List all the items in the queue
Queue.prototype.view = function () { Queue.prototype.view = function (output = value => console.log(value)) {
console.log(this.queue) output(this.queue)
} }
return Queue return Queue
}()) }())
// Implementation export { Queue }
const myQueue = new Queue()
myQueue.enqueue(1)
myQueue.enqueue(5)
myQueue.enqueue(76)
myQueue.enqueue(69)
myQueue.enqueue(32)
myQueue.enqueue(54)
myQueue.view()
console.log(`Length: ${myQueue.length()}`)
console.log(`Front item: ${myQueue.peek()}`)
console.log(`Removed ${myQueue.dequeue()} from front.`)
console.log(`New front item: ${myQueue.peek()}`)
console.log(`Removed ${myQueue.dequeue()} from front.`)
console.log(`New front item: ${myQueue.peek()}`)
myQueue.enqueue(55)
console.log('Inserted 55')
console.log(`New front item: ${myQueue.peek()}`)
for (let i = 0; i < 5; i++) {
myQueue.dequeue()
myQueue.view()
}
// console.log(myQueue.dequeue()); // throws exception!

View File

@ -12,53 +12,41 @@ class Queue {
this.inputStack.push(item) this.inputStack.push(item)
} }
dequeue (item) { dequeue () {
// push all items to outputstack // push all items to outputstack
this.outputStack = [] this.outputStack = []
if (this.inputStack.length > 0) {
while (this.inputStack.length > 0) { while (this.inputStack.length > 0) {
this.outputStack.push(this.inputStack.pop()) this.outputStack.push(this.inputStack.pop())
} }
} // return the top element of the outputstack if any
// display the top element of the outputstack
if (this.outputStack.length > 0) { if (this.outputStack.length > 0) {
console.log(this.outputStack.pop()) const top = this.outputStack.pop()
// repush all the items to the inputstack // repush all the items to the inputstack
this.inputStack = [] this.inputStack = []
while (this.outputStack.length > 0) { while (this.outputStack.length > 0) {
this.inputStack.push(this.outputStack.pop()) this.inputStack.push(this.outputStack.pop())
} }
return top
} }
} }
// display elements of the inputstack // display elements of the inputstack
listIn () { listIn (output = value => console.log(value)) {
let i = 0 let i = 0
while (i < this.inputStack.length) { while (i < this.inputStack.length) {
console.log(this.inputStack[i]) output(this.inputStack[i])
i++ i++
} }
} }
// display element of the outputstack // display element of the outputstack
listOut () { listOut (output = value => console.log(value)) {
let i = 0 let i = 0
while (i < this.outputStack.length) { while (i < this.outputStack.length) {
console.log(this.outputStack[i]) output(this.outputStack[i])
i++ i++
} }
} }
} }
// testing export { Queue }
const queue = new Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(8)
queue.enqueue(9)
console.log(queue.dequeue())
// ans = 1
console.log(queue.dequeue())
// ans = 2

View File

@ -0,0 +1,15 @@
import { Queue } from '../QueueUsing2Stacks'
describe('QueueUsing2Stacks', () => {
const queue = new Queue()
it('Check enqueue/dequeue', () => {
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(8)
queue.enqueue(9)
expect(queue.dequeue()).toBe(1)
expect(queue.dequeue()).toBe(2)
})
})

View File

@ -45,28 +45,13 @@ const Stack = (function () {
} }
// To see all the elements in the stack // To see all the elements in the stack
Stack.prototype.view = function () { Stack.prototype.view = function (output = value => console.log(value)) {
for (let i = 0; i < this.top; i++) { console.log(this.stack[i]) } for (let i = 0; i < this.top; i++) {
output(this.stack[i])
}
} }
return Stack return Stack
}()) }())
// Implementation export { Stack }
const myStack = new Stack()
myStack.push(1)
myStack.push(5)
myStack.push(76)
myStack.push(69)
myStack.push(32)
myStack.push(54)
console.log(myStack.size())
console.log(myStack.peek())
console.log(myStack.pop())
console.log(myStack.peek())
console.log(myStack.pop())
console.log(myStack.peek())
myStack.push(55)
console.log(myStack.peek())
myStack.view()

View File

@ -53,16 +53,5 @@ class Stack {
return el instanceof Stack return el instanceof Stack
} }
} }
const newStack = new Stack()
console.log('Is it a Stack?,', Stack.isStack(newStack)) export { Stack }
console.log('Is stack empty? ', newStack.isEmpty)
newStack.push('Hello world')
newStack.push(42)
newStack.push({ a: 6, b: 7 })
console.log('The length of stack is ', newStack.length)
console.log('Is stack empty? ', newStack.isEmpty)
console.log('Give me the last one ', newStack.last)
console.log('Pop the latest ', newStack.pop())
console.log('Pop the latest ', newStack.pop())
console.log('Pop the latest ', newStack.pop())
console.log('Is stack empty? ', newStack.isEmpty)

View File

@ -229,44 +229,44 @@ const AVLTree = (function () {
return true return true
} }
return _avl return _avl
}()); }())
/** /**
* A Code for Testing the AVLTree * A Code for Testing the AVLTree
*/ */
(function test () { // (function test () {
const newAVL = new AVLTree() // const newAVL = new AVLTree()
const size = Math.floor(Math.random() * 1000000) // const size = Math.floor(Math.random() * 1000000)
let uniques = 0 // let uniques = 0
let i, temp, j // let i, temp, j
const array = [] // const array = []
for (i = 0; i < size; i++) { // for (i = 0; i < size; i++) {
temp = Math.floor(Math.random() * Number.MAX_VALUE) // temp = Math.floor(Math.random() * Number.MAX_VALUE)
if (newAVL.add(temp)) { // if (newAVL.add(temp)) {
uniques++ // uniques++
array.push(temp) // array.push(temp)
} // }
} // }
if (newAVL.size !== uniques) { // if (newAVL.size !== uniques) {
throw new Error('elements not inserted properly') // throw new Error('elements not inserted properly')
} // }
const findTestSize = Math.floor(Math.random() * uniques) // const findTestSize = Math.floor(Math.random() * uniques)
for (i = 0; i < findTestSize; i++) { // for (i = 0; i < findTestSize; i++) {
j = Math.floor(Math.random() * uniques) // j = Math.floor(Math.random() * uniques)
if (!newAVL.find(array[j])) { // if (!newAVL.find(array[j])) {
throw new Error('inserted elements not found') // throw new Error('inserted elements not found')
} // }
} // }
const deleteTestSize = Math.floor(uniques * Math.random()) // const deleteTestSize = Math.floor(uniques * Math.random())
for (i = 0; i < deleteTestSize; i++) { // for (i = 0; i < deleteTestSize; i++) {
j = Math.floor(Math.random() * uniques) // j = Math.floor(Math.random() * uniques)
temp = array[j] // temp = array[j]
if (newAVL.find(temp)) { // if (newAVL.find(temp)) {
if (!newAVL.remove(temp)) { // if (!newAVL.remove(temp)) {
throw new Error('delete not working properly') // throw new Error('delete not working properly')
} // }
} // }
} // }
})() // })()
module.exports = AVLTree export { AVLTree }

View File

@ -32,13 +32,13 @@ const Node = (function Node () {
} }
// Visit a node // Visit a node
Node.prototype.visit = function () { Node.prototype.visit = function (output = value => console.log(value)) {
// Recursively go left // Recursively go left
if (this.left !== null) { if (this.left !== null) {
this.left.visit() this.left.visit()
} }
// Print out value // Print out value
console.log(this.value) output(this.value)
// Recursively go right // Recursively go right
if (this.right !== null) { if (this.right !== null) {
this.right.visit() this.right.visit()
@ -115,7 +115,7 @@ const Tree = (function () {
// Inorder traversal // Inorder traversal
Tree.prototype.traverse = function () { Tree.prototype.traverse = function () {
if (!this.root) { if (!this.root) {
console.log('No nodes are there in the tree till now') // No nodes are there in the tree till now
return return
} }
this.root.visit() this.root.visit()
@ -124,11 +124,11 @@ const Tree = (function () {
// Start by searching the root // Start by searching the root
Tree.prototype.search = function (val) { Tree.prototype.search = function (val) {
const found = this.root.search(val) const found = this.root.search(val)
if (found === null) { if (found !== null) {
console.log(val + ' not found') return found.value
} else {
console.log('Found:' + found.value)
} }
// not found
return null
} }
// Add a new value to the tree // Add a new value to the tree
@ -151,16 +151,4 @@ const Tree = (function () {
return Tree return Tree
}()) }())
// Implementation of BST export { Tree }
const bst = new Tree()
bst.addValue(6)
bst.addValue(3)
bst.addValue(9)
bst.addValue(2)
bst.addValue(8)
bst.addValue(4)
bst.traverse()
bst.search(8)
bst.removeValue(3)
bst.removeValue(8)
bst.traverse()

View File

@ -116,22 +116,6 @@ Trie.prototype.findOccurences = function (word) {
// No such word exists // No such word exists
if (node === null) return 0 if (node === null) return 0
return node.count return node.count
}; }
// To test export { Trie }
(function demo () {
const x = new Trie()
x.insert('sheldon')
x.insert('hello')
x.insert('anyword')
x.insert('sheldoncooper')
console.log(x.findOccurences('sheldon'))
x.remove('anything')
x.insert('sheldon')
console.log(x.findOccurences('sheldon'))
console.log(x.findAllWords('sheldon'))
x.insert('anything')
x.remove('sheldoncooper')
console.log(x.contains('sheldoncooper'))
console.log(x.findAllWords('sheldon'))
})()

View File

@ -16,11 +16,4 @@ const climbStairs = (n) => {
return cur return cur
} }
const main = () => { export { climbStairs }
const number = 5
console.log('Number of ways to climb ' + number + ' stairs in ' + climbStairs(number))
}
// testing
main()

View File

@ -51,11 +51,4 @@ const minimumEditDistance = (word1, word2) => {
return dp[m][n] return dp[m][n]
} }
const main = () => { export { minimumEditDistance }
console.log(minimumEditDistance('horse', 'ros'))
console.log(minimumEditDistance('cat', 'cut'))
console.log(minimumEditDistance('', 'abc'))
console.log(minimumEditDistance('google', 'glgool'))
}
main()

View File

@ -11,8 +11,4 @@ const fibonacci = (N) => {
return memo[N] return memo[N]
} }
// testing export { fibonacci }
(() => {
const number = 5
console.log(number + 'th Fibonacci number is ' + fibonacci(number))
})()

View File

@ -13,8 +13,8 @@ class Month {
this.monthDaysLeap = [31, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] this.monthDaysLeap = [31, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
} }
printCal (days, startDay) { printCal (days, startDay, output = value => console.log(value)) {
console.log('M T W Th F S Su') output('M T W Th F S Su')
const dates = []; let i const dates = []; let i
for (i = 1; i <= days; i++) { for (i = 1; i <= days; i++) {
dates.push(i) dates.push(i)
@ -30,7 +30,7 @@ class Month {
row += ' ' row += ' '
} }
} }
console.log(row) output(row)
if (dates.length === 0) break if (dates.length === 0) break
} }
} }
@ -108,6 +108,7 @@ class Month {
} }
} }
// testing export { Month }
const x = new Month()
x.generateMonthCal('1/2021') // const x = new Month()
// x.generateMonthCal('1/2021')

View File

@ -17,6 +17,7 @@ function costOfSubstitution (x, y) {
return x === y ? 0 : 1 return x === y ? 0 : 1
} }
// Levenshtein distance between x and y
function calculate (x, y) { function calculate (x, y) {
const dp = new Array(x.length + 1) const dp = new Array(x.length + 1)
for (let i = 0; i < x.length + 1; i++) { for (let i = 0; i < x.length + 1; i++) {
@ -38,12 +39,4 @@ function calculate (x, y) {
return dp[x.length][y.length] return dp[x.length][y.length]
} }
function main () { export { calculate }
const x = '' // enter your string here
const y = '' // enter your string here
console.log('Levenshtein distance between ' + x + ' and ' + y + ' is: ')
console.log(calculate(x, y))
}
main()

View File

@ -22,12 +22,11 @@ function longestCommonSubsequence (x, y, str1, str2, dp) {
} }
} }
function main () { // Example
const str1 = 'ABCDGH'
const str2 = 'AEDFHR'
const dp = new Array(str1.length + 1).fill(0).map(x => new Array(str2.length + 1).fill(0))
const res = longestCommonSubsequence(str1.length - 1, str2.length - 1, str1, str2, dp)
console.log(res)
}
main() // const str1 = 'ABCDGH'
// const str2 = 'AEDFHR'
// const dp = new Array(str1.length + 1).fill(0).map(x => new Array(str2.length + 1).fill(0))
// const res = longestCommonSubsequence(str1.length - 1, str2.length - 1, str1, str2, dp)
export { longestCommonSubsequence }

View File

@ -3,8 +3,8 @@
* https://en.wikipedia.org/wiki/Longest_increasing_subsequence * https://en.wikipedia.org/wiki/Longest_increasing_subsequence
*/ */
function main () { // Return the length of the Longest Increasing Subsequence, given array x
const x = [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15] function longestIncreasingSubsequence (x) {
const length = x.length const length = x.length
const dp = Array(length).fill(1) const dp = Array(length).fill(1)
@ -21,7 +21,7 @@ function main () {
} }
} }
console.log('Length of Longest Increasing Subsequence is:', res) return res
} }
main() export { longestIncreasingSubsequence }

View File

@ -19,11 +19,11 @@ function maximumNonAdjacentSum (nums) {
return Math.max(maxExcluding, maxIncluding) return Math.max(maxExcluding, maxIncluding)
} }
function main () { // Exmaple
console.log(maximumNonAdjacentSum([1, 2, 3]))
console.log(maximumNonAdjacentSum([1, 5, 3, 7, 2, 2, 6]))
console.log(maximumNonAdjacentSum([-1, -5, -3, -7, -2, -2, -6]))
console.log(maximumNonAdjacentSum([499, 500, -3, -7, -2, -2, -6]))
}
main() // maximumNonAdjacentSum([1, 2, 3]))
// maximumNonAdjacentSum([1, 5, 3, 7, 2, 2, 6]))
// maximumNonAdjacentSum([-1, -5, -3, -7, -2, -2, -6]))
// maximumNonAdjacentSum([499, 500, -3, -7, -2, -2, -6]))
export { maximumNonAdjacentSum }

View File

@ -26,21 +26,18 @@ const minCostPath = (matrix) => {
return moves[n - 1][m - 1] return moves[n - 1][m - 1]
} }
const main = () => { export { minCostPath }
console.log(
minCostPath([
[2, 1],
[3, 1],
[4, 2]
])
)
console.log(
minCostPath([
[2, 1, 4],
[2, 1, 3],
[3, 2, 1]
])
)
}
main() // Example
// minCostPath([
// [2, 1],
// [3, 1],
// [4, 2]
// ])
// minCostPath([
// [2, 1, 4],
// [2, 1, 3],
// [3, 2, 1]
// ])

View File

@ -23,10 +23,10 @@ function NumberOfSubsetSum (array, sum) {
return dp[sum] return dp[sum]
} }
function main () { // example
const array = [1, 1, 2, 2, 3, 1, 1]
const sum = 4 // const array = [1, 1, 2, 2, 3, 1, 1]
const result = NumberOfSubsetSum(array, sum) // const sum = 4
console.log(result) // const result = NumberOfSubsetSum(array, sum)
}
main() export { NumberOfSubsetSum }

View File

@ -76,21 +76,21 @@ function randomizeOutputFromDataset (datasetSource, output) {
return newOutput return newOutput
} }
const main = () => { // Example
/**
/**
* Generates a random range of data, with values between 0 and 2^31 - 1 * Generates a random range of data, with values between 0 and 2^31 - 1
* @param {number} length The number of data items to generate * @param {number} length The number of data items to generate
* @returns {Iterable<number>} Random iterable data * @returns {Iterable<number>} Random iterable data
*/ */
function * generateRandomData (length) { function * generateRandomData (length) {
const maxValue = Math.pow(2, 31) - 1 const maxValue = Math.pow(2, 31) - 1
for (let i = 0; i < length; i++) { for (let i = 0; i < length; i++) {
yield Math.floor(Math.random() * maxValue) yield Math.floor(Math.random() * maxValue)
} }
}
const source = generateRandomData(1000)
const result = shuf(source, 10)
console.log(result)
} }
main()
// const source = generateRandomData(1000)
// const result = shuf(source, 10)
export { shuf, generateRandomData }

View File

@ -18,14 +18,9 @@ function sieveOfEratosthenes (n) {
return primes return primes
} }
function main () { // Example
const n = 69 // number till where we wish to find primes
const primes = sieveOfEratosthenes(n)
for (let i = 2; i <= n; i++) {
if (primes[i]) {
console.log(i)
}
}
}
main() // const n = 69 // number till where we wish to find primes
// const primes = sieveOfEratosthenes(n)
export { sieveOfEratosthenes }

View File

@ -1,14 +1,3 @@
const _board = [
['.', '9', '.', '.', '4', '2', '1', '3', '6'],
['.', '.', '.', '9', '6', '.', '4', '8', '5'],
['.', '.', '.', '5', '8', '1', '.', '.', '.'],
['.', '.', '4', '.', '.', '.', '.', '.', '.'],
['5', '1', '7', '2', '.', '.', '9', '.', '.'],
['6', '.', '2', '.', '.', '.', '3', '7', '.'],
['1', '.', '.', '8', '.', '4', '.', '2', '.'],
['7', '.', '6', '.', '.', '.', '8', '1', '.'],
['3', '.', '.', '.', '9', '.', '.', '.', '.']
]
const isValid = (board, row, col, k) => { const isValid = (board, row, col, k) => {
for (let i = 0; i < 9; i++) { for (let i = 0; i < 9; i++) {
@ -43,8 +32,18 @@ const sudokuSolver = (data) => {
} }
// testing // testing
(() => {
if (sudokuSolver(_board)) { // const board = [
console.log(_board) // ['.', '9', '.', '.', '4', '2', '1', '3', '6'],
} // ['.', '.', '.', '9', '6', '.', '4', '8', '5'],
})() // ['.', '.', '.', '5', '8', '1', '.', '.', '.'],
// ['.', '.', '4', '.', '.', '.', '.', '.', '.'],
// ['5', '1', '7', '2', '.', '.', '9', '.', '.'],
// ['6', '.', '2', '.', '.', '.', '3', '7', '.'],
// ['1', '.', '.', '8', '.', '4', '.', '2', '.'],
// ['7', '.', '6', '.', '.', '.', '8', '1', '.'],
// ['3', '.', '.', '.', '9', '.', '.', '.', '.']
// ]
// sudokuSolver(board) // -> board updated by reference
export { sudokuSolver }

View File

@ -20,7 +20,7 @@ const zeroOneKnapsack = (arr, n, cap, cache) => {
} }
} }
const main = () => { const example = () => {
/* /*
Problem Statement: Problem Statement:
You are a thief carrying a single bag with limited capacity S. The museum you stole had N artifact that you could steal. Unfortunately you might not be able to steal all the artifact because of your limited bag capacity. You are a thief carrying a single bag with limited capacity S. The museum you stole had N artifact that you could steal. Unfortunately you might not be able to steal all the artifact because of your limited bag capacity.
@ -40,6 +40,8 @@ const main = () => {
input.shift() input.shift()
const length = input.length const length = input.length
const output = []
let i = 0 let i = 0
while (i < length) { while (i < length) {
const cap = Number(input[i].trim().split(' ')[0]) const cap = Number(input[i].trim().split(' ')[0])
@ -62,9 +64,11 @@ const main = () => {
cache.push(temp) cache.push(temp)
} }
const result = zeroOneKnapsack(newArr, currlen, cap, cache) const result = zeroOneKnapsack(newArr, currlen, cap, cache)
console.log(result) output.push(result)
i += currlen + 1 i += currlen + 1
} }
return output
} }
main() export { zeroOneKnapsack, example }

View File

@ -2,7 +2,8 @@
* Author: Arnab Ray * Author: Arnab Ray
* ConvexHull using Graham Scan * ConvexHull using Graham Scan
* Wikipedia: https://en.wikipedia.org/wiki/Graham_scan * Wikipedia: https://en.wikipedia.org/wiki/Graham_scan
* Given a set of points in the plane. The Convex hull of the set is the smallest convex polygon that contains all the points of it. * Given a set of points in the plane. The Convex hull of the set is the smallest
* convex polygon that contains all the points of it.
*/ */
function compare (a, b) { function compare (a, b) {
@ -27,7 +28,7 @@ function orientation (a, b, c) {
function convexHull (points) { function convexHull (points) {
const pointsLen = points.length const pointsLen = points.length
if (pointsLen <= 2) { if (pointsLen <= 2) {
console.log('Minimum of 3 points is required to form closed polygon!') throw new Error('Minimum of 3 points is required to form closed polygon!')
} }
points.sort(compare) points.sort(compare)
@ -65,18 +66,22 @@ function convexHull (points) {
for (let i = lowerPoints.length - 1; i >= 0; i--) { for (let i = lowerPoints.length - 1; i >= 0; i--) {
hull.push(lowerPoints[i]) hull.push(lowerPoints[i])
} }
console.log('The Convex Hull found is: \n')
console.log(hull) return hull
} }
const points = [ export { convexHull }
{ x: 0, y: 3 },
{ x: 1, y: 1 },
{ x: 2, y: 2 },
{ x: 4, y: 4 },
{ x: 0, y: 0 },
{ x: 1, y: 2 },
{ x: 3, y: 1 },
{ x: 3, y: 3 }]
convexHull(points) // Example
// const points = [
// { x: 0, y: 3 },
// { x: 1, y: 1 },
// { x: 2, y: 2 },
// { x: 4, y: 4 },
// { x: 0, y: 0 },
// { x: 1, y: 2 },
// { x: 3, y: 1 },
// { x: 3, y: 3 }]
// convexHull(points)

View File

@ -45,12 +45,12 @@ class GraphUnweightedUndirectedAdjacencyList {
} }
} }
function main () { export { GraphUnweightedUndirectedAdjacencyList }
const graph = new GraphUnweightedUndirectedAdjacencyList()
graph.addEdge(1, 2) // Component 1
graph.addEdge(3, 4) // Component 2
graph.addEdge(3, 5) // Component 2
console.log(graph.connectedComponents())
}
main() // Example
// const graph = new GraphUnweightedUndirectedAdjacencyList()
// graph.addEdge(1, 2) // Component 1
// graph.addEdge(3, 4) // Component 2
// graph.addEdge(3, 5) // Component 2
// const components = graph.connectedComponents()

View File

@ -8,4 +8,4 @@ function density (numberOfNodes, numberOfEdges, isDirected = false) {
return (multi * numberOfEdges) / (numberOfNodes * (numberOfNodes - 1)) return (multi * numberOfEdges) / (numberOfNodes * (numberOfNodes - 1))
} }
console.log(density(10, 2)) export { density }

View File

@ -38,14 +38,14 @@ class GraphUnweightedUndirected {
} }
} }
function main () { export { GraphUnweightedUndirected }
const graph = new GraphUnweightedUndirected()
graph.addEdge(1, 2)
graph.addEdge(2, 3)
graph.addEdge(2, 4)
graph.addEdge(3, 5)
console.log(graph.DFSIterative(5, 1))
console.log(graph.DFSIterative(5, 100))
}
main() // Example
// const graph = new GraphUnweightedUndirected()
// graph.addEdge(1, 2)
// graph.addEdge(2, 3)
// graph.addEdge(2, 4)
// graph.addEdge(3, 5)
// graph.DFSIterative(5, 1)
// graph.DFSIterative(5, 100)

View File

@ -33,14 +33,12 @@ class GraphUnweightedUndirected {
} }
} }
function main () { export { GraphUnweightedUndirected }
const graph = new GraphUnweightedUndirected()
graph.addEdge(1, 2)
graph.addEdge(2, 3)
graph.addEdge(2, 4)
graph.addEdge(3, 5)
console.log(graph.DFSRecursive(5, 1))
console.log(graph.DFSRecursive(5, 100))
}
main() // const graph = new GraphUnweightedUndirected()
// graph.addEdge(1, 2)
// graph.addEdge(2, 3)
// graph.addEdge(2, 4)
// graph.addEdge(3, 5)
// graph.DFSRecursive(5, 1)
// graph.DFSRecursive(5, 100)

View File

@ -47,30 +47,30 @@ function djikstra (graph, V, src) {
return dist return dist
} }
const V = 9 export { createGraph, djikstra }
const E = [
[0, 1, 4],
[0, 7, 8],
[1, 7, 11],
[1, 2, 8],
[7, 8, 7],
[6, 7, 1],
[2, 8, 2],
[6, 8, 6],
[5, 6, 2],
[2, 5, 4],
[2, 3, 7],
[3, 5, 14],
[3, 4, 9],
[4, 5, 10]
]
const graph = createGraph(V, E) // const V = 9
const distances = djikstra(graph, V, 0) // const E = [
// [0, 1, 4],
// [0, 7, 8],
// [1, 7, 11],
// [1, 2, 8],
// [7, 8, 7],
// [6, 7, 1],
// [2, 8, 2],
// [6, 8, 6],
// [5, 6, 2],
// [2, 5, 4],
// [2, 3, 7],
// [3, 5, 14],
// [3, 4, 9],
// [4, 5, 10]
// ]
// const graph = createGraph(V, E)
// const distances = djikstra(graph, V, 0)
/** /**
* The first value in the array determines the minimum distance and the * The first value in the array determines the minimum distance and the
* second value represents the parent node from which the minimum distance has been calculated * second value represents the parent node from which the minimum distance has been calculated
*/ */
console.log(distances)

View File

@ -39,28 +39,31 @@ function solve (graph, s) {
return solutions return solutions
} }
// create graph
const graph = {}
const layout = { export { solve }
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 // // create graph
// const graph = {}
// const 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
// let graph = { // let graph = {
// a: {e:1, b:1, g:3}, // a: {e:1, b:1, g:3},
// b: {a:1, c:1}, // b: {a:1, c:1},
@ -72,26 +75,22 @@ const layout = {
// h: {f:1} // h: {f:1}
// }; // };
for (const id in layout) { // for (const id in layout) {
if (!graph[id]) { graph[id] = {} } // if (!graph[id]) { graph[id] = {} }
layout[id].forEach(function (aid) { // layout[id].forEach(function (aid) {
graph[id][aid] = 1 // graph[id][aid] = 1
if (!graph[aid]) { graph[aid] = {} } // if (!graph[aid]) { graph[aid] = {} }
graph[aid][id] = 1 // graph[aid][id] = 1
}) // })
} // }
// choose start node // // choose start node
const start = '10' // const start = '10'
// get all solutions // // get all solutions
const solutions = solve(graph, start) // const solutions = solve(graph, start)
console.log("From '" + start + "' to") // // for s in solutions..
// display solutions // ' -> ' + s + ': [' + solutions[s].join(', ') + '] (dist:' + solutions[s].dist + ')'
for (const s in solutions) {
if (!solutions[s]) continue
console.log(' -> ' + s + ': [' + solutions[s].join(', ') + '] (dist:' + solutions[s].dist + ')')
}
// From '10' to // From '10' to
// -> 2: [7, 5, 4, 2] (dist:4) // -> 2: [7, 5, 4, 2] (dist:4)

View File

@ -23,26 +23,25 @@ const FloydWarshall = (dist) => {
return dist return dist
} }
const main = () => { export { FloydWarshall }
// For the following graph (edge weights are shown in brackets)
// 4 1 dist[1][2] = dist[2][1] = 1
// \ (2)/ \ dist[1][3] = dist[3][1] = 2
// \ / \(1) dist[1][4] = dist[4][1] = Infinity
// (1)\ / \ dist[3][4] = dist[4][3] = 1
// 3 2 dist[2][4] = dist[4][2] = Infinity
// dist[2][3] = dist[3][2] = Infinity
// Output should be:
// [ [0, 1, 2, 3],
// [1, 0, 3, 4],
// [2, 3, 0, 1],
// [3, 4, 1, 0] ]
console.log(FloydWarshall(
[[0, 1, 2, Infinity],
[1, 0, Infinity, Infinity],
[2, Infinity, 0, 1],
[Infinity, Infinity, 1, 0]
]
))
}
main() // For the following graph (edge weights are shown in brackets)
// 4 1 dist[1][2] = dist[2][1] = 1
// \ (2)/ \ dist[1][3] = dist[3][1] = 2
// \ / \(1) dist[1][4] = dist[4][1] = Infinity
// (1)\ / \ dist[3][4] = dist[4][3] = 1
// 3 2 dist[2][4] = dist[4][2] = Infinity
// dist[2][3] = dist[3][2] = Infinity
// Output should be:
// [ [0, 1, 2, 3],
// [1, 0, 3, 4],
// [2, 3, 0, 1],
// [3, 4, 1, 0] ]
// FloydWarshall(
// [[0, 1, 2, Infinity],
// [1, 0, Infinity, Infinity],
// [2, Infinity, 0, 1],
// [Infinity, Infinity, 1, 0]
// ]
// )

View File

@ -101,15 +101,12 @@ class GraphWeightedUndirectedAdjacencyList {
} }
} }
function main () { export { GraphWeightedUndirectedAdjacencyList }
const graph = new GraphWeightedUndirectedAdjacencyList()
graph.addEdge(1, 2, 1)
graph.addEdge(2, 3, 2)
graph.addEdge(3, 4, 1)
graph.addEdge(3, 5, 100) // Removed in MST
graph.addEdge(4, 5, 5)
console.log(graph)
console.log(graph.KruskalMST())
}
main() // const graph = new GraphWeightedUndirectedAdjacencyList()
// graph.addEdge(1, 2, 1)
// graph.addEdge(2, 3, 2)
// graph.addEdge(3, 4, 1)
// graph.addEdge(3, 5, 100) // Removed in MST
// graph.addEdge(4, 5, 5)
// graph.KruskalMST()

View File

@ -30,11 +30,11 @@ class Graph {
} }
} }
(() => { export { Graph }
const graph = new Graph()
graph.addEdge(1, 2) // const graph = new Graph()
graph.addEdge(2, 3) // graph.addEdge(1, 2)
graph.addEdge(3, 5) // graph.addEdge(2, 3)
graph.addEdge(1, 5) // graph.addEdge(3, 5)
console.log(graph.nodeNeighbors(1)) // graph.addEdge(1, 5)
})() // graph.nodeNeighbors(1)

View File

@ -46,12 +46,6 @@ Pseudocode:
Return the count Return the count
*/ */
const grid = [
['1', '1', '0', '0', '0'],
['1', '1', '0', '0', '0'],
['0', '0', '1', '0', '0'],
['0', '0', '0', '1', '1']
]
const islands = (matrixGrid) => { const islands = (matrixGrid) => {
const matrix = matrixGrid const matrix = matrixGrid
@ -83,4 +77,12 @@ const islands = (matrixGrid) => {
} }
return counter return counter
} }
console.log(islands(grid))
export { islands }
// islands(
// ['1', '1', '0', '0', '0'],
// ['1', '1', '0', '0', '0'],
// ['0', '0', '1', '0', '0'],
// ['0', '0', '0', '1', '1']
// )

View File

@ -197,14 +197,12 @@ class GraphWeightedUndirectedAdjacencyList {
} }
} }
function main () { export { GraphWeightedUndirectedAdjacencyList }
const graph = new GraphWeightedUndirectedAdjacencyList()
graph.addEdge(1, 2, 1)
graph.addEdge(2, 3, 2)
graph.addEdge(3, 4, 1)
graph.addEdge(3, 5, 100) // Removed in MST
graph.addEdge(4, 5, 5)
console.log(graph.PrimMST(1))
}
main() // const graph = new GraphWeightedUndirectedAdjacencyList()
// graph.addEdge(1, 2, 1)
// graph.addEdge(2, 3, 2)
// graph.addEdge(3, 4, 1)
// graph.addEdge(3, 5, 100) // Removed in MST
// graph.addEdge(4, 5, 5)
// graph.PrimMST(1)

View File

@ -170,8 +170,5 @@ function SHA1 (message) {
return HH return HH
} }
console.log(SHA1('A Test'))
console.log(SHA1('A Test'))
// export SHA1 function // export SHA1 function
module.exports = SHA1 export { SHA1 }

View File

@ -185,4 +185,4 @@ function SHA256 (message) {
} }
// export SHA256 function // export SHA256 function
module.exports = SHA256 export { SHA256 }

View File

@ -5,12 +5,11 @@
This file contains the test-suite for the linear algebra library. This file contains the test-suite for the linear algebra library.
The tests use javascript test-framework mocha The tests use javascript test-framework mocha
*/ */
/* eslint-disable */ /* eslint-disable */
import { LinearAlgebra } from "../src/la_lib" import { LinearAlgebra } from '../src/la_lib'
import * as assert from 'assert'
var assert = require('assert')
var fs = require('fs')
// file is included here // file is included here
// Tests goes here // Tests goes here

View File

@ -41,4 +41,4 @@ const CheckKishnamurthyNumber = (number) => {
return sumOfAllDigitFactorial === number return sumOfAllDigitFactorial === number
} }
module.exports = CheckKishnamurthyNumber export { CheckKishnamurthyNumber }

View File

@ -37,4 +37,4 @@ const CoPrimeCheck = (firstNumber, secondNumber) => {
return GetEuclidGCD(firstNumber, secondNumber) === 1 return GetEuclidGCD(firstNumber, secondNumber) === 1
} }
module.exports = CoPrimeCheck export { CoPrimeCheck }

View File

@ -29,4 +29,4 @@ const GetEuclidGCD = (arg1, arg2) => {
return (less) return (less)
} }
module.exports = GetEuclidGCD export { GetEuclidGCD }

View File

@ -10,6 +10,6 @@ export const isDivisible = (num1, num2) => {
return num1 % num2 === 0 return num1 % num2 === 0
} }
console.log(isDivisible(10, 5)) // returns true // isDivisible(10, 5) // returns true
console.log(isDivisible(123498175, 5)) // returns true // isDivisible(123498175, 5) // returns true
console.log(isDivisible(99, 5)) // returns false // isDivisible(99, 5) // returns false

View File

@ -45,7 +45,7 @@ const MatMult = (matA, matB) => {
return matC return matC
} }
const MatrixExponentiationRecursive = (mat, m) => { export const MatrixExponentiationRecursive = (mat, m) => {
// Input: mat: 2D Array of Numbers of size n x n // Input: mat: 2D Array of Numbers of size n x n
// Output: mat^n: 2D Array of Numbers of size n x n // Output: mat^n: 2D Array of Numbers of size n x n
// Complexity: O(n^3 log m) // Complexity: O(n^3 log m)
@ -65,20 +65,16 @@ const MatrixExponentiationRecursive = (mat, m) => {
} }
} }
const main = () => { // const mat = [[1, 0, 2], [2, 1, 0], [0, 2, 1]]
const mat = [[1, 0, 2], [2, 1, 0], [0, 2, 1]]
// mat ^ 0 = [ [ 1, 0, 0 ], [ 0, 1, 0 ], [ 0, 0, 1 ] ] // // mat ^ 0 = [ [ 1, 0, 0 ], [ 0, 1, 0 ], [ 0, 0, 1 ] ]
console.log(MatrixExponentiationRecursive(mat, 0)) // MatrixExponentiationRecursive(mat, 0)
// mat ^ 1 = [ [ 1, 0, 2 ], [ 2, 1, 0 ], [ 0, 2, 1 ] ] // // mat ^ 1 = [ [ 1, 0, 2 ], [ 2, 1, 0 ], [ 0, 2, 1 ] ]
console.log(MatrixExponentiationRecursive(mat, 1)) // MatrixExponentiationRecursive(mat, 1)
// mat ^ 2 = [ [ 1, 4, 4 ], [ 4, 1, 4 ], [ 4, 4, 1 ] ] // // mat ^ 2 = [ [ 1, 4, 4 ], [ 4, 1, 4 ], [ 4, 4, 1 ] ]
console.log(MatrixExponentiationRecursive(mat, 2)) // MatrixExponentiationRecursive(mat, 2)
// mat ^ 5 = [ [ 1, 4, 4 ], [ 4, 1, 4 ], [ 4, 4, 1 ] ] // // mat ^ 5 = [ [ 1, 4, 4 ], [ 4, 1, 4 ], [ 4, 4, 1 ] ]
console.log(MatrixExponentiationRecursive(mat, 5)) // MatrixExponentiationRecursive(mat, 5)
}
main()

View File

@ -10,7 +10,7 @@ const matrixCheck = (matrix) => {
if (index === 0) { if (index === 0) {
columnNumb = matrix[index].length columnNumb = matrix[index].length
} else if (matrix[index].length !== columnNumb) { } else if (matrix[index].length !== columnNumb) {
console.log('The columns in this array are not equal') // The columns in this array are not equal
} else { } else {
return columnNumb return columnNumb
} }
@ -21,7 +21,7 @@ const matrixCheck = (matrix) => {
const twoMatricesCheck = (first, second) => { const twoMatricesCheck = (first, second) => {
const [firstRowLength, secondRowLength, firstColLength, secondColLength] = [first.length, second.length, matrixCheck(first), matrixCheck(second)] const [firstRowLength, secondRowLength, firstColLength, secondColLength] = [first.length, second.length, matrixCheck(first), matrixCheck(second)]
if (firstRowLength !== secondColLength || secondRowLength !== firstColLength) { if (firstRowLength !== secondColLength || secondRowLength !== firstColLength) {
console.log('These matrices do not have a common side') // These matrices do not have a common side
return false return false
} else { } else {
return true return true
@ -44,7 +44,7 @@ const initiateEmptyArray = (first, second) => {
// Finally, `matrixMult` uses `Array.prototype.push()`, multiple layers of nested `for` loops, the addition assignment `+=` operator and multiplication operator `*` to perform the dot product between two matrices of differing sizes. // Finally, `matrixMult` uses `Array.prototype.push()`, multiple layers of nested `for` loops, the addition assignment `+=` operator and multiplication operator `*` to perform the dot product between two matrices of differing sizes.
// Dot product, takes the row of the first matrix and multiplies it by the column of the second matrix, the `twoMatricesCheck` tested to see if they were the same size already. // Dot product, takes the row of the first matrix and multiplies it by the column of the second matrix, the `twoMatricesCheck` tested to see if they were the same size already.
// The dot product for each iteration is then saved to its respective index into `multMatrix`. // The dot product for each iteration is then saved to its respective index into `multMatrix`.
const matrixMult = (firstArray, secondArray) => { export const matrixMult = (firstArray, secondArray) => {
const multMatrix = initiateEmptyArray(firstArray, secondArray) const multMatrix = initiateEmptyArray(firstArray, secondArray)
for (let rm = 0; rm < firstArray.length; rm++) { for (let rm = 0; rm < firstArray.length; rm++) {
const rowMult = [] const rowMult = []
@ -66,26 +66,26 @@ const matrixMult = (firstArray, secondArray) => {
return multMatrix return multMatrix
} }
const firstMatrix = [ // const firstMatrix = [
[1, 2], // [1, 2],
[3, 4] // [3, 4]
] // ]
const secondMatrix = [ // const secondMatrix = [
[5, 6], // [5, 6],
[7, 8] // [7, 8]
] // ]
console.log(matrixMult(firstMatrix, secondMatrix)) // [ [ 19, 22 ], [ 43, 50 ] ] // matrixMult(firstMatrix, secondMatrix) // [ [ 19, 22 ], [ 43, 50 ] ]
const thirdMatrix = [ // const thirdMatrix = [
[-1, 4, 1], // [-1, 4, 1],
[7, -6, 2] // [7, -6, 2]
] // ]
const fourthMatrix = [ // const fourthMatrix = [
[2, -2], // [2, -2],
[5, 3], // [5, 3],
[3, 2] // [3, 2]
] // ]
console.log(matrixMult(thirdMatrix, fourthMatrix)) // [ [ 21, 16 ], [ -10, -28 ] ] // matrixMult(thirdMatrix, fourthMatrix) // [ [ 21, 16 ], [ -10, -28 ] ]

View File

@ -47,21 +47,4 @@ const combination = (n, r) => {
} }
// Exports the functions to be used in other files. // Exports the functions to be used in other files.
module.exports.factorial = factorial export { factorial, permutation, combination }
module.exports.permutation = permutation
module.exports.combination = combination
/**
* @example
const funcs = require("./PermutationAndCombination.js");
console.log(funcs.factorial(5));
console.log(funcs.permutation(5, 2));
console.log(funcs.combination(5, 2));
* @output
120
20
10
*/

View File

@ -26,4 +26,4 @@ const ReverseNumber = (number) => {
return reverseNumber return reverseNumber
} }
module.exports = ReverseNumber export { ReverseNumber }

View File

@ -1,7 +1,7 @@
/* /*
author: Theepag author: Theepag
*/ */
const factorialize = (num) => { export const factorialize = (num) => {
// Step 1. variable result to store num // Step 1. variable result to store num
let result = num let result = num
// If num = 0 OR 1, the factorial will return 1 // If num = 0 OR 1, the factorial will return 1
@ -14,6 +14,3 @@ const factorialize = (num) => {
// Step 3. Return the factorial // Step 3. Return the factorial
return result return result
} }
// test
console.log(factorialize(5))
console.log(factorialize(4))

View File

@ -4,14 +4,7 @@
* Return the result. * Return the result.
*/ */
const decimalIsolate = (number) => { export const decimalIsolate = (number) => {
const ans = parseFloat((number + '').replace(/^[-\d]+./, '.')) const ans = parseFloat((number + '').replace(/^[-\d]+./, '.'))
return isNaN(ans) === true ? 0 : ans return isNaN(ans) === true ? 0 : ans
} }
// testing
console.log(decimalIsolate(35.345))
console.log(decimalIsolate(56.879))
console.log(decimalIsolate(89.5643))
console.log(decimalIsolate(38.00))
console.log(decimalIsolate(33))

View File

@ -4,10 +4,6 @@
* else false * else false
*/ */
const isOdd = (value) => { export const isOdd = (value) => {
return !!((value & 1)) return !!((value & 1))
} }
// testing
console.log(isOdd(2))
console.log(isOdd(3))

View File

@ -1,4 +1,4 @@
const { binaryExponentiation } = require('../BinaryExponentiationRecursive') import { binaryExponentiation } from '../BinaryExponentiationRecursive'
describe('BinaryExponentiationRecursive', () => { describe('BinaryExponentiationRecursive', () => {
it('should calculate 2 to the power of 10 correctly', () => { it('should calculate 2 to the power of 10 correctly', () => {

View File

@ -0,0 +1,19 @@
import { factorial, permutation, combination } from '../PermutationAndCombination'
describe('Factorial', () => {
it('factorial(5)', () => {
expect(factorial(5)).toBe(120)
})
})
describe('Permutation', () => {
it('permutation(5, 2)', () => {
expect(permutation(5, 2)).toBe(20)
})
})
describe('Combination', () => {
it('combination(5, 2)', () => {
expect(combination(5, 2)).toBe(10)
})
})

View File

@ -4,8 +4,6 @@
Find the sum of all the multiples of 3 or 5 below the provided parameter value number. Find the sum of all the multiples of 3 or 5 below the provided parameter value number.
*/ */
const readline = require('readline')
const multiplesThreeAndFive = (num) => { const multiplesThreeAndFive = (num) => {
let total = 0 let total = 0
// total for calculating the sum // total for calculating the sum
@ -17,11 +15,4 @@ const multiplesThreeAndFive = (num) => {
return total return total
} }
const rl = readline.createInterface({ export { multiplesThreeAndFive }
input: process.stdin,
output: process.stdout
})
rl.question('Enter a number: ', function (num) {
console.log(multiplesThreeAndFive(num)) // multiples3_5 function to calculate the sum of multiples of 3 and 5 within num
rl.close()
})

View File

@ -4,10 +4,9 @@ const PHI = (1 + SQ5) / 2 // definition of PHI
// theoretically it should take O(1) constant amount of time as long // theoretically it should take O(1) constant amount of time as long
// arithmetic calculations are considered to be in constant amount of time // arithmetic calculations are considered to be in constant amount of time
const EvenFibonacci = (limit) => { export const EvenFibonacci = (limit) => {
const highestIndex = Math.floor(Math.log(limit * SQ5) / Math.log(PHI)) const highestIndex = Math.floor(Math.log(limit * SQ5) / Math.log(PHI))
const n = Math.floor(highestIndex / 3) const n = Math.floor(highestIndex / 3)
return ((PHI ** (3 * n + 3) - 1) / (PHI ** 3 - 1) - return ((PHI ** (3 * n + 3) - 1) / (PHI ** 3 - 1) -
((1 - PHI) ** (3 * n + 3) - 1) / ((1 - PHI) ** 3 - 1)) / SQ5 ((1 - PHI) ** (3 * n + 3) - 1) / ((1 - PHI) ** 3 - 1)) / SQ5
} }
console.log(EvenFibonacci(4e6)) // Sum of even Fibonacci upto 4 Million

View File

@ -1,7 +1,6 @@
// https://projecteuler.net/problem=3 // https://projecteuler.net/problem=3
const problem = 600851475143
const largestPrime = (num) => { export const largestPrime = (num = 600851475143) => {
let newnumm = num let newnumm = num
let largestFact = 0 let largestFact = 0
let counter = 2 let counter = 2
@ -17,4 +16,3 @@ const largestPrime = (num) => {
} }
return largestFact return largestFact
} }
console.log(largestPrime(problem))

View File

@ -2,7 +2,7 @@
/* A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. /* A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers. Find the largest palindrome made from the product of two 3-digit numbers.
*/ */
const largestPalindromic = (digits) => { export const largestPalindromic = (digits) => {
let i let i
let n let n
let m let m
@ -42,5 +42,3 @@ const largestPalindromic = (digits) => {
} }
return NaN // returning not a number, if any such case arise return NaN // returning not a number, if any such case arise
} }
console.log(largestPalindromic(3))

Some files were not shown because too many files have changed in this diff Show More