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) {
this.n = n
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) {
if (total === 0) {
console.log(this.combinationArray)
return
this.combinations.push([...this.current])
return this.combinations
}
for (let i = low; i <= high; i++) {
this.combinationArray.push(i)
this.current.push(i)
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?
* - 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:
* - https://www.britannica.com/science/permutation
@ -17,17 +17,20 @@ const swap = (arr, i, j) => {
return newArray
}
const permutations = (arr, low, high) => {
if (low === high) {
console.log(arr.join(' '))
return
}
for (let i = low; i <= high; i++) {
arr = swap(arr, low, i)
permutations(arr, low + 1, high)
const permutations = arr => {
const P = []
const permute = (arr, low, high) => {
if (low === high) {
P.push([...arr])
return P
}
for (let i = low; i <= high; i++) {
arr = swap(arr, low, i)
permute(arr, low + 1, high)
}
return P
}
return permute(arr, 0, arr.length - 1)
}
// Driver Code
const input = [1, 2, 3]
permutations(input, 0, input.length - 1)
export { permutations }

View File

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

View File

@ -36,7 +36,6 @@ class NQueen {
solve (col = 0) {
if (col >= this.size) {
this.printBoard()
this.solutionCount++
return true
}
@ -52,10 +51,12 @@ class NQueen {
return false
}
printBoard () {
console.log('\n')
printBoard (output = value => console.log(value)) {
if (!output._isMockFunction) {
output('\n')
}
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)
}
printBoard () {
printBoard (output = (...v) => console.log(...v)) {
// helper function to display board
for (let i = 0; i < 9; i++) {
if (i % 3 === 0 && i !== 0) console.log('- - - - - - - - - - - -')
console.log(
if (i % 3 === 0 && i !== 0) {
output('- - - - - - - - - - - -')
}
output(
...this.getSection(i, [0, 3]), ' | ',
...this.getSection(i, [3, 6]), ' | ',
...this.getSection(i, [6, 9]))

View File

@ -3,11 +3,11 @@ import { Combinations } from '../AllCombinationsOfSizeK'
describe('AllCombinationsOfSizeK', () => {
it('should return 3x2 matrix solution for n = 3 and k = 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)
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
}
// Run `binary_and` Function to find the binary and operation
console.log(BinaryCountSetBits(251))
export { BinaryCountSetBits }

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
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
Be confident that your code works. When was the last time you committed a code change, your build failed, and half of
@ -125,7 +131,7 @@ function sumOfArray (arrayOfNumbers) {
return (sum)
}
```
*
*
* Avoid using global variables and avoid `==`
* Please use `let` over `var`
* Please refrain from using `console.log` or any other console methods

View File

@ -103,41 +103,4 @@ class LFUCache {
}
}
function main () {
// 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()
export { LFUCache }

View File

@ -86,41 +86,4 @@ class LRUCache {
}
}
function main () {
// 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()
export { LRUCache }

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
}
// Atbash Example
const encryptedString = 'HELLO WORLD'
const decryptedString = Atbash(encryptedString)
console.log(decryptedString) // SVOOL DLIOW
export { Atbash }
// > Atbash('HELLO WORLD')
// 'SVOOL DLIOW'

View File

@ -29,8 +29,7 @@ function rot13 (str) {
return response.join('')
}
// Caesars Cipher Example
const encryptedString = 'Uryyb Jbeyq'
const decryptedString = rot13(encryptedString)
export { rot13 }
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++) {
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
// linked list will be used in the next stage of development to calculate the number of occurrence of the key
if (wordBank[i] === outStrElement) {
return k // return the key number if founded
}
outStrElement = '' // reset the temp word
} // end for ( let i=0; i < wordBank.length; i++)
}
@ -145,4 +141,7 @@ function caesarCipherEncodeAndDecodeEngine (inStr, numShifted) {
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)
}
console.log(encrypt('keyword', 'Hello world!')) // Prints 'Aoggj ujngw!'
console.log(decrypt('keyword', 'Aoggj ujngw!')) // Prints 'Hello world!
export { encrypt, decrypt }
// 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
* @return {String} - decrypted string
*/
const transcipher = (text) => {
const ROT13 = (text) => {
const originalCharacterList = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
const toBeMappedCharaterList = 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm'
const index = x => originalCharacterList.indexOf(x)
@ -11,11 +11,7 @@ const transcipher = (text) => {
return text.split('').map(replace).join('')
}
(() => {
const messageToBeEncrypted = 'The quick brown fox jumps over the lazy dog'
console.log(`Original Text = "${messageToBeEncrypted}"`)
const rot13CipheredText = transcipher(messageToBeEncrypted)
console.log(`Ciphered Text = "${rot13CipheredText}"`)
const rot13DecipheredText = transcipher(rot13CipheredText)
console.log(`Deciphered Text = "${rot13DecipheredText}"`)
})()
export { ROT13 }
// > ROT13('The quick brown fox jumps over the lazy dog')
// 'Gur dhvpx oebja sbk whzcf bire gur ynml qbt'

View File

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

View File

@ -20,7 +20,12 @@ function XOR (str, key) {
return result
}
const encryptedString = XOR('test string', 32)
console.log('Encrypted: ', encryptedString)
const decryptedString = XOR(encryptedString, 32)
console.log('Decrypted: ', decryptedString)
export { XOR }
// Nb: Node REPL might not output the null char '\x00' (charcode 0)
// > 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}+`), '')
}
(() => {
console.log(convertArbitraryBase('98', '0123456789', '01234567'))
console.log(convertArbitraryBase('98', '0123456789', 'abcdefgh'))
console.log(convertArbitraryBase('129', '0123456789', '01234567'))
})()
export { convertArbitraryBase }
// > convertArbitraryBase('98', '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
const binaryDigits = binaryString.split('').reverse() // Splits the binary number into reversed single digits
binaryDigits.forEach((binaryDigit, index) => {
decimalNumber += binaryDigit * (Math.pow(2, index)) // Summation of all the decimal converted digits
})
console.log(`Decimal of ${binaryString} is ${decimalNumber}`)
return decimalNumber
}
(() => {
binaryToDecimal('111001')
binaryToDecimal('101')
})()
// > binaryToDecimal('111001')
// 57
// > binaryToDecimal('101')
// 5

View File

@ -38,4 +38,4 @@ const DateDayDifference = (date1, date2) => {
// 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
module.exports = DateToDay
export { DateToDay }

View File

@ -4,9 +4,16 @@ function decimalToBinary (num) {
bin.unshift(num % 2)
num >>= 1 // basically /= 2 without remainder if any
}
console.log('The decimal in binary is ' + bin.join(''))
return bin.join('')
}
decimalToBinary(2)
decimalToBinary(7)
decimalToBinary(35)
export { decimalToBinary }
// > 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++))
num = Math.floor(num / 8) // basically /= 8 without remainder if any
}
console.log('The decimal in octal is ' + oct)
return oct
}
decimalToOctal(2)
decimalToOctal(8)
decimalToOctal(65)
decimalToOctal(216)
decimalToOctal(512)
export { decimalToOctal }
// > decimalToOctal(2)
// 2
// > decimalToOctal(8)
// 10
// > decimalToOctal(65)
// 101
// > decimalToOctal(216)
// 330
// > decimalToOctal(512)
// 1000

View File

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

View File

@ -11,4 +11,7 @@ function hexStringToRGB (hexString) {
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('')
}
module.exports = LowerCaseConversion
export { LowerCaseConversion }

View File

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

View File

@ -12,5 +12,10 @@ function RGBToHex (r, g, b) {
return `#${toHex(r)}${toHex(g)}${toHex(b)}`
}
console.log(RGBToHex(255, 255, 255) === '#ffffff')
console.log(RGBToHex(255, 99, 71) === '#ff6347')
export { RGBToHex }
// > 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
}
function romanToDecimal (romanNumber) {
export function romanToDecimal (romanNumber) {
let prev = ' '
let sum = 0
@ -32,7 +32,3 @@ function romanToDecimal (romanNumber) {
}
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)
## 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)
* [Problem014](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem014.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)
* [Problem018](https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem018.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
* [BinaryEquivalent](https://github.com/TheAlgorithms/Javascript/blob/master/Recursive/BinaryEquivalent.js)

View File

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

View File

@ -36,7 +36,7 @@ class Graph {
}
// Prints the vertex and adjacency list
printGraph () {
printGraph (output = value => console.log(value)) {
// get all the vertices
const getKeys = this.AdjList.keys()
@ -54,35 +54,9 @@ class Graph {
}
// 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
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()
export { Graph }

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()
maxHeap.insert([4])
maxHeap.insert([3])
maxHeap.insert([6])
maxHeap.insert([1])
maxHeap.insert([8])
maxHeap.insert([2])
// Example
while (!maxHeap.empty()) {
const mx = maxHeap.extractMax()
console.log(mx)
}
// const maxHeap = new BinaryHeap()
// maxHeap.insert([4])
// 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
print () {
console.log(this.heap.slice(1))
print (output = value => console.log(value)) {
output(this.heap.slice(1))
}
// heap sorting can be done by performing
@ -109,17 +109,4 @@ class MinPriorityQueue {
}
}
// testing
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 ]
export { MinPriorityQueue }

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()
newDoubleLinkedList.append(1)
newDoubleLinkedList.append(2)
console.log('Testing: ' + newDoubleLinkedList.size()) // returns 2
// Example
// const newDoubleLinkedList = new DoubleLinkedList()
// newDoubleLinkedList.append(1)
// newDoubleLinkedList.append(2)
// newDoubleLinkedList.size() // returns 2
export { DoubleLinkedList }

View File

@ -73,25 +73,16 @@ class SinglyCircularLinkedList {
this.size--
}
printData () {
printData (output = value => console.log(value)) {
let count = 0
let current = this.head
while (current !== null && count !== this.size) {
console.log(current.data + '\n')
while (current !== null && count < this.size) {
output(current.data)
current = current.next
count++
}
}
}
const ll = new 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()
export { SinglyCircularLinkedList }

View File

@ -180,12 +180,12 @@ const LinkedList = (function () {
}
// Function to view the LinkedList
LinkedList.prototype.view = function () {
LinkedList.prototype.view = function (output = value => console.log(value)) {
let currentNode = this.head
let count = 0
while (count < this.length) {
count++
console.log(currentNode.element)
output(currentNode.element)
currentNode = currentNode.next
}
}
@ -194,16 +194,4 @@ const LinkedList = (function () {
return LinkedList
}())
// Implementation of 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()
export { LinkedList }

View File

@ -28,7 +28,7 @@ class CircularQueue {
// REMOVES ELEMENTS
dequeue () {
if (this.checkEmpty()) {
console.log('UNDERFLOW')
// UNDERFLOW
return
}
const y = this.queue[this.front]
@ -62,15 +62,15 @@ class CircularQueue {
// Checks if max capacity of queue has been reached or not
checkOverflow () {
if ((this.front === 1 && this.rear === this.maxLength) || (this.front === this.rear + 1)) {
console.log('CIRCULAR QUEUE OVERFLOW')
// CIRCULAR QUEUE OVERFLOW
return true
}
}
// Prints the entire array
display () {
// Prints the entire array ('*' represents blank space)
display (output = value => console.log(value)) {
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 () {
// 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()
export { CircularQueue }

View File

@ -43,38 +43,11 @@ const Queue = (function () {
}
// List all the items in the queue
Queue.prototype.view = function () {
console.log(this.queue)
Queue.prototype.view = function (output = value => console.log(value)) {
output(this.queue)
}
return Queue
}())
// Implementation
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!
export { Queue }

View File

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

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
Stack.prototype.view = function () {
for (let i = 0; i < this.top; i++) { console.log(this.stack[i]) }
Stack.prototype.view = function (output = value => console.log(value)) {
for (let i = 0; i < this.top; i++) {
output(this.stack[i])
}
}
return Stack
}())
// Implementation
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()
export { Stack }

View File

@ -53,16 +53,5 @@ class Stack {
return el instanceof Stack
}
}
const newStack = new Stack()
console.log('Is it a Stack?,', Stack.isStack(newStack))
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)
export { Stack }

View File

@ -229,44 +229,44 @@ const AVLTree = (function () {
return true
}
return _avl
}());
}())
/**
* A Code for Testing the AVLTree
*/
(function test () {
const newAVL = new AVLTree()
const size = Math.floor(Math.random() * 1000000)
let uniques = 0
let i, temp, j
const array = []
for (i = 0; i < size; i++) {
temp = Math.floor(Math.random() * Number.MAX_VALUE)
if (newAVL.add(temp)) {
uniques++
array.push(temp)
}
}
if (newAVL.size !== uniques) {
throw new Error('elements not inserted properly')
}
const findTestSize = Math.floor(Math.random() * uniques)
for (i = 0; i < findTestSize; i++) {
j = Math.floor(Math.random() * uniques)
if (!newAVL.find(array[j])) {
throw new Error('inserted elements not found')
}
}
const deleteTestSize = Math.floor(uniques * Math.random())
for (i = 0; i < deleteTestSize; i++) {
j = Math.floor(Math.random() * uniques)
temp = array[j]
if (newAVL.find(temp)) {
if (!newAVL.remove(temp)) {
throw new Error('delete not working properly')
}
}
}
})()
// (function test () {
// const newAVL = new AVLTree()
// const size = Math.floor(Math.random() * 1000000)
// let uniques = 0
// let i, temp, j
// const array = []
// for (i = 0; i < size; i++) {
// temp = Math.floor(Math.random() * Number.MAX_VALUE)
// if (newAVL.add(temp)) {
// uniques++
// array.push(temp)
// }
// }
// if (newAVL.size !== uniques) {
// throw new Error('elements not inserted properly')
// }
// const findTestSize = Math.floor(Math.random() * uniques)
// for (i = 0; i < findTestSize; i++) {
// j = Math.floor(Math.random() * uniques)
// if (!newAVL.find(array[j])) {
// throw new Error('inserted elements not found')
// }
// }
// const deleteTestSize = Math.floor(uniques * Math.random())
// for (i = 0; i < deleteTestSize; i++) {
// j = Math.floor(Math.random() * uniques)
// temp = array[j]
// if (newAVL.find(temp)) {
// if (!newAVL.remove(temp)) {
// 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
Node.prototype.visit = function () {
Node.prototype.visit = function (output = value => console.log(value)) {
// Recursively go left
if (this.left !== null) {
this.left.visit()
}
// Print out value
console.log(this.value)
output(this.value)
// Recursively go right
if (this.right !== null) {
this.right.visit()
@ -115,7 +115,7 @@ const Tree = (function () {
// Inorder traversal
Tree.prototype.traverse = function () {
if (!this.root) {
console.log('No nodes are there in the tree till now')
// No nodes are there in the tree till now
return
}
this.root.visit()
@ -124,11 +124,11 @@ const Tree = (function () {
// Start by searching the root
Tree.prototype.search = function (val) {
const found = this.root.search(val)
if (found === null) {
console.log(val + ' not found')
} else {
console.log('Found:' + found.value)
if (found !== null) {
return found.value
}
// not found
return null
}
// Add a new value to the tree
@ -151,16 +151,4 @@ const Tree = (function () {
return Tree
}())
// Implementation of BST
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()
export { Tree }

View File

@ -116,22 +116,6 @@ Trie.prototype.findOccurences = function (word) {
// No such word exists
if (node === null) return 0
return node.count
};
}
// To test
(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'))
})()
export { Trie }

View File

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

View File

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

View File

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

View File

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

View File

@ -17,6 +17,7 @@ function costOfSubstitution (x, y) {
return x === y ? 0 : 1
}
// Levenshtein distance between x and y
function calculate (x, y) {
const dp = new Array(x.length + 1)
for (let i = 0; i < x.length + 1; i++) {
@ -38,12 +39,4 @@ function calculate (x, y) {
return dp[x.length][y.length]
}
function main () {
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()
export { calculate }

View File

@ -22,12 +22,11 @@ function longestCommonSubsequence (x, y, str1, str2, dp) {
}
}
function 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)
console.log(res)
}
// Example
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
*/
function main () {
const x = [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]
// Return the length of the Longest Increasing Subsequence, given array x
function longestIncreasingSubsequence (x) {
const length = x.length
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)
}
function main () {
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]))
}
// Exmaple
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]
}
const main = () => {
console.log(
minCostPath([
[2, 1],
[3, 1],
[4, 2]
])
)
console.log(
minCostPath([
[2, 1, 4],
[2, 1, 3],
[3, 2, 1]
])
)
}
export { minCostPath }
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]
}
function main () {
const array = [1, 1, 2, 2, 3, 1, 1]
const sum = 4
const result = NumberOfSubsetSum(array, sum)
console.log(result)
}
main()
// example
// const array = [1, 1, 2, 2, 3, 1, 1]
// const sum = 4
// const result = NumberOfSubsetSum(array, sum)
export { NumberOfSubsetSum }

View File

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

View File

@ -18,14 +18,9 @@ function sieveOfEratosthenes (n) {
return primes
}
function main () {
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)
}
}
}
// Example
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) => {
for (let i = 0; i < 9; i++) {
@ -43,8 +32,18 @@ const sudokuSolver = (data) => {
}
// testing
(() => {
if (sudokuSolver(_board)) {
console.log(_board)
}
})()
// 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', '.', '.', '.', '.']
// ]
// 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:
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()
const length = input.length
const output = []
let i = 0
while (i < length) {
const cap = Number(input[i].trim().split(' ')[0])
@ -62,9 +64,11 @@ const main = () => {
cache.push(temp)
}
const result = zeroOneKnapsack(newArr, currlen, cap, cache)
console.log(result)
output.push(result)
i += currlen + 1
}
return output
}
main()
export { zeroOneKnapsack, example }

View File

@ -2,7 +2,8 @@
* Author: Arnab Ray
* ConvexHull using 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) {
@ -27,7 +28,7 @@ function orientation (a, b, c) {
function convexHull (points) {
const pointsLen = points.length
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)
@ -65,18 +66,22 @@ function convexHull (points) {
for (let i = lowerPoints.length - 1; i >= 0; i--) {
hull.push(lowerPoints[i])
}
console.log('The Convex Hull found is: \n')
console.log(hull)
return hull
}
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 }]
export { convexHull }
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 () {
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())
}
export { GraphUnweightedUndirectedAdjacencyList }
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))
}
console.log(density(10, 2))
export { density }

View File

@ -38,14 +38,14 @@ class GraphUnweightedUndirected {
}
}
function main () {
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))
}
export { GraphUnweightedUndirected }
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 () {
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))
}
export { GraphUnweightedUndirected }
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
}
const V = 9
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]
]
export { createGraph, djikstra }
const graph = createGraph(V, E)
const distances = djikstra(graph, V, 0)
// const V = 9
// 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
* 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
}
// 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: []
}
export { solve }
// 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 = {
// a: {e:1, b:1, g:3},
// b: {a:1, c:1},
@ -72,26 +75,22 @@ const layout = {
// h: {f:1}
// };
for (const id in layout) {
if (!graph[id]) { graph[id] = {} }
layout[id].forEach(function (aid) {
graph[id][aid] = 1
if (!graph[aid]) { graph[aid] = {} }
graph[aid][id] = 1
})
}
// for (const id in layout) {
// if (!graph[id]) { graph[id] = {} }
// layout[id].forEach(function (aid) {
// graph[id][aid] = 1
// if (!graph[aid]) { graph[aid] = {} }
// graph[aid][id] = 1
// })
// }
// choose start node
const start = '10'
// get all solutions
const solutions = solve(graph, start)
// // choose start node
// const start = '10'
// // get all solutions
// const solutions = solve(graph, start)
console.log("From '" + start + "' to")
// display solutions
for (const s in solutions) {
if (!solutions[s]) continue
console.log(' -> ' + s + ': [' + solutions[s].join(', ') + '] (dist:' + solutions[s].dist + ')')
}
// // for s in solutions..
// ' -> ' + s + ': [' + solutions[s].join(', ') + '] (dist:' + solutions[s].dist + ')'
// From '10' to
// -> 2: [7, 5, 4, 2] (dist:4)

View File

@ -23,26 +23,25 @@ const FloydWarshall = (dist) => {
return dist
}
const 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] ]
console.log(FloydWarshall(
[[0, 1, 2, Infinity],
[1, 0, Infinity, Infinity],
[2, Infinity, 0, 1],
[Infinity, Infinity, 1, 0]
]
))
}
export { FloydWarshall }
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 () {
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())
}
export { GraphWeightedUndirectedAdjacencyList }
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 {
}
}
(() => {
const graph = new Graph()
graph.addEdge(1, 2)
graph.addEdge(2, 3)
graph.addEdge(3, 5)
graph.addEdge(1, 5)
console.log(graph.nodeNeighbors(1))
})()
export { Graph }
// const graph = new Graph()
// graph.addEdge(1, 2)
// graph.addEdge(2, 3)
// graph.addEdge(3, 5)
// graph.addEdge(1, 5)
// graph.nodeNeighbors(1)

View File

@ -46,12 +46,6 @@ Pseudocode:
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 matrix = matrixGrid
@ -83,4 +77,12 @@ const islands = (matrixGrid) => {
}
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 () {
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))
}
export { GraphWeightedUndirectedAdjacencyList }
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
}
console.log(SHA1('A Test'))
console.log(SHA1('A Test'))
// export SHA1 function
module.exports = SHA1
export { SHA1 }

View File

@ -185,4 +185,4 @@ function SHA256 (message) {
}
// 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.
The tests use javascript test-framework mocha
*/
/* eslint-disable */
import { LinearAlgebra } from "../src/la_lib"
var assert = require('assert')
var fs = require('fs')
import { LinearAlgebra } from '../src/la_lib'
import * as assert from 'assert'
// file is included here
// Tests goes here
@ -211,4 +210,4 @@ describe('class Matrix', function () {
assert.ok(B.equal(C))
})
})
})
})

View File

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

View File

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

View File

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

View File

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

View File

@ -45,7 +45,7 @@ const MatMult = (matA, matB) => {
return matC
}
const MatrixExponentiationRecursive = (mat, m) => {
export const MatrixExponentiationRecursive = (mat, m) => {
// Input: mat: 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)
@ -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 ] ]
console.log(MatrixExponentiationRecursive(mat, 0))
// // mat ^ 0 = [ [ 1, 0, 0 ], [ 0, 1, 0 ], [ 0, 0, 1 ] ]
// MatrixExponentiationRecursive(mat, 0)
// mat ^ 1 = [ [ 1, 0, 2 ], [ 2, 1, 0 ], [ 0, 2, 1 ] ]
console.log(MatrixExponentiationRecursive(mat, 1))
// // mat ^ 1 = [ [ 1, 0, 2 ], [ 2, 1, 0 ], [ 0, 2, 1 ] ]
// MatrixExponentiationRecursive(mat, 1)
// mat ^ 2 = [ [ 1, 4, 4 ], [ 4, 1, 4 ], [ 4, 4, 1 ] ]
console.log(MatrixExponentiationRecursive(mat, 2))
// // mat ^ 2 = [ [ 1, 4, 4 ], [ 4, 1, 4 ], [ 4, 4, 1 ] ]
// MatrixExponentiationRecursive(mat, 2)
// mat ^ 5 = [ [ 1, 4, 4 ], [ 4, 1, 4 ], [ 4, 4, 1 ] ]
console.log(MatrixExponentiationRecursive(mat, 5))
}
main()
// // mat ^ 5 = [ [ 1, 4, 4 ], [ 4, 1, 4 ], [ 4, 4, 1 ] ]
// MatrixExponentiationRecursive(mat, 5)

View File

@ -10,7 +10,7 @@ const matrixCheck = (matrix) => {
if (index === 0) {
columnNumb = matrix[index].length
} 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 {
return columnNumb
}
@ -21,7 +21,7 @@ const matrixCheck = (matrix) => {
const twoMatricesCheck = (first, second) => {
const [firstRowLength, secondRowLength, firstColLength, secondColLength] = [first.length, second.length, matrixCheck(first), matrixCheck(second)]
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
} else {
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.
// 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`.
const matrixMult = (firstArray, secondArray) => {
export const matrixMult = (firstArray, secondArray) => {
const multMatrix = initiateEmptyArray(firstArray, secondArray)
for (let rm = 0; rm < firstArray.length; rm++) {
const rowMult = []
@ -66,26 +66,26 @@ const matrixMult = (firstArray, secondArray) => {
return multMatrix
}
const firstMatrix = [
[1, 2],
[3, 4]
]
// const firstMatrix = [
// [1, 2],
// [3, 4]
// ]
const secondMatrix = [
[5, 6],
[7, 8]
]
// const secondMatrix = [
// [5, 6],
// [7, 8]
// ]
console.log(matrixMult(firstMatrix, secondMatrix)) // [ [ 19, 22 ], [ 43, 50 ] ]
// matrixMult(firstMatrix, secondMatrix) // [ [ 19, 22 ], [ 43, 50 ] ]
const thirdMatrix = [
[-1, 4, 1],
[7, -6, 2]
]
const fourthMatrix = [
[2, -2],
[5, 3],
[3, 2]
]
// const thirdMatrix = [
// [-1, 4, 1],
// [7, -6, 2]
// ]
// const fourthMatrix = [
// [2, -2],
// [5, 3],
// [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.
module.exports.factorial = factorial
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
*/
export { factorial, permutation, combination }

View File

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

View File

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

View File

@ -4,14 +4,7 @@
* Return the result.
*/
const decimalIsolate = (number) => {
export const decimalIsolate = (number) => {
const ans = parseFloat((number + '').replace(/^[-\d]+./, '.'))
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
*/
const isOdd = (value) => {
export const isOdd = (value) => {
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', () => {
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.
*/
const readline = require('readline')
const multiplesThreeAndFive = (num) => {
let total = 0
// total for calculating the sum
@ -17,11 +15,4 @@ const multiplesThreeAndFive = (num) => {
return total
}
const rl = readline.createInterface({
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()
})
export { multiplesThreeAndFive }

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
// 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 n = Math.floor(highestIndex / 3)
return ((PHI ** (3 * n + 3) - 1) / (PHI ** 3 - 1) -
((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
const problem = 600851475143
const largestPrime = (num) => {
export const largestPrime = (num = 600851475143) => {
let newnumm = num
let largestFact = 0
let counter = 2
@ -17,4 +16,3 @@ const largestPrime = (num) => {
}
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.
Find the largest palindrome made from the product of two 3-digit numbers.
*/
const largestPalindromic = (digits) => {
export const largestPalindromic = (digits) => {
let i
let n
let m
@ -42,5 +42,3 @@ const largestPalindromic = (digits) => {
}
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