├── src └── .gitkeep ├── .github ├── issue-template.md ├── pull-request-template.md ├── contributing.md └── code-of-conduct.md ├── algorithms ├── math │ ├── evenNumbers.js │ ├── naturalNumbersSum.js │ ├── randomNumber.js │ ├── greatestCommonDivisor.js │ ├── euclidean.js │ ├── factorial.js │ ├── fibonnaci.js │ ├── computeNCR.js │ ├── euclideanIterative.js │ ├── factorial-recursive.js │ ├── degreeRadianConversion.js │ ├── gcd.js │ ├── isPerfectSquare.js │ ├── quadrant.js │ ├── fibonacci-recursive.js │ ├── checkPrime.js │ ├── fibonacci.js │ ├── collatz.js │ ├── pascalsTriangle.js │ ├── 2sum.js │ ├── spiralMatrix.js │ └── smallest-common-multiple.js ├── sorting │ ├── gulagSort.js │ ├── color.js │ ├── shellSort.js │ ├── Distance.js │ ├── gnomeSort.js │ ├── selectionSort.js │ ├── countingSort.js │ ├── insertionSort.js │ ├── bubbleSort.js │ ├── pancakeSort.js │ ├── mergeSort.js │ ├── heapSort.js │ ├── radixSort.js │ ├── quickSort.js │ ├── BogoSort.js │ └── flashSort.js ├── others │ ├── checkPrime.js │ ├── primeFactors.js │ └── bigonotaion.js ├── strings │ ├── missingNumber.js │ ├── pigLatin.js │ ├── anagram.js │ ├── integerReversal.js │ ├── largestSumOfTwo.js │ ├── palindrome.js │ └── checkPalindrome.js ├── searches │ ├── sequentialSearch.js │ └── binarySearch.js ├── ciphers │ ├── rot13.js │ └── vigenere.js ├── searching │ ├── linearSearch.js │ ├── jumpSearch.js │ ├── naivePatternSearching.js │ └── binarySearch.js ├── graphs │ ├── bfs.js │ ├── dfs.js │ ├── breadth-first-search.js │ ├── dijkstra.js │ └── unweightedGraph.js ├── dynamic-programming │ ├── cookies_function.js │ ├── linkedList.js │ └── singlyLinkedList.js ├── data-structures │ ├── queue.js │ ├── maxHeap.js │ ├── hashTable.js │ ├── stack.js │ ├── priorityQueue.js │ ├── BinaryTree.js │ ├── doublyLinkedList.js │ └── singlyLinkedList.js └── classes │ └── Tree.js ├── license └── readme.md /src/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.github/issue-template.md: -------------------------------------------------------------------------------- 1 | I am creating an issue because... 2 | -------------------------------------------------------------------------------- /.github/pull-request-template.md: -------------------------------------------------------------------------------- 1 | I am creating a pull request for... 2 | 3 | - [ ] New algorithm 4 | - [ ] Update to an algorithm 5 | - [ ] Fix an error 6 | - [ ] Other - *Describe below* -------------------------------------------------------------------------------- /.github/contributing.md: -------------------------------------------------------------------------------- 1 | ## Contributing 2 | 3 | > Please note that this project is released with a [Contributor Code of Conduct](code-of-conduct.md). By participating in this project you agree to abide by its terms. -------------------------------------------------------------------------------- /algorithms/math/evenNumbers.js: -------------------------------------------------------------------------------- 1 | // Check For Even Numbers 2 | // Author: Abejide Femi 3 | 4 | function evenNumber(arr) { 5 | return arr.filter(a => a % 2 === 0); 6 | } 7 | console.log([1,2,5,6,8,12]) // returns [2,6,8,12] -------------------------------------------------------------------------------- /algorithms/math/naturalNumbersSum.js: -------------------------------------------------------------------------------- 1 | // Change this as the limit of numbers to be added 2 | // const lastNumber = 4 // 1+2+3+4 3 | const lastNumber = 5 // 1+2+3+4+4 4 | 5 | 6 | let sum = lastNumber*(1+lastNumber)*0.5 7 | console.log(sum) 8 | -------------------------------------------------------------------------------- /algorithms/sorting/gulagSort.js: -------------------------------------------------------------------------------- 1 | const gulagSort = ls => { 2 | if (!ls.length) return [] 3 | 4 | const [x, y, ...xs] = ls 5 | 6 | return y == null ? 7 | [x] : x < y ? 8 | [x, ...gulagSort([y, ...xs])] : gulagSort([y, ...xs]) 9 | } 10 | -------------------------------------------------------------------------------- /algorithms/math/randomNumber.js: -------------------------------------------------------------------------------- 1 | const randomNumber = ({ min, max, integer }) => { 2 | 3 | const number = Math.random() * (max - min) + min; 4 | 5 | if (integer) { 6 | return Math.round(number); 7 | } 8 | 9 | return number; 10 | 11 | } 12 | -------------------------------------------------------------------------------- /algorithms/math/greatestCommonDivisor.js: -------------------------------------------------------------------------------- 1 | // JavaScript implementation of greatest common divisor of two positive number 2 | 3 | let gcd = function(a, b) { 4 | if (!b) { 5 | return a; 6 | } 7 | 8 | return gcd(b, a % b); 9 | }; 10 | 11 | console.log(gcd(2154, 458)); -------------------------------------------------------------------------------- /algorithms/math/euclidean.js: -------------------------------------------------------------------------------- 1 | function euclideanAlgorithm(originalA, originalB) { 2 | const a = Math.abs(originalA); 3 | const b = Math.abs(originalB); 4 | 5 | return b === 0 ? a : euclideanAlgorithm(b, a % b); 6 | } 7 | 8 | var gcd = euclideanAlgorithm(1, 3); 9 | console.log(gcd); 10 | -------------------------------------------------------------------------------- /algorithms/math/factorial.js: -------------------------------------------------------------------------------- 1 | // JavaScript implementation of Factorial 2 | 3 | // Author: Niezwan Abdul Wahid 4 | 5 | function factorial(number) { 6 | let val = 1; 7 | 8 | for (let i = 2; i <= number; i += 1) { 9 | val *= i; 10 | } 11 | 12 | return val; 13 | } 14 | 15 | //factorial(13) === 6 227 020 800 -------------------------------------------------------------------------------- /algorithms/others/checkPrime.js: -------------------------------------------------------------------------------- 1 | function isPrime(n){ 2 | var divisor = 2; 3 | 4 | while (n > divisor){ 5 | if(n % divisor == 0){ 6 | return false; 7 | } 8 | else 9 | divisor++; 10 | } 11 | return true; 12 | } 13 | 14 | isPrime(137); 15 | // -> 'true' 16 | isPrime(237); 17 | // -> 'false' 18 | -------------------------------------------------------------------------------- /algorithms/strings/missingNumber.js: -------------------------------------------------------------------------------- 1 | function missingNumber(arr){ 2 | var n = arr.length+1, 3 | sum = 0, 4 | expectedSum = n* (n+1)/2; 5 | 6 | for(var i = 0, len = arr.length; i < len; i++){ 7 | sum += arr[i]; 8 | } 9 | 10 | return expectedSum - sum; 11 | } 12 | 13 | missingNumber([5, 2, 6, 1, 3]); 14 | -------------------------------------------------------------------------------- /algorithms/math/fibonnaci.js: -------------------------------------------------------------------------------- 1 | // FIBONACCI SEQUENCE 2 | 3 | var fibonacci_series = function (n) 4 | { 5 | if (n===1) 6 | { 7 | return [0, 1]; 8 | } 9 | else 10 | { 11 | var s = fibonacci_series(n - 1); 12 | s.push(s[s.length - 1] + s[s.length - 2]); 13 | return s; 14 | } 15 | }; 16 | 17 | console.log(fibonacci_series(8)); 18 | -------------------------------------------------------------------------------- /algorithms/math/computeNCR.js: -------------------------------------------------------------------------------- 1 | // JavaScript implementation of nCr computation 2 | // 3 | // Author: Shriharsha KL 4 | 5 | function fact(n) { 6 | if (n === 0) 7 | return 1; 8 | 9 | return n * fact(n - 1); 10 | } 11 | 12 | function nCr(n, r) { 13 | return fact(n) / (fact(r) * fact(n - r)); 14 | } 15 | 16 | // Test 17 | console.log(nCr(10, 2)) -------------------------------------------------------------------------------- /algorithms/math/euclideanIterative.js: -------------------------------------------------------------------------------- 1 | function euclideanAlgorithmIterative(originalA, originalB) { 2 | let a = Math.abs(originalA); 3 | let b = Math.abs(originalB); 4 | while (a && b && a !== b) { 5 | [a, b] = a > b ? [a - b, b] : [a, b - a]; 6 | } 7 | return a || b; 8 | } 9 | 10 | var gcd = euclideanAlgorithmIterative(4, 7); 11 | 12 | console.log(gcd); 13 | -------------------------------------------------------------------------------- /algorithms/others/primeFactors.js: -------------------------------------------------------------------------------- 1 | function primeFactors(n){ 2 | var factors = [], 3 | divisor = 2; 4 | 5 | while(n>2){ 6 | if(n % divisor == 0){ 7 | factors.push(divisor); 8 | n= n/ divisor; 9 | } 10 | else{ 11 | divisor++; 12 | } 13 | } 14 | return factors; 15 | } 16 | 17 | primeFactors(69); 18 | // -> [3, 23] 19 | -------------------------------------------------------------------------------- /algorithms/math/factorial-recursive.js: -------------------------------------------------------------------------------- 1 | // JavaScript implementation of recursive factorial 2 | 3 | // Author: Jay McDoniel 4 | 5 | function factorial(number) { 6 | let retNum = number ? number : 1; 7 | if (number >= 2) { 8 | retNum *= factorial(number - 1); 9 | } 10 | return retNum; 11 | } 12 | 13 | for (let i = 0; i < 20; i++) { 14 | console.log(factorial(i)); 15 | } -------------------------------------------------------------------------------- /algorithms/sorting/color.js: -------------------------------------------------------------------------------- 1 | function HexToRGB(hex) 2 | { 3 | var bigint = parseInt(hex, 16); 4 | var r = (bigint >> 16) & 255; 5 | var g = (bigint >> 8) & 255; 6 | var b = bigint & 255; 7 | 8 | return new RGB(r, g, b); 9 | 10 | } 11 | 12 | function RGBToHex(rgb) { 13 | return '#' + ((1 << 24) + (rgb.r << 16) + (rgb.g << 8) + rgb.b).toString(16).slice(1); 14 | } 15 | -------------------------------------------------------------------------------- /algorithms/math/degreeRadianConversion.js: -------------------------------------------------------------------------------- 1 | // JavaScript implementation of Degree-Radian Conversion 2 | 3 | // Author: Niezwan Abdul Wahid 4 | 5 | function degreeToRadian(degree) { 6 | return degree * (Math.PI / 180); 7 | } 8 | 9 | function radianToDegree(radian) { 10 | return radian * (180 / Math.PI); 11 | } 12 | 13 | 14 | //degreeToRadian(180) === 3.1415926 15 | 16 | //radianToDegree(3.1415) === 179.994 -------------------------------------------------------------------------------- /algorithms/sorting/shellSort.js: -------------------------------------------------------------------------------- 1 | function shellsort(array) { 2 | for(var g = 0; g < gaps.length; g++) { 3 | var gap = gaps[g]; 4 | for(var i = gap; i < array.length; i++) { 5 | var temp = array[i]; 6 | for(var j = i; j >= gap && array[j - gap] > temp; j -= gap) { 7 | array[j] = array[j - gap]; 8 | } 9 | array[j] = temp; 10 | } 11 | } 12 | return array; 13 | } 14 | -------------------------------------------------------------------------------- /algorithms/math/gcd.js: -------------------------------------------------------------------------------- 1 | // GCD - greatest common divisor or HCF - highest common factor 2 | 3 | function gcd (small, large) { 4 | if (small === 0) { return large } else { return gcd(large % small, small) } 5 | } 6 | 7 | const gcdList = [[6, 9], [6, 12], [12, 18], [7, 14], [7, 13]] 8 | 9 | for (const set of gcdList) { 10 | const small = set[0] 11 | const large = set[1] 12 | console.log(`GCD for ${small} and ${large} is ${gcd(small, large)}`) 13 | } 14 | -------------------------------------------------------------------------------- /algorithms/strings/pigLatin.js: -------------------------------------------------------------------------------- 1 | const pigLatin = str => { 2 | const vows = ['a', 'e', 'i', 'o', 'u'], 3 | res = str.split('') 4 | 5 | if(vows.includes(str.charAt(0))) { 6 | return str += 'way' 7 | } else { 8 | for(let i = 0; i < str.length; i++) { 9 | if(!vows.includes(str[i])) { 10 | res.push(res.shift()) 11 | } else { 12 | res.push('ay') 13 | return res.join('') 14 | } 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /algorithms/math/isPerfectSquare.js: -------------------------------------------------------------------------------- 1 | // JavaScript implementation of to check if a number is a perfect square 2 | // 3 | // Author: Ayoola Akindolani 4 | 5 | var isPerfectSquare = function(num) { 6 | if (num >= 0 && Math.sqrt(num) % 1 === 0) { 7 | console.log("Number is a perfect square."); 8 | } else { 9 | console.log("Number is not a perfect square."); 10 | } 11 | }; 12 | 13 | isPerfectSquare(81); 14 | isPerfectSquare(9); 15 | isPerfectSquare(8); 16 | -------------------------------------------------------------------------------- /algorithms/math/quadrant.js: -------------------------------------------------------------------------------- 1 | // Author: Ferdhika Yudira 2 | // Quadrant detector 3 | 4 | var quadrant = function (x, y){ 5 | var quadrant = 4; 6 | 7 | if(x > 0 && y > 0){ 8 | quadrant = 1; 9 | }else if(x < 0 && y > 0){ 10 | quadrant = 2; 11 | }else if(x < 0 && y < 0){ 12 | quadrant = 3; 13 | } 14 | 15 | return quadrant; 16 | } 17 | 18 | // test 19 | console.log(quadrant(-5, 2)); 20 | console.log(quadrant(5, 2)); 21 | console.log(quadrant(-5, -2)); -------------------------------------------------------------------------------- /algorithms/strings/anagram.js: -------------------------------------------------------------------------------- 1 | //Check if 2 words are anagrams of each other. 2 | var o1 = "arms"; 3 | var o2 = "mars" 4 | //Remove non-letter characters, and sort the letters in alphabetical order. 5 | var n1 = o1.replace(/\W+/g,'').toLowerCase().split("").sort().join(""); 6 | var n2 = o2.replace(/\W+/g,'').toLowerCase().split("").sort().join(""); 7 | var isAnagram = n1==n2; 8 | if(isAnagram) console.log("The two words are anagrams"); 9 | else console.log("The two words are not anagrams"); 10 | -------------------------------------------------------------------------------- /algorithms/strings/integerReversal.js: -------------------------------------------------------------------------------- 1 | // JS algorithm of Integer Reversal 2 | // Author: Irsyad 3 | 4 | // Sample input and output 5 | // reverse(81) will produce 18 6 | // reverse(-67) will produce -76 7 | // reverse(-500) will produce -5 8 | 9 | const reverse = integer => 10 | parseInt(integer 11 | .toString() 12 | .split("") 13 | .reverse() 14 | .join("") 15 | ) * Math.sign(integer); 16 | 17 | // Test 18 | console.log(reverse(4729)); 19 | console.log(reverse(-270)); -------------------------------------------------------------------------------- /algorithms/math/fibonacci-recursive.js: -------------------------------------------------------------------------------- 1 | / JavaScript recursive implementation of Fibonacci item finder 2 | // 3 | // Author: Nikoals Huebecker 4 | 5 | // Time Complexity O(2^n) 6 | 7 | function fibonacci(n){ 8 | if(n<=1) 9 | return n; 10 | else 11 | return fibonacci(n-1) + fibonacci (n-2); 12 | } 13 | 14 | // Test 15 | 16 | console.log("The first item of the sequence is:") 17 | console.log(fibonacci(1)) 18 | 19 | console.log("The tweleth item of the sequence is:") 20 | console.log(fibonacci(12)) 21 | -------------------------------------------------------------------------------- /algorithms/math/checkPrime.js: -------------------------------------------------------------------------------- 1 | // JavaScript implementation of prime number checking 2 | // 3 | // Author: Nikolas Huebecker 4 | 5 | function isPrime(n){ 6 | var divisor = 2; 7 | 8 | while (n > divisor){ 9 | if(n % divisor == 0){ 10 | return false; 11 | }else { 12 | divisor++; 13 | } 14 | } 15 | return true; 16 | } 17 | 18 | // Test 19 | 20 | console.log("The number 137 is prime:" 21 | console.log(isPrime(137)) 22 | 23 | 24 | console.log("The number 16 is prime:" 25 | console.log(isPrime(16)) 26 | -------------------------------------------------------------------------------- /algorithms/searches/sequentialSearch.js: -------------------------------------------------------------------------------- 1 | // JavaScript implementation of Sequential Search 2 | 3 | // Author: Niezwan Abdul Wahid 4 | 5 | let items = [3,7,33,42,5,66,44,65,20,34] 6 | 7 | function sequentialSearch(item) { 8 | for(let i=0; i < items.length; i++) { 9 | if(items[i] === item) { 10 | console.log( item + " found at index " + i); 11 | return true; 12 | } 13 | } 14 | return false; 15 | } 16 | 17 | let item = sequentialSearch(33); 18 | if(!item) { 19 | console.log('Item is not in array.'); 20 | } -------------------------------------------------------------------------------- /algorithms/math/fibonacci.js: -------------------------------------------------------------------------------- 1 | // JavaScript implementation of Fibonacci item finder 2 | // 3 | // Author: Nikoals Huebecker 4 | 5 | // Time Complexity O(n) 6 | 7 | function fibonacci(n){ 8 | var fib = [0, 1]; 9 | 10 | if (n <= 2) return 1; 11 | 12 | for (var i = 2; i <=n; i++ ){ 13 | fib[i] = fib[i-1]+fib[i-2]; 14 | } 15 | 16 | return fib[n]; 17 | } 18 | 19 | // Test 20 | 21 | console.log("The first item of the sequence is:") 22 | console.log(fibonacci(1)) 23 | 24 | console.log("The tweleth item of the sequence is:") 25 | console.log(fibonacci(12)) 26 | -------------------------------------------------------------------------------- /algorithms/ciphers/rot13.js: -------------------------------------------------------------------------------- 1 | // JavaScript implementation of ROT13 2 | // 3 | // Author: NIEZWAN ABDUL WAHID 4 | 5 | function rot13(str) { 6 | var string = []; 7 | 8 | for (var i = 0; i < str.length; i++) { 9 | if ((str.charCodeAt(i) > 77 && str.charCodeAt(i) <= 90) || (str.charCodeAt(i) > 109 && str.charCodeAt(i) <= 122)) { 10 | string.push(String.fromCharCode(str.charCodeAt(i) - 13)); 11 | } else { 12 | string.push(String.fromCharCode(str.charCodeAt(i) + 13)); 13 | } 14 | } 15 | return string.join(""); 16 | } 17 | 18 | // rot13("hello") == "uryyb" -------------------------------------------------------------------------------- /algorithms/strings/largestSumOfTwo.js: -------------------------------------------------------------------------------- 1 | function topSum(arr){ 2 | 3 | var biggest = arr[0], 4 | second = arr[1], 5 | len = arr.length, 6 | i = 2; 7 | 8 | if (len<2) return null; 9 | 10 | if (biggest biggest){ 18 | second = biggest; 19 | biggest = arr[i]; 20 | } 21 | else if (arr[i]>second){ 22 | second = arr[i]; 23 | } 24 | 25 | } 26 | return biggest + second; 27 | } 28 | 29 | topSum([5, 2, 6, 1, 3]); -------------------------------------------------------------------------------- /algorithms/math/collatz.js: -------------------------------------------------------------------------------- 1 | /* Collatz conjecture */ 2 | 3 | function collatz(n) { 4 | var numbers = [] 5 | 6 | while (n > 1) { 7 | numbers.push(n) 8 | if (n % 2 === 0) { 9 | n = n / 2; 10 | } else { 11 | n = (3 * n) + 1; 12 | } 13 | } 14 | numbers.push(n) 15 | return numbers 16 | } 17 | 18 | console.log( 19 | 'Collatz conjecture for n = 11', 20 | collatz(11) 21 | ) 22 | 23 | console.log( 24 | 'Collatz conjecture for n = 27', 25 | collatz(27) 26 | ) 27 | 28 | console.log( 29 | 'Collatz conjecture for n = 51', 30 | collatz(51) 31 | ) 32 | -------------------------------------------------------------------------------- /algorithms/sorting/Distance.js: -------------------------------------------------------------------------------- 1 | function GetDistanceBetweenPoints(v1, v2) { 2 | let dx = v1.x - v2.x; 3 | let dy = v1.y - v2.y; 4 | let dz = v1.z - v2.z; 5 | 6 | return Math.sqrt(dx * dx + dy * dy + dz * dz); 7 | } 8 | function GetDistanceBetweenPointsXZ(v1, v2) { 9 | let v13f = new Vector3f(v1.x, 0.0, v1.z); 10 | let v14f = new Vector3f(v2.x, 0.0, v2.z); 11 | return GetDistanceBetweenPoints(v13f, v14f); 12 | } 13 | 14 | function GetDistanceBetweenPointsXY(v1, v2) { 15 | let v13f = new Vector3f(v1.x, v1.y, 0.0); 16 | let v14f = new Vector3f(v2.x, v2.y, 0.0); 17 | return GetDistanceBetweenPoints(v13f, v14f); 18 | } 19 | -------------------------------------------------------------------------------- /algorithms/strings/palindrome.js: -------------------------------------------------------------------------------- 1 | // Author: Ferdhika Yudira 2 | // Palindrome 3 | 4 | var isPalindrome = function (text){ 5 | text = text.split(''); 6 | index=0; 7 | palindrom=true; 8 | 9 | pTeks=text.length; 10 | 11 | i=0; 12 | while((i 0 && arr[i-1] > arr[i]; i--) 10 | { 11 | let t = arr[i]; 12 | arr[i] = arr[i-1]; 13 | arr[i-1] = t; 14 | } 15 | } 16 | for (let i = 1; i < arr.length; i++) 17 | { 18 | if (arr[i-1] > arr[i]) moveBack(i); 19 | } 20 | return arr; 21 | } 22 | 23 | const array = [3, 0, 2, 5, -1, 4, 1, -2]; 24 | console.log("Original Array"); 25 | console.log(array); 26 | console.log("Sorted Array"); 27 | console.log(gnomeSort(array)); 28 | -------------------------------------------------------------------------------- /algorithms/sorting/selectionSort.js: -------------------------------------------------------------------------------- 1 | // JavaScript implementation of selection sort 2 | // 3 | // Author: Niezwan Abdul Wahid 4 | 5 | function selectionSort(arr){ 6 | let min, temp; 7 | let len = arr.length; 8 | for(let i = 0; i < len; i++){ 9 | min = i; 10 | for(let j = i+1; j= len) return -1; 15 | } 16 | 17 | while (arr[parseInt(prev)] < x) { 18 | prev += 1; 19 | 20 | if (prev === Math.min(step, len)) return -1; 21 | } 22 | if (arr[parseInt(prev)] === x) return prev; 23 | 24 | return -1; 25 | } 26 | 27 | let arr = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]; 28 | 29 | console.log(jumpSearch(arr, 610)); 30 | -------------------------------------------------------------------------------- /algorithms/sorting/countingSort.js: -------------------------------------------------------------------------------- 1 | // JavaScript implementation of counting sort 2 | // 3 | // Author: Dito Baskoro 4 | 5 | function countingSort(arr, min, max) 6 | { 7 | let i, z = 0, count = []; 8 | 9 | for (i = min; i <= max; i++) { 10 | count[i] = 0; 11 | } 12 | 13 | for (i=0; i < arr.length; i++) { 14 | count[arr[i]]++; 15 | } 16 | 17 | for (i = min; i <= max; i++) { 18 | while (count[i]-- > 0) { 19 | arr[z++] = i; 20 | } 21 | } 22 | return arr; 23 | } 24 | 25 | //Test 26 | let array = [2, 0, 3, 5, 4, 1]; 27 | console.log(array.length); 28 | console.log("Original Array"); 29 | console.log(array); 30 | console.log("Sorted Array"); 31 | console.log(countingSort(array, 0, 5)); 32 | -------------------------------------------------------------------------------- /algorithms/sorting/insertionSort.js: -------------------------------------------------------------------------------- 1 | function insertionSort (items) { 2 | for (var i = 0; i < items.length; i++) { 3 | let value = items[i] 4 | // store the current item value so it can be placed right 5 | for (var j = i - 1; j > -1 && items[j] > value; j--) { 6 | // loop through the items in the sorted array (the items from the current to the beginning) 7 | // copy each item to the next one 8 | items[j + 1] = items[j] 9 | } 10 | // the last item we've reached should now hold the value of the currently sorted item 11 | items[j + 1] = value 12 | } 13 | 14 | return list 15 | } 16 | 17 | const list = [54, 26, 93, 17, 77, 31, 44, 55, 20] 18 | console.log(insertionSort(list)) // [ 17, 20, 26, 31, 44, 54, 55, 77, 93 ] 19 | -------------------------------------------------------------------------------- /algorithms/math/pascalsTriangle.js: -------------------------------------------------------------------------------- 1 | function pascalTriangleRecursive(lineNumber) { 2 | if (lineNumber === 0) { 3 | return [1]; 4 | } 5 | 6 | const currentLineSize = lineNumber + 1; 7 | const previousLineSize = currentLineSize - 1; 8 | 9 | const currentLine = []; 10 | 11 | const previousLine = pascalTriangleRecursive(lineNumber - 1); 12 | 13 | for (let numIndex = 0; numIndex < currentLineSize; numIndex += 1) { 14 | const leftCoefficient = numIndex - 1 >= 0 ? previousLine[numIndex - 1] : 0; 15 | const rightCoefficient = 16 | numIndex < previousLineSize ? previousLine[numIndex] : 0; 17 | 18 | currentLine[numIndex] = leftCoefficient + rightCoefficient; 19 | } 20 | 21 | return currentLine; 22 | } 23 | console.log(pascalTriangleRecursive(40)); 24 | -------------------------------------------------------------------------------- /algorithms/sorting/bubbleSort.js: -------------------------------------------------------------------------------- 1 | // JavaScript implementation of bubble sort 2 | // 3 | // Author: Carlos Abraham Hernandez 4 | 5 | function swap(arr, i, j) { 6 | var temp = arr[i]; 7 | arr[i] = arr[j]; 8 | arr[j] = temp; 9 | } 10 | 11 | function bubbleSort(arr) { 12 | var swapped; 13 | do { 14 | swapped = false; 15 | for(var i = 0; i < arr.length; i++) { 16 | if(arr[i] && arr[i + 1] && arr[i] > arr[i + 1]) { 17 | swap(arr, i, i + 1); 18 | swapped = true; 19 | } 20 | } 21 | } while(swapped); 22 | return arr; 23 | } 24 | 25 | // Test 26 | var arr = [46, 24, 33, 10, 2, 81, 50]; 27 | console.log('Unsorted array '); 28 | console.log(arr.slice()); 29 | 30 | console.log('Sorted array '); 31 | console.log(bubbleSort(arr.slice())); 32 | -------------------------------------------------------------------------------- /algorithms/searching/naivePatternSearching.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @author Rashik Ansar 3 | * 4 | * @param {string} txt The text in which pattern has to be searched 5 | * @param {string} pat Pattern to search in string 6 | * @returns {number} The total count of given pattern occurence/s in the text 7 | */ 8 | function naiveSearch(txt, pat) { 9 | let count = 0; 10 | for (let i = 0; i < txt.length; i++) { 11 | for (let j = 0; j < pat.length; j++) { 12 | if (pat[j] !== txt[i + j]) { 13 | break; 14 | } 15 | if (j === pat.length - 1) { 16 | count++; 17 | } 18 | } 19 | } 20 | return count; 21 | } 22 | 23 | let x = naiveSearch('aaabbcbaabcabcaaabcaccaabcaade', 'abc'); 24 | console.log(x); //4 25 | let y = naiveSearch('meow', 'ow'); 26 | console.log(y); //1 27 | -------------------------------------------------------------------------------- /algorithms/searches/binarySearch.js: -------------------------------------------------------------------------------- 1 | // JavaScript implementation of Binary Search 2 | 3 | // Author: Niezwan Abdul Wahid 4 | 5 | // Binary Search only applicable to a sorted array 6 | 7 | let arrayOfItems = [1, 3, 5, 7, 9, 11, 13, 15, 16, 19, 22]; 8 | 9 | function binarySearch(arrayOfItems, itemToFind) { 10 | let low = 0; 11 | let high = arrayOfItems.length - 1; 12 | let mid, pointer; 13 | 14 | while(low <= high) { 15 | mid = Math.floor((low + high) / 2), 16 | pointer = arrayOfItems[mid]; 17 | 18 | if(pointer === itemToFind) { 19 | console.log('Found ' + pointer + " at index " + mid); 20 | return; 21 | } 22 | if(itemToFind < pointer) { 23 | high = mid - 1; 24 | } else { 25 | low = mid + 1; 26 | } 27 | } 28 | console.log("Item not found"); 29 | return null; 30 | } 31 | 32 | binarySearch(arrayOfItems, 7); -------------------------------------------------------------------------------- /algorithms/ciphers/vigenere.js: -------------------------------------------------------------------------------- 1 | function vigenere(plaintext, key) { 2 | const upperKey = key.toUpperCase(); 3 | let decryptedMessage = ''; 4 | for (let i = 0, keyIndex = 0; i < plaintext.length; keyIndex += 1, i += 1) { 5 | const char = plaintext.charCodeAt(i); 6 | const keyCode = upperKey.charCodeAt(keyIndex % upperKey.length); 7 | if (char >= 97 && char <= 122) { 8 | const index = ((char - 97 + keyCode - 65) % 26); 9 | decryptedMessage += String.fromCharCode(index + 97); 10 | } else if (char >= 65 && char <= 90) { 11 | const index = ((char - 65 + keyCode - 65) % 26); 12 | decryptedMessage += String.fromCharCode(index + 65); 13 | } else { 14 | keyIndex -= 1; 15 | decryptedMessage += String.fromCharCode(char); 16 | } 17 | } 18 | return decryptedMessage; 19 | } 20 | 21 | console.log(vigenere('The quick brown fox jumps over the lazy dog.', 'key')); // Dlc aygmo zbsux jmh nswtq yzcb xfo pyjc byk. 22 | -------------------------------------------------------------------------------- /algorithms/math/2sum.js: -------------------------------------------------------------------------------- 1 | // File name: 2sum.js 2 | // Author: boasmarbun (https://github.com/boasmarbun) 3 | // Date created: 02/10/2020 4 | 5 | function twoSum (nums, target) { 6 | var diff = 0; 7 | for (var firstIndex = 0; firstIndex <= nums.length; firstIndex++) { 8 | diff = target - nums[firstIndex]; 9 | var secondIndex = nums.indexOf(diff, firstIndex+1); 10 | if(secondIndex != -1) { 11 | return [firstIndex, secondIndex]; 12 | } 13 | } 14 | return [0]; 15 | }; 16 | 17 | // uncomment below for testing 18 | // var testArray1 = [1,2,3,9] 19 | // var target1 = 5 20 | // var testArray2 = [0,3,4,0] 21 | // var target2 = 0 22 | // var testArray3 = [-2, -3, -7, -13, -6] 23 | // var target3 = -8 24 | // var testArray4 = [] 25 | // var target4 = 2 26 | 27 | // console.log(twoSum(testArray1, target1)) 28 | // console.log(twoSum(testArray2, target2)) 29 | // console.log(twoSum(testArray3, target3)) 30 | // console.log(twoSum(testArray4, target4)) -------------------------------------------------------------------------------- /algorithms/math/spiralMatrix.js: -------------------------------------------------------------------------------- 1 | function getSpiralMatrix (n) { 2 | const matrix = [] 3 | for (let i = 0; i < n; ++i) { matrix.push([]) } 4 | let counter = 1 5 | let startRow = 0 6 | let endRow = n - 1 7 | let startCol = 0 8 | let endCol = n - 1 9 | 10 | while (startCol <= endCol && startRow <= endRow) { 11 | for (let i = startCol; i <= endCol; ++i) { 12 | matrix[startRow][i] = counter 13 | counter++ 14 | } 15 | startRow++ 16 | 17 | for (let i = startRow; i <= endRow; ++i) { 18 | matrix[i][endCol] = counter 19 | counter++ 20 | } 21 | endCol-- 22 | 23 | for (let i = endCol; i >= startCol; --i) { 24 | matrix[endRow][i] = counter 25 | counter++ 26 | } 27 | endRow-- 28 | 29 | for (let i = endRow; i >= startRow; --i) { 30 | matrix[i][startCol] = counter 31 | counter++ 32 | } 33 | startCol++ 34 | } 35 | return matrix 36 | } 37 | 38 | const matrix = getSpiralMatrix(3) 39 | console.log(matrix) 40 | -------------------------------------------------------------------------------- /algorithms/math/smallest-common-multiple.js: -------------------------------------------------------------------------------- 1 | // Find the smallest common multiple of the given parameters that can be evenly divided by both, as well as 2 | // by all numbers in the range between these parameters. 3 | // The range is an array of two numbers, not necessarily be in numerical order. 4 | 5 | function smallestCommons(arr) { 6 | arr.sort(function(a, b) { //sorting given numbers 7 | return b - a; 8 | }); 9 | 10 | var num = []; 11 | for (var i = arr[0]; i >= arr[1]; i--) { //create array of all nums 12 | num.push(i); 13 | } 14 | 15 | var quot = 0; //variables for the quotient that can access them outside the loop 16 | var loop = 1; 17 | var n; 18 | // Run code while n is not the same as the array length. 19 | do { 20 | quot = num[0] * loop * num[1]; 21 | for (n = 2; n < num.length; n++) { 22 | if (quot % num[n] !== 0) { 23 | break; 24 | } 25 | } 26 | loop++; 27 | } while (n !== num.length); 28 | 29 | return quot; 30 | } 31 | 32 | smallestCommons([1,5]); //Example of given numbers 33 | -------------------------------------------------------------------------------- /algorithms/graphs/bfs.js: -------------------------------------------------------------------------------- 1 | /* 2 | A non-recursive implementation of bfs with worst-case space complexity O(|E|) 3 | */ 4 | 5 | function Vertex (name, neighbours) { 6 | this.name = name; 7 | this.neighbours = neighbours; 8 | } 9 | 10 | function bfs (root) { 11 | var visited = {} 12 | var stack = [] 13 | 14 | stack.push(root) 15 | while(!!stack.length) { 16 | var vertex = stack.shift() 17 | 18 | if (!visited[vertex.name]) { 19 | visited[vertex.name] = true 20 | console.log('Visiting vertex ', vertex.name) 21 | 22 | var len = vertex.neighbours.length 23 | for (var index = 0; index < len; index++) { 24 | stack.push(vertex.neighbours[index]) 25 | } 26 | } 27 | } 28 | } 29 | 30 | var root = new Vertex('root', [ 31 | new Vertex('child 1', [ 32 | new Vertex('grandchild 1', []), new Vertex('grandchild 2', []) 33 | ]), 34 | new Vertex('child 2', [ 35 | new Vertex('grandchild 3', []), 36 | ]), 37 | new Vertex('child 3', [ 38 | new Vertex('grandchild 4', [ 39 | new Vertex('grandgrandchild 1', []) 40 | ]), 41 | ]), 42 | ]) 43 | 44 | bfs(root) 45 | -------------------------------------------------------------------------------- /algorithms/strings/checkPalindrome.js: -------------------------------------------------------------------------------- 1 | // JavaScript implementation of palindrome check 2 | // 3 | // Author: Shriharsha KL 4 | 5 | /** 6 | * @description Check if the input is a palindrome 7 | * 8 | * @param {string|number} input 9 | * @returns {boolean} is input a palindrome? 10 | */ 11 | function checkPalindrome(input) { 12 | // Only strings and numbers can be palindrome 13 | if (typeof input !== 'string' && typeof input !== 'number') { 14 | return null; 15 | } 16 | 17 | // Convert given number to string 18 | if (typeof input === 'number') { 19 | input = String(input); 20 | } 21 | 22 | return input === input.split('').reverse().join(''); 23 | } 24 | 25 | // Test 26 | let input = 'ABCDCBA'; 27 | console.log(checkPalindrome(input)); // true 28 | 29 | input = 12321; 30 | console.log(checkPalindrome(input)); // true 31 | 32 | input = 123.321; 33 | console.log(checkPalindrome(input)); // true 34 | 35 | input = 'ABCD'; 36 | console.log(checkPalindrome(input)); // false 37 | 38 | input = 123.4; 39 | console.log(checkPalindrome(input)); // false 40 | 41 | input = {}; 42 | console.log(checkPalindrome(input)) // null 43 | -------------------------------------------------------------------------------- /algorithms/graphs/dfs.js: -------------------------------------------------------------------------------- 1 | /* 2 | A non-recursive implementation of DFS with worst-case space complexity O(|E|) 3 | 4 | according to wiki pseudocode https://en.wikipedia.org/wiki/Depth-first_search 5 | */ 6 | 7 | function Vertex (name, neighbours) { 8 | this.name = name; 9 | this.neighbours = neighbours; 10 | } 11 | 12 | function dfs (root) { 13 | var visited = {} 14 | var stack = [] 15 | 16 | stack.push(root) 17 | while(!!stack.length) { 18 | var vertex = stack.pop() 19 | 20 | if (!visited[vertex.name]) { 21 | visited[vertex.name] = true 22 | console.log('Visiting vertex ', vertex.name) 23 | 24 | var len = vertex.neighbours.length 25 | for (var index = 0; index < len; index++) { 26 | stack.push(vertex.neighbours[index]) 27 | } 28 | } 29 | } 30 | } 31 | 32 | var root = new Vertex('root', [ 33 | new Vertex('child 1', [ 34 | new Vertex('grandchild 1', []), new Vertex('grandchild 2', []) 35 | ]), 36 | new Vertex('child 2', [ 37 | new Vertex('grandchild 3', []), 38 | ]), 39 | new Vertex('child 3', [ 40 | new Vertex('grandchild 4', [ 41 | new Vertex('grandgrandchild 1', []) 42 | ]), 43 | ]), 44 | ]) 45 | 46 | dfs(root) 47 | -------------------------------------------------------------------------------- /algorithms/sorting/pancakeSort.js: -------------------------------------------------------------------------------- 1 | // JavaScript implementation of pancake sort 2 | 3 | function pancake_sort(arr) { 4 | for (let i = arr.length - 1; i >= 1; i--) { 5 | // find the index of the largest element not yet sorted 6 | let max_idx = 0; 7 | let max = arr[0]; 8 | for (let j = 1; j <= i; j++) { 9 | if (arr[j] > max) { 10 | max = arr[j]; 11 | max_idx = j; 12 | } 13 | } 14 | 15 | if (max_idx == i) 16 | continue; // element already in place 17 | 18 | let new_slice; 19 | 20 | // flip arr max element to index 0 21 | if (max_idx > 0) { 22 | new_slice = arr.slice(0, max_idx+1).reverse(); 23 | for ( j = 0; j <= max_idx; j++) 24 | arr[j] = new_slice[j]; 25 | } 26 | 27 | // then flip the max element to its place 28 | new_slice = arr.slice(0, i+1).reverse(); 29 | for ( j = 0; j <= i; j++) 30 | arr[j] = new_slice[j]; 31 | } 32 | return arr; 33 | } 34 | 35 | const array = [3, 0, 2, 5, -1, 4, 1]; 36 | console.log("Original Array"); 37 | console.log(array); 38 | console.log("Sorted Array"); 39 | console.log(pancake_sort(array, 0, 5)); 40 | -------------------------------------------------------------------------------- /algorithms/sorting/mergeSort.js: -------------------------------------------------------------------------------- 1 | 2 | // Split the array into halves and merge them recursively 3 | function mergeSort(arr) { 4 | if (arr.length === 1) { 5 | // return once we hit an array with a single item 6 | return arr 7 | } 8 | 9 | const middle = Math.floor(arr.length / 2) // get the middle item of the array rounded down 10 | const left = arr.slice(0, middle) // items on the left side 11 | const right = arr.slice(middle) // items on the right side 12 | 13 | return merge( 14 | mergeSort(left), 15 | mergeSort(right) 16 | ) 17 | } 18 | 19 | // compare the arrays item by item and return the concatenated result 20 | function merge(left, right) { 21 | let result = [] 22 | let indexLeft = 0 23 | let indexRight = 0 24 | 25 | while (indexLeft < left.length && indexRight < right.length) { 26 | if (left[indexLeft] < right[indexRight]) { 27 | result.push(left[indexLeft]) 28 | indexLeft++ 29 | } else { 30 | result.push(right[indexRight]) 31 | indexRight++ 32 | } 33 | } 34 | 35 | return result.concat(left.slice(indexLeft)).concat(right.slice(indexRight)) 36 | } 37 | 38 | const list = [2, 5, 1, 3, 7, 2, 3, 8, 6, 3] 39 | console.log(mergeSort(list)) 40 | 41 | 42 | //A. Kondov, Medium -------------------------------------------------------------------------------- /license: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 All Algorithms and its contributors (allalgorithms.com) 4 | Copyright (c) 2018 Carlos Abraham (abranhe.com) 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy 7 | of this software and associated documentation files (the "Software"), to deal 8 | in the Software without restriction, including without limitation the rights 9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | copies of the Software, and to permit persons to whom the Software is 11 | furnished to do so, subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included in all 14 | copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | SOFTWARE. -------------------------------------------------------------------------------- /algorithms/sorting/heapSort.js: -------------------------------------------------------------------------------- 1 | // JavaScript implementation of heap sort 2 | // 3 | // Author: Dito Baskoro 4 | 5 | let array_length; 6 | /* to create MAX array */ 7 | function heap_root(input, i) { 8 | let left = 2 * i + 1; 9 | let right = 2 * i + 2; 10 | let max = i; 11 | 12 | if (left < array_length && input[left] > input[max]) { 13 | max = left; 14 | } 15 | 16 | if (right < array_length && input[right] > input[max]) { 17 | max = right; 18 | } 19 | 20 | if (max != i) { 21 | swap(input, i, max); 22 | heap_root(input, max); 23 | } 24 | } 25 | 26 | function swap(input, index_A, index_B) { 27 | let temp = input[index_A]; 28 | 29 | input[index_A] = input[index_B]; 30 | input[index_B] = temp; 31 | } 32 | 33 | function heapSort(input) { 34 | 35 | array_length = input.length; 36 | 37 | for (let i = Math.floor(array_length / 2); i >= 0; i -= 1) { 38 | heap_root(input, i); 39 | } 40 | 41 | for (i = input.length - 1; i > 0; i--) { 42 | swap(input, 0, i); 43 | array_length--; 44 | 45 | 46 | heap_root(input, 0); 47 | } 48 | } 49 | 50 | const arr = [3, 0, 2, 5, -1, 4, 1, -2]; 51 | heapSort(arr); 52 | console.log(arr); 53 | -------------------------------------------------------------------------------- /algorithms/sorting/radixSort.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Gives the number at specified digits place 3 | * @param {number} num 4 | * @param {number} place 5 | */ 6 | function getDigit(num, place) { 7 | return Math.floor(Math.abs(num) / Math.pow(10, place)) % 10; 8 | } 9 | 10 | /** 11 | * Calculate the number of digits in a given number 12 | * @param {number} num 13 | */ 14 | function digits(num) { 15 | if (num !== 0) { 16 | return Math.floor(Math.log10(Math.abs(num))) + 1; 17 | } 18 | return 1; 19 | } 20 | 21 | /** 22 | * Find the maxDigits element in the given array 23 | * @param {number[]} arr 24 | */ 25 | function maxDigits(arr) { 26 | let max = 0; 27 | for (let i = 0; i < arr.length; i++) { 28 | max = Math.max(max, digits(arr[i])); 29 | } 30 | return max; 31 | } 32 | 33 | /** 34 | * Its default base10 digit sorting 35 | * @param {number[]} arr 36 | */ 37 | function radixSort(arr) { 38 | let max = maxDigits(arr); 39 | for (let i = 0; i < max; i++) { 40 | let buckets = Array.from({ length: 10 }, () => []); 41 | for (let j = 0; j < arr.length; j++) { 42 | let digitsValue = getDigit(arr[j], i); 43 | buckets[digitsValue].push(arr[j]); 44 | } 45 | arr = [].concat(...buckets); 46 | } 47 | return arr; 48 | } 49 | 50 | let a = [234, 364, 12, 64, 21315, 75, 23425]; 51 | let b = radixSort(a); 52 | console.log(b); 53 | -------------------------------------------------------------------------------- /algorithms/sorting/quickSort.js: -------------------------------------------------------------------------------- 1 | function quickSort (recievedArray) { 2 | const sortedArray = Object.assign([], recievedArray) 3 | 4 | function partition (array, begin, end) { 5 | const pivot = array[Math.floor((end + begin) / 2)] 6 | let i = begin 7 | let j = end 8 | 9 | while (i <= j) { 10 | while (array[i] < pivot) { 11 | i++ 12 | } 13 | 14 | while (array[j] > pivot) { 15 | j-- 16 | } 17 | 18 | if (i <= j) { 19 | swap(array, i, j) 20 | i++ 21 | j-- 22 | } 23 | } 24 | 25 | return i 26 | } 27 | 28 | function sort (array, begin, end) { 29 | let index 30 | 31 | if (array.length > 1) { 32 | index = partition(array, begin, end) 33 | 34 | if (begin < index - 1) 35 | sort(array, begin, index - 1) 36 | 37 | if (index < end) 38 | sort(array, index, end) 39 | } 40 | 41 | return array 42 | } 43 | 44 | function swap (array, firstIndex, secondIndex) { 45 | const temp = array[firstIndex] 46 | array[firstIndex] = array[secondIndex] 47 | array[secondIndex] = temp 48 | } 49 | 50 | return sort(sortedArray, 0, sortedArray.length - 1) 51 | } 52 | 53 | const array = [3, 2, 9, 7, 24, 11] 54 | 55 | const sortedArray = quickSort(array) 56 | 57 | console.log('array', array) 58 | console.log('sortedArray', sortedArray) 59 | -------------------------------------------------------------------------------- /algorithms/dynamic-programming/cookies_function.js: -------------------------------------------------------------------------------- 1 | // Useful Functions to create , read and delete the cookies. 2 | 3 | (function ($) { 4 | 'use strict'; 5 | 6 | function createCookie(name, value, days) { 7 | var expires; 8 | 9 | if (days) { 10 | var date = new Date(); 11 | date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000); 12 | expires = '; expires=' + date.toGMTString(); 13 | } else { 14 | expires = ''; 15 | } 16 | document.cookie = 17 | encodeURIComponent(name) + 18 | '=' + 19 | encodeURIComponent(value) + 20 | expires + 21 | '; path=/'; 22 | } 23 | 24 | // How to Create Cookies? 25 | createCookie('el_data', 'Prajakta'); 26 | 27 | function readCookie(name) { 28 | var nameEQ = encodeURIComponent(name) + '='; 29 | var ca = document.cookie.split(';'); 30 | for (var i = 0; i < ca.length; i++) { 31 | var c = ca[i]; 32 | while (c.charAt(0) === ' ') c = c.substring(1, c.length); 33 | if (c.indexOf(nameEQ) === 0) 34 | return decodeURIComponent(c.substring(nameEQ.length, c.length)); 35 | } 36 | return null; 37 | } 38 | 39 | // How to read cookies? 40 | var name = readCookie('el_data'); 41 | 42 | function eraseCookie(name) { 43 | createCookie(name, '', -1); 44 | } 45 | 46 | // How to delete cookies? 47 | eraseCookie('el_data'); 48 | })(jQuery); 49 | -------------------------------------------------------------------------------- /algorithms/sorting/BogoSort.js: -------------------------------------------------------------------------------- 1 | /* 2 | * In computer science, bogosort is a particularly ineffective sorting algorithm based on the generate and test paradigm. The algorithm successively generates permutations of its input until it finds one that is sorted. It is not useful for sorting, but may be used for educational purposes, to contrast it with other more realistic algorithms. 3 | */ 4 | 5 | function Bogosort(arr){ 6 | var isSorted = function(arr){ 7 | for(var i = 1; i < arr.length; i++){ 8 | if (arr[i-1] > arr[i]) { 9 | return false; 10 | } 11 | } 12 | return true; 13 | }; 14 | 15 | function shuffle(arr){ 16 | var count = arr.length, temp, index; 17 | 18 | while(count > 0){ 19 | index = Math.floor(Math.random() * count); 20 | count--; 21 | 22 | temp = arr[count]; 23 | arr[count] = arr[index]; 24 | arr[index] = temp; 25 | } 26 | 27 | return arr; 28 | } 29 | 30 | function sort(arr){ 31 | var sorted = false; 32 | while(!sorted){ 33 | arr = shuffle(arr); 34 | sorted = isSorted(arr); 35 | } 36 | return arr; 37 | } 38 | 39 | return sort(arr); 40 | } 41 | 42 | 43 | var array = [3, 0, 2, 5, -1, 4, 1]; 44 | console.log("Original Array Elements"); 45 | console.log(array); 46 | console.log("Sorted Array Elements"); 47 | console.log(Bogosort(array)); -------------------------------------------------------------------------------- /algorithms/others/bigonotaion.js: -------------------------------------------------------------------------------- 1 | // Constant runtime - Big O Notation: "O (1)" 2 | function log(array) { 3 | console.log(array[0]); 4 | console.log(array[1]); 5 | } 6 | 7 | log([1, 2, 3, 4]); 8 | log([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); 9 | 10 | 11 | // Linear runtime - Big O Notation: "O (n)" 12 | function logAll(array) { 13 | for (var i = 0; i < array.length; i++) { 14 | console.log(array[i]); 15 | } 16 | } 17 | 18 | logAll([1, 2, 3, 4, 5]); 19 | logAll([1, 2, 3, 4, 5, 6]); 20 | logAll([1, 2, 3, 4, 5, 6, 7]); 21 | 22 | 23 | // Exponential runtime - Big O Notation: "O (n^2)" 24 | function addAndLog(array) { 25 | for (var i = 0; i < array.length; i++) { 26 | for (var j = 0; j < array.length; j++) { 27 | console.log(array[i] + array[j]); 28 | } 29 | } 30 | } 31 | 32 | addAndLog(['A', 'B', 'C']); // 9 pairs logged out 33 | addAndLog(['A', 'B', 'C', 'D']); // 16 pairs logged out 34 | addAndLog(['A', 'B', 'C', 'D', 'E']); // 25 pairs logged out 35 | 36 | 37 | // Logarithmic runtime - Big O Notation: O (log n) 38 | function binarySearch(array, key) { 39 | var low = 0; 40 | var high = array.length - 1; 41 | var mid; 42 | var element; 43 | 44 | while (low <= high) { 45 | mid = Math.floor((low + high) / 2, 10); 46 | element = array[mid]; 47 | if (element < key) { 48 | low = mid + 1; 49 | } else if (element > key) { 50 | high = mid - 1; 51 | } else { 52 | return mid; 53 | } 54 | } 55 | return -1; 56 | } 57 | -------------------------------------------------------------------------------- /algorithms/data-structures/queue.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @author Rashik Ansar 3 | * 4 | * Implementation of Queue Data structure 5 | * Queue follows FIFO (First In First Out) Principle 6 | */ 7 | 8 | class Node { 9 | constructor(data) { 10 | this.data = data; 11 | this.next = null; 12 | } 13 | } 14 | 15 | class Queue { 16 | constructor() { 17 | this.first = null; 18 | this.last = null; 19 | this.size = 0; 20 | } 21 | 22 | /** 23 | * Adding data to the end of queue 24 | * @param {*} data Data to add in the queue 25 | * @returns {Queue} Returns the queue after adding new data 26 | */ 27 | enqueue(data) { 28 | let newNode = new Node(data); 29 | if (!this.first) { 30 | this.first = newNode; 31 | this.last = newNode; 32 | } else { 33 | this.last.next = newNode; 34 | this.last = newNode; 35 | } 36 | this.size++; 37 | return this; 38 | } 39 | 40 | /** 41 | * Removing data from the beginning of the queue 42 | * @returns Data that is removing from queue 43 | */ 44 | dequeue() { 45 | if (!this.first) { 46 | throw Error( 47 | 'UNDERFLOW::: The queue is empty, there is nothing to remove' 48 | ); 49 | } 50 | let temp = this.first; 51 | if (this.first === this.last) { 52 | this.last = null; 53 | } 54 | this.first = this.first.next; 55 | this.size--; 56 | return temp.data; 57 | } 58 | 59 | /** 60 | * @returns First element in the queue 61 | */ 62 | peek() { 63 | if (!this.first) { 64 | throw Error('Stack is empty'); 65 | } 66 | return this.first.data; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /algorithms/classes/Tree.js: -------------------------------------------------------------------------------- 1 | // JavaScript implementation of Binary Search 2 | 3 | // Author: Youcef Madadi 4 | 5 | // Binary Tree 6 | class BinaryTree{ 7 | left=null; 8 | right=null; 9 | value; 10 | 11 | constructor(value,left,right) { 12 | this.value = value; 13 | if(left instanceof BinaryTree)this.left = left; 14 | if(right instanceof BinaryTree)this.right= right; 15 | } 16 | AddValue(value){ 17 | if(value>this.value){ 18 | if(this.right) return this.right.AddValue(value); 19 | this.right=new BinaryTree(value) 20 | }else if(value value ) { 42 | if(this.left)return this.left.findValue(value); 43 | } 44 | else if( this.value < value ) { 45 | if(this.right) return this.right.findValue(value); 46 | } 47 | else return true 48 | return false; 49 | } 50 | static CreateRandomTree(){ 51 | let root=new BinaryTree(Math.floor(Math.random() * 100)), 52 | deep= Math.floor(Math.random() * 50); 53 | for( let i=0 ; i 0) { 23 | const element = this.heap[index]; 24 | const parentIndex = Math.floor((index - 1) / 2); 25 | const parent = this.heap[parentIndex]; 26 | 27 | if (parent[0] >= element[0]) break; 28 | this.heap[index] = parent; 29 | this.heap[parentIndex] = element; 30 | index = parentIndex; 31 | } 32 | } 33 | 34 | extractMax() { 35 | const max = this.heap[0]; 36 | const tmp = this.heap.pop(); 37 | if (!this.empty()) { 38 | this.heap[0] = tmp; 39 | this.sinkDown(0); 40 | } 41 | return max; 42 | } 43 | 44 | sinkDown(index) { 45 | const left = 2 * index + 1; 46 | const right = 2 * index + 2; 47 | let largest = index; 48 | const length = this.size(); 49 | 50 | if (left < length && this.heap[left][0] > this.heap[largest][0]) { 51 | largest = left; 52 | } 53 | if (right < length && this.heap[right][0] > this.heap[largest][0]) { 54 | largest = right; 55 | } 56 | // swap 57 | if (largest !== index) { 58 | const tmp = this.heap[largest]; 59 | this.heap[largest] = this.heap[index]; 60 | this.heap[index] = tmp; 61 | this.sinkDown(largest); 62 | } 63 | } 64 | } 65 | 66 | const maxHeap = new BinaryHeap(); 67 | maxHeap.insert([4]); 68 | maxHeap.insert([3]); 69 | maxHeap.insert([6]); 70 | maxHeap.insert([1]); 71 | maxHeap.insert([8]); 72 | maxHeap.insert([2]); 73 | 74 | while (!maxHeap.empty()) { 75 | const mx = maxHeap.extractMax(); 76 | console.log(mx); 77 | } 78 | -------------------------------------------------------------------------------- /algorithms/data-structures/hashTable.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @author Rashik Ansar 3 | * 4 | * Implementation of Hash Table 5 | */ 6 | 7 | class HashTable { 8 | constructor(size = 47) { 9 | this.keyMap = new Array(size); 10 | } 11 | 12 | /** 13 | * Hash Function 14 | * Private method to generate hash of the given data 15 | * @param {*} key data to hash 16 | */ 17 | _hash(key) { 18 | let total = 0; 19 | const RANDOM_PRIME = 31; 20 | for (let i = 0; i < Math.min(key.length, 100); i++) { 21 | let char = key[i]; 22 | let value = char.charCodeAt(0) - 96; 23 | total = (total * RANDOM_PRIME + value) % this.keyMap.length; 24 | } 25 | return total; 26 | } 27 | 28 | set(key, value) { 29 | let index = this._hash(key); 30 | if (!this.keyMap[index]) { 31 | this.keyMap[index] = []; 32 | } 33 | this.keyMap[index].push([key, value]); 34 | return this; 35 | } 36 | 37 | get(key) { 38 | let index = this._hash(key); 39 | if (this.keyMap[index]) { 40 | for (let i = 0; i < this.keyMap[index].length; i++) { 41 | if (this.keyMap[index][i][0] === key) { 42 | return this.keyMap[index][i]; 43 | } 44 | } 45 | } 46 | return undefined; 47 | } 48 | 49 | values() { 50 | let valArray = []; 51 | for (let i = 0; i < this.keyMap.length; i++) { 52 | if (this.keyMap[i]) { 53 | for (let j = 0; j < this.keyMap[i].length; j++) { 54 | if (!valArray.includes(this.keyMap[i][j][1])) { 55 | valArray.push(this.keyMap[i][j][1]); 56 | } 57 | } 58 | } 59 | } 60 | return valArray; 61 | } 62 | 63 | keys() { 64 | let keysArray = []; 65 | for (let i = 0; i < this.keyMap.length; i++) { 66 | if (this.keyMap[i]) { 67 | for (let j = 0; j < this.keyMap[i].length; j++) { 68 | if (!keysArray.includes(this.keyMap[i][j][0])) { 69 | keysArray.push(this.keyMap[i][j][0]); 70 | } 71 | } 72 | } 73 | } 74 | return keysArray; 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /algorithms/sorting/flashSort.js: -------------------------------------------------------------------------------- 1 | // JavaScript implementation of flash sort 2 | // Flashsort is a distribution sorting algorithm showing linear computational complexity O(n) 3 | // 4 | // Author: Dito Baskoro 5 | 6 | function flash_sort(arr) 7 | { 8 | let max = 0, min = arr[0]; 9 | let n = arr.length; 10 | let m = ~~(0.45 * n); 11 | let l = new Array(m); 12 | 13 | for (let i = 1; i < n; ++i) { 14 | if (arr[i] < min) { 15 | min = arr[i]; 16 | } 17 | if (arr[i] > arr[max]) { 18 | max = i; 19 | } 20 | } 21 | 22 | if (min === arr[max]) { 23 | return arr; 24 | } 25 | 26 | let c1 = (m - 1) / (arr[max] - min); 27 | 28 | 29 | for (let k = 0; k < m; k++) { 30 | l[k] = 0; 31 | } 32 | for (let j = 0; j < n; ++j) { 33 | k = ~~(c1 * (arr[j] - min)); 34 | ++l[k]; 35 | } 36 | 37 | for (let p = 1; p < m; ++p) { 38 | l[p] = l[p] + l[p - 1]; 39 | } 40 | 41 | let hold = arr[max]; 42 | arr[max] = arr[0]; 43 | arr[0] = hold; 44 | 45 | //permutation 46 | let move = 0, t, flash; 47 | j = 0; 48 | k = m - 1; 49 | 50 | while (move < (n - 1)) { 51 | while (j > (l[k] - 1)) { 52 | ++j; 53 | k = ~~(c1 * (arr[j] - min)); 54 | } 55 | if (k < 0) break; 56 | flash = arr[j]; 57 | while (j !== l[k]) { 58 | k = ~~(c1 * (flash - min)); 59 | hold = arr[t = --l[k]]; 60 | arr[t] = flash; 61 | flash = hold; 62 | ++move; 63 | } 64 | } 65 | 66 | //insertion 67 | for (j = 1; j < n; j++) { 68 | hold = arr[j]; 69 | i = j - 1; 70 | while (i >= 0 && arr[i] > hold) { 71 | arr[i + 1] = arr[i--]; 72 | } 73 | arr[i + 1] = hold; 74 | } 75 | return arr; 76 | } 77 | 78 | //test 79 | const array = [3, 0, 2, 5, -1, 4, 1, -2]; 80 | console.log("Original Array"); 81 | console.log(array); 82 | console.log("Sorted Array"); 83 | console.log(flash_sort(array, 0, 5)); 84 | -------------------------------------------------------------------------------- /algorithms/searching/binarySearch.js: -------------------------------------------------------------------------------- 1 | /** 2 | JavaScript implementation of the binary search algorithm. 3 | 4 | Author: Brendan Albert 5 | 6 | This is a JavaScript iterative (rather than recursive) implementation of the binary search algorithm. 7 | 8 | The binary search algorithm works by looking at the middle element of a list. 9 | The list must be sorted to work correctly. 10 | This implementation uses ascending order. 11 | 12 | If the value being searched for is not the middle element, then we check 13 | if the value is smaller or larger than the middle element. 14 | 15 | This allows the size of the list being searched to be halved each iteration. 16 | 17 | The big O runtime of this algorithm is log(n). 18 | Log(n) is nice because it means that given a huge list, say of 1 million IDs, 19 | it will take no more than 20 iterations to determine if the ID is present. 20 | 21 | Arguments: value (that we are searching for), list_to_search (the list) 22 | 23 | Return: the value if it is found in the list or -1 if the value is not found. 24 | */ 25 | function binarySearch(value, list_to_search) { 26 | 27 | search_value = -1 28 | max_index = list_to_search.length - 1 29 | min_index = 0 30 | middle_index = Math.floor( (max_index + min_index) / 2) 31 | current_element = list_to_search[middle_index] 32 | 33 | while (max_index >= min_index) { 34 | 35 | if (current_element == value) 36 | return current_element 37 | 38 | else if (value > current_element) 39 | min_index = middle_index + 1 40 | 41 | else if (value < current_element) 42 | max_index = middle_index - 1 43 | 44 | middle_index = Math.floor( (min_index + max_index) / 2) 45 | current_element = list_to_search[middle_index] 46 | 47 | } 48 | 49 | return search_value 50 | } 51 | 52 | // Sample lists to test with 53 | id_list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] 54 | odd_list = [1,3,5,7,9,11,13,15,17,19] 55 | short_list = ['allie', 'ben', 'charlie', 'danielle', 'emilio', 'fred', 'gina', 'henry', 'isabella'] 56 | 57 | console.log(binarySearch(3, odd_list)) 58 | -------------------------------------------------------------------------------- /algorithms/graphs/breadth-first-search.js: -------------------------------------------------------------------------------- 1 | // Breadth-first Search 2 | // author: Pavel Kalugin 3 | 4 | class Graph { 5 | constructor(n) { 6 | // the number of vertexes 7 | this.n = n; 8 | 9 | // adjacency list representation 10 | this.adjList = Array.from(Array(n), () => []); 11 | } 12 | 13 | addDirectedEdge(from, to) { 14 | this.adjList[from].push(to); 15 | } 16 | 17 | addEdge(v, w) { 18 | this.adjList[v].push(w); 19 | this.adjList[w].push(v); 20 | } 21 | 22 | // s - the number of the starting vertex 23 | // to - the number of the end vertex 24 | breadthFirstSearch(s) { 25 | if (s < 0 || s >= this.n) { 26 | throw Error('Wrong starting vertex'); 27 | } 28 | 29 | let queue = []; 30 | let visited = new Array(this.n); 31 | let path = new Array(this.n); 32 | let time = new Array(this.n).fill(-1); 33 | 34 | // The first iteration 35 | queue.push(s); 36 | visited[s] = true; 37 | path[s] = -1; 38 | time[s] = 0; 39 | 40 | while (queue.length > 0) { 41 | let v = queue.shift(); 42 | 43 | for (let to of this.adjList[v]) { 44 | if (!visited[to]) { 45 | queue.push(to); 46 | visited[to] = true; 47 | path[to] = v; 48 | time[to] = time[v] + 1; 49 | } 50 | } 51 | } 52 | 53 | return { visited, path, time }; 54 | } 55 | 56 | // Array of distances to vertexes from the starting one 57 | BFS(s) { 58 | return this.breadthFirstSearch(s).time; 59 | } 60 | 61 | findPathToVertex(s, to) { 62 | let { visited, path } = this.breadthFirstSearch(s); 63 | 64 | if (!visited[to]) { 65 | return 'No path'; 66 | } 67 | 68 | let realPath = []; 69 | 70 | for (let v = to; v !== -1; v = path[v]) { 71 | realPath.unshift(v); 72 | } 73 | 74 | return realPath.reduce((out, i) => `${out} ${i}`, `Path from ${s} to ${to}:`); 75 | } 76 | } 77 | 78 | function test() { 79 | let g = new Graph(5); 80 | 81 | g.addDirectedEdge(0, 1); 82 | g.addDirectedEdge(1, 2); 83 | g.addDirectedEdge(2, 3); 84 | g.addDirectedEdge(3, 3); 85 | g.addDirectedEdge(4, 2) 86 | g.addEdge(2, 0); 87 | 88 | 89 | console.log(g.BFS(2)); 90 | console.log(g.findPathToVertex(4, 1)); 91 | } 92 | 93 | test(); 94 | -------------------------------------------------------------------------------- /algorithms/data-structures/stack.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @author Rashik Ansar and Luiz Guerra 3 | * 4 | * Implemtaion of Stack data structure 5 | * Stack follows LIFO (Last In First Out) priniciple 6 | * For Insertion and Deletion its complexity is O(1) 7 | * For Accessing and Searching its complexity is O(n) 8 | * 9 | * @author Jan Tabacki 10 | * Fix in toString method, display all elements and get data property instead of element 11 | * which does no exist. 12 | */ 13 | 14 | class Stack { 15 | /** 16 | * initialize stack instances with null 17 | */ 18 | constructor() { 19 | this.first = null; 20 | this.last = null; 21 | this.size = 0; 22 | } 23 | 24 | /** 25 | * Adding data to Top of the stack 26 | * @param {*} data 27 | * @returns {Stack} 28 | */ 29 | push(data) { 30 | let newNode = new Node(data); 31 | if (!this.first) { 32 | this.first = newNode; 33 | this.last = newNode; 34 | } else { 35 | let temp = this.first; 36 | this.first = newNode; 37 | this.first.next = temp; 38 | } 39 | this.size++; 40 | return this; 41 | } 42 | 43 | /** 44 | * Removing data frpm Top of the stack 45 | * @returns {Node.data} The data that is removing from the stack 46 | */ 47 | pop() { 48 | if (!this.first) { 49 | throw Error('UNDERFLOW :::: Stack is empty, there is nothing to remove'); 50 | } 51 | let current = this.first; 52 | if (this.first === this.last) { 53 | this.last = null; 54 | } 55 | this.first = current.next; 56 | this.size--; 57 | return current.data; 58 | } 59 | 60 | /** 61 | * @returns {Node.data} Top most element of the stack 62 | */ 63 | peek() { 64 | if (!this.first) { 65 | throw Error('Stack is empty'); 66 | } 67 | return this.first.data; 68 | } 69 | 70 | /** 71 | * @returns size of the Stack 72 | */ 73 | size() { 74 | return this.size; 75 | } 76 | 77 | /** 78 | * @returns if Stack is empty 79 | */ 80 | isEmpty() { 81 | return this.size == 0; 82 | } 83 | 84 | /** 85 | * clears the Stack 86 | */ 87 | clear() { 88 | this.first = null; 89 | this.last = null; 90 | this.size = 0; 91 | } 92 | 93 | /** 94 | * @returns the Stack 95 | */ 96 | toString() { 97 | let str = ""; 98 | let aux = this.first; 99 | while (aux) { 100 | str += aux.data + " "; 101 | aux = aux.next; 102 | } 103 | return str; 104 | } 105 | 106 | } 107 | 108 | class Node { 109 | constructor(data) { 110 | this.data = data; 111 | this.next = null; 112 | } 113 | } -------------------------------------------------------------------------------- /.github/code-of-conduct.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | * Trolling, insulting/derogatory comments, and personal or political attacks 21 | * Public or private harassment 22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | * Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Attribution 36 | 37 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 38 | 39 | [homepage]: http://contributor-covenant.org 40 | [version]: http://contributor-covenant.org/version/1/4/ 41 | -------------------------------------------------------------------------------- /algorithms/graphs/dijkstra.js: -------------------------------------------------------------------------------- 1 | // One of the algorithms I was to use in my Microsoft interview was Dijkstra's algorithm. Here is a basic implementation. 2 | function PriorityQueue() { 3 | this._nodes = []; 4 | 5 | this.enqueue = function(priority, key) { 6 | this._nodes.push({key: key, priority: priority }); 7 | this.sort(); 8 | }; 9 | this.dequeue = function() { 10 | return this._nodes.shift().key; 11 | }; 12 | this.sort = function() { 13 | this._nodes.sort(function (a, b) { 14 | return a.priority - b.priority; 15 | }); 16 | }; 17 | this.isEmpty = function() { 18 | return !this._nodes.length; 19 | }; 20 | } 21 | 22 | /** 23 | * Pathfinding starts here 24 | */ 25 | function Graph(){ 26 | var INFINITY = 1/0; 27 | this.vertices = {}; 28 | 29 | this.addVertex = function(name, edges){ 30 | this.vertices[name] = edges; 31 | }; 32 | 33 | this.shortestPath = function(start, finish) { 34 | var nodes = new PriorityQueue(), 35 | distances = {}, 36 | previous = {}, 37 | path = [], 38 | smallest, vertex, neighbor, alt; 39 | 40 | for (vertex in this.vertices) { 41 | if (vertex === start) { 42 | distances[vertex] = 0; 43 | nodes.enqueue(0, vertex); 44 | } 45 | else { 46 | distances[vertex] = INFINITY; 47 | nodes.enqueue(INFINITY, vertex); 48 | } 49 | 50 | previous[vertex] = null; 51 | } 52 | 53 | while (!nodes.isEmpty()) { 54 | smallest = nodes.dequeue(); 55 | 56 | if (smallest === finish) { 57 | path = []; 58 | 59 | while (previous[smallest]) { 60 | path.push(smallest); 61 | smallest = previous[smallest]; 62 | } 63 | 64 | break; 65 | } 66 | 67 | if (!smallest || distances[smallest] === INFINITY){ 68 | continue; 69 | } 70 | 71 | for (neighbor in this.vertices[smallest]) { 72 | alt = distances[smallest] + this.vertices[smallest][neighbor]; 73 | 74 | if (alt < distances[neighbor]) { 75 | distances[neighbor] = alt; 76 | previous[neighbor] = smallest; 77 | 78 | nodes.enqueue(alt, neighbor); 79 | } 80 | } 81 | } 82 | 83 | return path; 84 | }; 85 | } 86 | 87 | var g = new Graph(); 88 | 89 | g.addVertex('A', {B: 7, C: 8}); 90 | g.addVertex('B', {A: 7, F: 2}); 91 | g.addVertex('C', {A: 8, F: 6, G: 4}); 92 | g.addVertex('D', {F: 8}); 93 | g.addVertex('E', {H: 1}); 94 | g.addVertex('F', {B: 2, C: 6, D: 8, G: 9, H: 3}); 95 | g.addVertex('G', {C: 4, F: 9}); 96 | g.addVertex('H', {E: 1, F: 3}); 97 | 98 | // Log test, with the addition of reversing the path and prepending the first node so it's more readable 99 | console.log(g.shortestPath('A', 'H').concat(['A']).reverse()); 100 | -------------------------------------------------------------------------------- /algorithms/dynamic-programming/linkedList.js: -------------------------------------------------------------------------------- 1 | // LinkedList and Node function Constructor 2 | function LinkedList() { 3 | this.head = null; 4 | this.tail = null; 5 | }; 6 | 7 | function Node(value, next, prev) { 8 | this.value = value; 9 | this.next = next; 10 | this.prev = prev; 11 | }; 12 | 13 | // Add to head 14 | 15 | LinkedList.prototype.addHead = function(value) { 16 | var newNode = new Node(value, this.head, null); 17 | if(this.head) { 18 | this.head.prev = newNode; 19 | } else { 20 | this.tail = newNode; 21 | } 22 | this.head = newNode; 23 | }; 24 | 25 | var LL = new LinkedList(); 26 | LL.addHead(100); 27 | LL.addHead(200); 28 | LL.addHead(300); 29 | LL.addHead(200); 30 | console.log(LL); 31 | 32 | // Add to tail 33 | LinkedList.prototype.addTail = function(value) { 34 | var newNode = new Node(value, null, this.tail); 35 | if(this.tail) { 36 | this.tail.next = newNode; 37 | }else { 38 | this.head = newNode; 39 | } 40 | this.tail = newNode; 41 | }; 42 | 43 | LL.addTail(100); 44 | LL.addTail(200); 45 | LL.addTail(300); 46 | console.log(LL); 47 | console.log(ll.head.value); 48 | 49 | // Remove from head 50 | LinkedList.prototype.removeHead = function(){ 51 | if(this.head == null) { 52 | return null; 53 | } 54 | else { 55 | var val = this.head.value; 56 | this.head = this.head.next; 57 | } 58 | if(!this.head) this.tail = null; 59 | return val; 60 | }; 61 | 62 | var ll = new LinkedList(); 63 | console.log(LL.removeHead()); 64 | console.log(LL); 65 | 66 | // Remove from tail 67 | LinkedList.prototype.removeTail = function() { 68 | if(!this.tail) return null; 69 | var val = this.tail.value; 70 | this.tail = this.tail.prev; 71 | if(this.tail) this.tail.next = null; 72 | else this.head = null; 73 | return val; 74 | } 75 | 76 | console.log(LL.removeTail()); 77 | console.log(LL.removeTail()); 78 | console.log(LL.removeTail()); 79 | console.log(LL); 80 | 81 | // search in LinkedList 82 | LinkedList.prototype.search = function(searchValue) { 83 | if(!this.head) return null; 84 | var currentNode = this.head; 85 | while(currentNode){ 86 | if(currentNode.value === searchValue) return currentNode.value; 87 | currentNode = currentNode.next; 88 | } 89 | return null; 90 | } 91 | 92 | console.log(LL.search(100)); 93 | 94 | // find indexOf element in LinkedList 95 | LinkedList.prototype.indexOf = function(value) { 96 | if(!this.head) return null; 97 | var currentNode = this.head; 98 | var counter = 0; 99 | var indexArr = new Array; 100 | while(currentNode){ 101 | if(currentNode.value === value){ 102 | indexArr.push(counter); 103 | } 104 | counter++; 105 | currentNode = currentNode.next; 106 | } 107 | return indexArr; 108 | } 109 | 110 | console.log(LL.indexOf(200)); 111 | 112 | -------------------------------------------------------------------------------- /algorithms/data-structures/priorityQueue.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @author Rashik Ansar 3 | * 4 | * Implemntaion of priority queue 5 | * Lower the priority value higher its priority 6 | * under the hood its implementing minBinaryHeap 7 | */ 8 | class PriorityQueue { 9 | constructor() { 10 | this.values = []; 11 | } 12 | 13 | /** 14 | * Adding data to the queue 15 | * @param {*} data Data to add into queue 16 | * @param {*} priority Priority of the data 17 | * @returns {PriorityQueue} 18 | */ 19 | enqueue(data, priority) { 20 | let temp = new Node(data, priority); 21 | this.values.push(temp); 22 | this.bubbleUp(); 23 | return this; 24 | } 25 | 26 | /** 27 | * removing a node from the queue 28 | * @returns {Node} 29 | */ 30 | dequeue() { 31 | const min = this.values[0]; 32 | const end = this.values.pop(); 33 | if (this.values.length > 0) { 34 | this.values[0] = end; 35 | this.sinkDown(); 36 | } 37 | return min; 38 | } 39 | 40 | /** 41 | * enqueue helper function 42 | */ 43 | bubbleUp() { 44 | let index = this.values.length - 1; 45 | const element = this.values[index]; 46 | while (index > 0) { 47 | let parentIndex = Math.floor((index - 1) / 2); 48 | let parent = this.values[parentIndex]; 49 | // if (element.priority <= parent.priority) break; //maxBinaryHeap condition 50 | if (element.priority >= parent.priority) break; //minBinaryHeap condition 51 | this.values[parentIndex] = element; 52 | this.values[index] = parent; 53 | index = parentIndex; 54 | } 55 | } 56 | 57 | /** 58 | * dequeue helper function 59 | */ 60 | sinkDown() { 61 | let index = 0; 62 | const length = this.values.length; 63 | const element = this.values[index]; 64 | while (true) { 65 | let leftChildIndex = 2 * index + 1; 66 | let rightChildIndex = 2 * index + 2; 67 | let leftChild; 68 | let rightChild; 69 | let swap = null; 70 | 71 | if (leftChildIndex < length) { 72 | leftChild = this.values[leftChildIndex]; 73 | // Change below comparision operators to make maxBinaryHeap 74 | if (leftChild.priority < element.priority) { 75 | swap = leftChildIndex; 76 | } 77 | } 78 | 79 | if (rightChildIndex < length) { 80 | rightChild = this.values[rightChildIndex]; 81 | // Change below comparision operators to make maxBinaryHeap 82 | if ( 83 | (!swap && rightChild.priority < element.priority) || 84 | (swap && rightChild.priority < leftChild.priority) 85 | ) { 86 | swap = rightChildIndex; 87 | } 88 | } 89 | 90 | if (!swap) break; 91 | 92 | this.values[index] = this.values[swap]; 93 | this.values[swap] = element; 94 | index = swap; 95 | } 96 | } 97 | } 98 | 99 | class Node { 100 | constructor(data, priority) { 101 | this.data = data; 102 | this.priority = priority; 103 | } 104 | } 105 | 106 | let a = new PriorityQueue(); 107 | a.enqueue('Common Cold', 10); 108 | a.enqueue('Gunshot wound', 2); 109 | a.enqueue('Fever', 8); 110 | 111 | console.log(a); 112 | a.dequeue(); 113 | console.log(a); 114 | a.dequeue(); 115 | console.log(a); 116 | a.dequeue(); 117 | console.log(a); 118 | -------------------------------------------------------------------------------- /algorithms/data-structures/BinaryTree.js: -------------------------------------------------------------------------------- 1 | class Node { 2 | constructor(value) { 3 | this.value = value; 4 | this.left = null; 5 | this.right = null; 6 | } 7 | } 8 | 9 | class BinarySearchTree { 10 | constructor() { 11 | this.root = null; 12 | } 13 | 14 | insert(value) { 15 | var newNode = new Node(value); 16 | if (this.root === null) { 17 | this.root = newNode; 18 | return this; 19 | } 20 | var current = this.root; 21 | while (true) { 22 | if (value === current.value) return undefined; 23 | if (value < current.value) { 24 | if (current.left === null) { 25 | current.left = newNode; 26 | return this; 27 | } 28 | current = current.left; 29 | } else { 30 | if (current.right === null) { 31 | current.right = newNode; 32 | return this; 33 | } 34 | current = current.right; 35 | } 36 | } 37 | } 38 | 39 | find(value) { 40 | if (this.root === null) return false; 41 | var current = this.root, 42 | found = false; 43 | while (current && !found) { 44 | if (value < current.value) { 45 | current = current.left; 46 | } else if (value > current.value) { 47 | current = current.right; 48 | } else { 49 | found = true; 50 | } 51 | } 52 | if (!found) return undefined; 53 | return current; 54 | } 55 | 56 | contains(value) { 57 | if (this.root === null) return false; 58 | var current = this.root, 59 | found = false; 60 | while (current && !found) { 61 | if (value < current.value) current = current.left; 62 | else if (value > current.value) current = current.right; 63 | else return true; 64 | } 65 | return false; 66 | } 67 | 68 | BreadthFirstSearch() { 69 | let node = this.root, 70 | data = [], 71 | queue = []; 72 | queue.push(node); 73 | 74 | while (queue.length) { 75 | node = queue.shift(); 76 | data.push(node.value); 77 | if (node.left) queue.push(node.left); 78 | if (node.right) queue.push(node.right); 79 | } 80 | 81 | return data; 82 | } 83 | 84 | DepthFirstSearchPreOrder() { 85 | let data = []; 86 | function traverse(node) { 87 | data.push(node.value); 88 | if (node.left) traverse(node.left); 89 | if (node.right) traverse(node.right); 90 | } 91 | traverse(this.root); 92 | return data; 93 | } 94 | DepthFirstSearchPostOrder() { 95 | let data = []; 96 | function traverse(node) { 97 | if (node.left) traverse(node.left); 98 | if (node.right) traverse(node.right); 99 | data.push(node.value); 100 | } 101 | traverse(this.root); 102 | return data; 103 | } 104 | DepthFirstSearchInOrder() { 105 | let data = []; 106 | function traverse(node) { 107 | if (node.left) traverse(node.left); 108 | data.push(node.value); 109 | if (node.right) traverse(node.right); 110 | } 111 | traverse(this.root); 112 | return data; 113 | } 114 | } 115 | 116 | // 10 117 | // 5 13 118 | // 2 7 11 16 119 | 120 | var tree = new BinarySearchTree(); 121 | tree.insert(10); 122 | tree.insert(5); 123 | tree.insert(13); 124 | tree.insert(11); 125 | tree.insert(2); 126 | tree.insert(16); 127 | tree.insert(7); 128 | 129 | console.log("node with value 13:", tree.find(13)); 130 | console.log("node with value 19:", tree.find(19)); 131 | 132 | console.log("tree coontais node with value 2:", tree.contains(2)); 133 | console.log("tree coontais node with value 534:", tree.contains(534)); 134 | 135 | console.log("BreadthFirstSearch:", tree.BreadthFirstSearch()); 136 | console.log("DepthFirstSearchPreOrder:", tree.DepthFirstSearchPreOrder()); 137 | console.log("DepthFirstSearchPostOrder:", tree.DepthFirstSearchPostOrder()); 138 | console.log("DepthFirstSearchInOrder:", tree.DepthFirstSearchInOrder()); 139 | -------------------------------------------------------------------------------- /algorithms/graphs/unweightedGraph.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @author Rashik Ansar 3 | * Implemtaion of graph with the help of Adjacency List 4 | * Its Unweighted graph implemetation 5 | */ 6 | 7 | class Graph { 8 | constructor() { 9 | this.adjacencyList = {}; 10 | } 11 | 12 | /** 13 | * Adding a vertex to the graph 14 | * @param {*} vertex The data of the vertex to add into graph 15 | * @returns {Graph} 16 | */ 17 | addVertex(vertex) { 18 | if (this.adjacencyList[vertex]) { 19 | throw Error(`${vertex} already exist in graph... `); 20 | } else { 21 | this.adjacencyList[vertex] = []; 22 | } 23 | // return this; 24 | } 25 | 26 | /** 27 | * Removing a vertex from the graph 28 | * @param {*} vertex The data of the vertex to remove from graph 29 | */ 30 | removeVertex(vertex) { 31 | if (this.adjacencyList[vertex]) { 32 | while (this.adjacencyList[vertex].length) { 33 | const itemInArray = this.adjacencyList[vertex].pop(); 34 | this.removeEdge(vertex, itemInArray); 35 | } 36 | delete this.adjacencyList[vertex]; 37 | // return this; // Added for testing before traversal methods 38 | } else { 39 | throw Error(`${vertex} doesn't exist...`); 40 | } 41 | } 42 | 43 | /** 44 | * Adding an edge between two vertices in the graph 45 | * @param {*} vertex1 46 | * @param {*} vertex2 47 | */ 48 | addEdge(vertex1, vertex2) { 49 | if (this.adjacencyList[vertex1] && this.adjacencyList[vertex2]) { 50 | this.adjacencyList[vertex1].push(vertex2); 51 | this.adjacencyList[vertex2].push(vertex1); 52 | // return this; 53 | } else { 54 | throw Error('Given vertex/vertices might not exist in graph...'); 55 | } 56 | } 57 | 58 | /** 59 | * Removing an existing edge between two vertices in the graph 60 | * @param {*} vertex1 61 | * @param {*} vertex2 62 | */ 63 | removeEdge(vertex1, vertex2) { 64 | if (this.adjacencyList[vertex1] && this.adjacencyList[vertex2]) { 65 | this.adjacencyList[vertex1] = this.adjacencyList[vertex1].filter( 66 | i => i !== vertex2 67 | ); 68 | this.adjacencyList[vertex2] = this.adjacencyList[vertex2].filter( 69 | i => i !== vertex1 70 | ); 71 | // return this; 72 | } else { 73 | throw Error('Given vertex/vertices might not exist in graph...'); 74 | } 75 | } 76 | 77 | /** 78 | * Travesal of the graph by breadth-first approach 79 | * @param {*} start Starting vertex for traversal 80 | * @returns {[]} 81 | */ 82 | breadthFirstTraversal(start) { 83 | const queue = []; 84 | const result = []; 85 | const visited = {}; 86 | let current; 87 | queue.push(start); 88 | visited[start] = true; 89 | 90 | while (queue.length) { 91 | current = queue.shift(); 92 | result.push(current); 93 | this.adjacencyList[current].forEach(x => { 94 | if (!visited[x]) { 95 | visited[x] = true; 96 | queue.push(x); 97 | } 98 | }); 99 | } 100 | return result; 101 | } 102 | 103 | /** 104 | * Depth First Traversal (recursive approach) 105 | * 106 | * @param {*} start Starting vertex for traversal 107 | * @returns {[]} 108 | */ 109 | DFTrecursuive(start) { 110 | const visited = {}; 111 | const result = []; 112 | const adjacencyList = this.adjacencyList; 113 | function dfs(vertex) { 114 | if (!vertex) { 115 | throw Error('Incorrect starting vertex!'); 116 | } 117 | visited[vertex] = true; 118 | result.push(vertex); 119 | adjacencyList[vertex].forEach(x => { 120 | if (!visited[x]) { 121 | return dfs(x); 122 | } 123 | }); 124 | } 125 | dfs(start); 126 | return result; 127 | } 128 | /** 129 | * Depth First Traversal (Iterative approach) 130 | * 131 | * @param {*} start Starting vertex for traversal 132 | * @returns {[]} 133 | */ 134 | DFTiterative(start) { 135 | const stack = []; 136 | const visited = {}; 137 | const result = []; 138 | let current; 139 | 140 | stack.push(start); 141 | visited[start] = true; 142 | while (stack.length) { 143 | current = stack.pop(); 144 | result.push(current); 145 | this.adjacencyList[current].forEach(x => { 146 | if (!visited[x]) { 147 | visited[x] = true; 148 | stack.push(x); 149 | } 150 | }); 151 | } 152 | return result; 153 | } 154 | } 155 | -------------------------------------------------------------------------------- /algorithms/data-structures/doublyLinkedList.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @author Rashik Ansar 3 | * 4 | * Implementation of doubly linked list 5 | * Doubly linked list is a linear data structure 6 | */ 7 | 8 | class Node { 9 | constructor(data) { 10 | this.data = data; 11 | this.next = null; 12 | this.prev = null; 13 | } 14 | } 15 | 16 | class DoublyLinkedList { 17 | constructor() { 18 | this.head = null; 19 | this.tail = null; 20 | this.length = 0; 21 | } 22 | 23 | /** 24 | * Adding new node as a tail of the linked list 25 | * @param {any} data This dataue is added at the end of list 26 | * @returns {DoublyLinkedList} LinkedList after adding new node as tail 27 | */ 28 | push(data) { 29 | let temp = new Node(data); 30 | if (!this.head) { 31 | this.head = temp; 32 | this.tail = temp; 33 | } else { 34 | this.tail.next = temp; 35 | temp.prev = this.tail; 36 | this.tail = temp; 37 | } 38 | this.length++; 39 | return this; 40 | } 41 | 42 | /** 43 | * Adding new node as a head of the linked list 44 | * @param {any} data This dataue is added at the beginning of the list 45 | * @returns {DoublyLinkedList} LinkedList after adding a new node as head 46 | */ 47 | unshift(data) { 48 | let current = new Node(data); 49 | if (!this.head) { 50 | this.head = current; 51 | this.tail = current; 52 | } else { 53 | this.head.prev = current; 54 | current.next = this.head; 55 | this.head = current; 56 | } 57 | this.length++; 58 | return this; 59 | } 60 | 61 | /** 62 | * Adding a node to the linkedList at specified position 63 | * @param {number} index Position at which new node to insert 64 | * @param {any} data dataue in the new node 65 | * @returns {DoublyLinkedList} LinkedList after inserting a new node 66 | */ 67 | insert(index, data) { 68 | if (index < 0 || index > this.length) { 69 | throw Error('Given index is out of range'); 70 | } 71 | if (index === this.length) { 72 | return this.push(data); 73 | } 74 | if (index === 0) { 75 | return this.unshift(data); 76 | } 77 | let insertNode = new Node(data); 78 | let previous = this.get(index - 1); 79 | let temp = previous.next; 80 | previous.next = insertNode; 81 | insertNode.prev = previous; 82 | insertNode.next = temp; 83 | temp.prev = insertNode; 84 | this.length++; 85 | return this; 86 | } 87 | 88 | /** 89 | * Removes the node at the end of linked list(tail of linked list) 90 | * @returns {Node} the node which is going to pop 91 | */ 92 | pop() { 93 | if (!this.head) { 94 | throw Error( 95 | 'UNDERFLOW :::: LinkedList is empty, there is nothing to remove' 96 | ); 97 | } 98 | let temp = this.tail; 99 | if (this.length === 1) { 100 | this.head = null; 101 | this.tail = null; 102 | } else { 103 | this.tail = temp.prev; 104 | this.tail.next = null; 105 | temp.prev = null; 106 | } 107 | this.length--; 108 | return temp; 109 | } 110 | 111 | /** 112 | * Removes the node from the beginnig of linked list(head of linked list) 113 | * @returns {Node} the node which is going to shift 114 | */ 115 | shift() { 116 | if (!this.head) { 117 | throw Error( 118 | 'UNDERFLOW :::: LinkedList is empty, there is nothing to remove' 119 | ); 120 | } 121 | let current = this.head; 122 | if (this.length === 1) { 123 | this.head = null; 124 | this.tail = null; 125 | } else { 126 | this.head = current.next; 127 | this.head.prev = null; 128 | current.next = null; 129 | } 130 | this.length--; 131 | return current; 132 | } 133 | 134 | /** 135 | * Removes a node from the linkedList at specified position 136 | * @param {number} index 137 | * @returns {Node} Node which is removed from LinkedList 138 | */ 139 | remove(index) { 140 | if (index < 0 || index > this.length) { 141 | throw Error('Given index is out of range'); 142 | } 143 | if (index === this.length - 1) { 144 | return this.pop(); 145 | } 146 | if (index === 0) { 147 | return this.shift(); 148 | } 149 | let removeNode = this.get(index); 150 | let before = removeNode.prev; 151 | let after = removeNode.next; 152 | before.next = after; 153 | after.prev = before; 154 | removeNode.next = null; 155 | removeNode.prev = null; 156 | this.length--; 157 | return removeNode; 158 | } 159 | 160 | /** 161 | * Retrieve the node at specified index 162 | * @param {number} index Index of the node 163 | * @returns {Node} LinkedList Node at specified index 164 | */ 165 | get(index) { 166 | if (index < 0 || index >= this.length) { 167 | throw Error('Given index is out of range'); 168 | } 169 | let current; 170 | if (index <= this.length / 2) { 171 | let counter = 0; 172 | current = this.head; 173 | while (counter !== index) { 174 | current = current.next; 175 | counter++; 176 | } 177 | } else { 178 | let counter = this.length - 1; 179 | current = this.tail; 180 | while (counter !== index) { 181 | current = current.prev; 182 | counter--; 183 | } 184 | } 185 | return current; 186 | } 187 | 188 | /** 189 | * Change the data of node at specified index 190 | * @param {number} index Index of the node 191 | * @param {any} data data replaces the current data at given index 192 | * @returns {DoublyLinkedList} LinkedList 193 | */ 194 | set(index, data) { 195 | let existedNode = this.get(index); 196 | if (existedNode) { 197 | existedNode.data = data; 198 | return this; 199 | } 200 | } 201 | 202 | /** 203 | * Traversing or Printing the Linked list 204 | */ 205 | traverse() { 206 | let current = this.head; 207 | console.log(this.length); 208 | while (current) { 209 | console.log(current.data); 210 | current = current.next; 211 | } 212 | } 213 | 214 | /** 215 | * @returns {[]} Linkedlist data as elements in Array 216 | */ 217 | listAsArray() { 218 | let arr = []; 219 | let current = this.head; 220 | while (current) { 221 | arr.push(current.data); 222 | current = current.next; 223 | } 224 | return arr; 225 | } 226 | } 227 | -------------------------------------------------------------------------------- /algorithms/data-structures/singlyLinkedList.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @author Rashik Ansar 3 | * 4 | * Implementation of singly linked list 5 | * Singly linked list is a linear data strucutre 6 | */ 7 | 8 | class Node { 9 | constructor(data) { 10 | this.data = data; 11 | this.next = null; 12 | } 13 | } 14 | 15 | class SinglyLinkedList { 16 | constructor() { 17 | this.head = null; 18 | this.tail = null; 19 | this.length = 0; 20 | } 21 | 22 | /** 23 | * Adding new node as a tail of the linked list 24 | * @param {any} data This dataue is added at the end of list 25 | * @returns {SinglyLinkedList} LinkedList after adding new node as tail 26 | */ 27 | push(data) { 28 | let temp = new Node(data); 29 | if (!this.head) { 30 | this.head = temp; 31 | this.tail = this.head; // temp 32 | } else { 33 | this.tail.next = temp; 34 | this.tail = temp; 35 | } 36 | this.length++; 37 | return this; 38 | } 39 | 40 | /** 41 | * Adding new node as a head of the linked list 42 | * @param {any} data This dataue is added at the beginning of the list 43 | * @returns {SinglyLinkedList} LinkedList after adding a new node as head 44 | */ 45 | unshift(data) { 46 | let temp = new Node(data); 47 | if (!this.head) { 48 | this.head = temp; 49 | this.tail = this.head; 50 | } else { 51 | temp.next = this.head; 52 | this.head = temp; 53 | } 54 | this.length++; 55 | return this; 56 | } 57 | 58 | /** 59 | * Adding a node to the linkedList at specified position 60 | * @param {number} index Position at which new node to insert 61 | * @param {any} data dataue in the new node 62 | * @returns {SinglyLinkedList} LinkedList after inserting a new node 63 | */ 64 | insert(index, data) { 65 | if (index < 0 || index > this.length) { 66 | throw Error('Given index is out of range'); 67 | } 68 | if (index === this.length) { 69 | return this.push(data); 70 | } 71 | if (index === 0) { 72 | return this.unshift(data); 73 | } 74 | let insertNode = new Node(data); 75 | let previous = this.get(index - 1); 76 | let temp = previous.next; 77 | previous.next = insertNode; 78 | insertNode.next = temp; 79 | this.length++; 80 | return this; 81 | } 82 | 83 | /** 84 | * Removes the node at the end of linked list(tail of linked list) 85 | * @returns {Node} the node which is going to pop 86 | */ 87 | pop() { 88 | if (!this.head) { 89 | throw Error( 90 | 'UNDERFLOW :::: LinkedList is empty, there is nothing to remove' 91 | ); 92 | } 93 | let current = this.head; 94 | let temp = current; 95 | while (current.next) { 96 | temp = current; 97 | current = current.next; 98 | } 99 | this.tail = temp; 100 | this.tail.next = null; 101 | this.length--; 102 | this.emptyListCheck(); 103 | return current; 104 | } 105 | 106 | /** 107 | * Removes the node from the beginnig of linked list(head of linked list) 108 | * @returns {Node} the node which is going to shift 109 | */ 110 | shift() { 111 | if (!this.head) { 112 | throw Error( 113 | 'UNDERFLOW :::: LinkedList is empty, there is nothing to remove' 114 | ); 115 | } 116 | let current = this.head; 117 | this.head = current.next; 118 | this.length--; 119 | this.emptyListCheck(); 120 | return current; 121 | } 122 | 123 | /** 124 | * Removes a node from the linkedList at specified position 125 | * @param {number} index 126 | * @returns {Node} Node which is removed from LinkedList 127 | */ 128 | remove(index) { 129 | if (index < 0 || index > this.length) { 130 | throw Error('Given index is out of range'); 131 | } 132 | if (index === this.length - 1) { 133 | return this.pop(); 134 | } 135 | if (index === 0) { 136 | return this.shift(); 137 | } 138 | let previous = this.get(index - 1); 139 | let temp = previous.next; 140 | previous.next = temp.next; 141 | this.length--; 142 | return temp; 143 | } 144 | 145 | /** 146 | * Retrieve the node at specified index 147 | * @param {number} index Index of the node 148 | * @returns {Node} LinkedList Node at specified index 149 | */ 150 | get(index) { 151 | if (index < 0 || index >= this.length) { 152 | throw Error('Given index is out of range'); 153 | } 154 | let counter = 0; 155 | let current = this.head; 156 | while (counter !== index) { 157 | current = current.next; 158 | counter++; 159 | } 160 | return current; 161 | } 162 | 163 | /** 164 | * Change the data of node at specified index 165 | * @param {number} index Index of the node 166 | * @param {any} data data replaces the current data at given index 167 | * @returns {SinglyLinkedList} LinkedList 168 | */ 169 | set(index, data) { 170 | // Here error checking will be done by the get method itself 171 | // No need to specify explicitly 172 | let existedNode = this.get(index); 173 | if (existedNode) { 174 | existedNode.data = data; 175 | return this; 176 | } 177 | } 178 | 179 | /** 180 | * Reversing the Linked list 181 | * @returns {SinglyLinkedList} LinkedList 182 | */ 183 | reverse() { 184 | let temp = this.head; 185 | this.head = this.tail; 186 | this.tail = temp; 187 | 188 | let previous = null; 189 | let after = null; 190 | while (temp) { 191 | after = temp.next; 192 | temp.next = previous; 193 | previous = temp; 194 | temp = after; 195 | } 196 | return this; 197 | } 198 | 199 | /** 200 | * Traversing or Printing the Linked list 201 | */ 202 | traverse() { 203 | let current = this.head; 204 | while (current) { 205 | console.log(current.data); 206 | current = current.next; 207 | } 208 | } 209 | 210 | /** 211 | * @returns {[]} Linkedlist data as elements in Array 212 | */ 213 | listAsArray() { 214 | let arr = []; 215 | let current = this.head; 216 | while (current) { 217 | arr.push(current.data); 218 | current = current.next; 219 | } 220 | return arr; 221 | } 222 | 223 | /** 224 | * Utility Function (PRIVATE FUNCTION) 225 | * if the length is zero then assign null to both head and tail 226 | */ 227 | emptyListCheck() { 228 | if (this.length === 0) { 229 | this.head = null; 230 | this.tail = null; 231 | } 232 | } 233 | } 234 | -------------------------------------------------------------------------------- /algorithms/dynamic-programming/singlyLinkedList.js: -------------------------------------------------------------------------------- 1 | // Implementation of single link list 2 | // Author: Sheary Tan 3 | 4 | class Node { 5 | constructor(val) { 6 | this.val = val; 7 | this.next = null; 8 | } 9 | } 10 | 11 | class SinglyList { 12 | constructor() { 13 | // Initializing... 14 | // There is nothing at the beginning so 15 | // the head & the tail should be empty, 16 | // and the length should be zero too 17 | this.head = null; 18 | this.tail = null; 19 | this.length = 0; 20 | } 21 | 22 | // 1st method: push (push the val into the end of the list) 23 | push(val) { 24 | // Firstly, we have to accept a new value 25 | var newNode = new Node(val); 26 | // If there is no head, means there is nothing on the list, 27 | // set the head & tail pointers to this value. 28 | if(!this.head) { 29 | this.head = newNode; 30 | this.tail = newNode; 31 | } else { 32 | // If there is value existed, assign the newNode to the next value 33 | // of the current existing value 34 | this.tail.next = newNode; 35 | // Update the tail to it! 36 | this.tail = newNode; 37 | } 38 | // Increment the length and return the newly created link-list 39 | this.length++; 40 | return this; 41 | } 42 | 43 | // 2nd method: pop (remove the last item) 44 | pop() { 45 | // If there is nothing on the list, return undefined 46 | if (!this.head) return undefined; 47 | // Loop through to find the last item 48 | var current = this.head; 49 | var newTail = current; 50 | while(current.next) { 51 | newTail = current; 52 | current = current.next 53 | } 54 | // Set the found tail to tail 55 | this.tail = newTail; 56 | // The next one will be null since we 57 | // would like to remove it 58 | this.tail.next = null; 59 | // Decrease the length 60 | this.length--; 61 | // If there is nothing left after removing 62 | // set the head and tail to be null 63 | if(this.length === 0) { 64 | this.head = null; 65 | this.tail = null; 66 | } 67 | return current; 68 | } 69 | 70 | // 3rd method: shift (remove the first item) 71 | shift() { 72 | // If there is no nothing on the list, return undefined 73 | if(!this.head) return undefined; 74 | // Store the current head in a new variable 75 | var currentHead = this.head; 76 | // Shift the head to the next value of the currentHead 77 | this.head = currentHead.next; 78 | // Decrement the length since we have removed the head 79 | this.length--; 80 | if(this.length === 0) { 81 | this.head = null; 82 | this.tail = null; 83 | } 84 | return currentHead; 85 | } 86 | 87 | // 4th method: unshift (add item to the beginning ) 88 | unshift(val) { 89 | // Initialize the value to a new node; 90 | var newNode = new Node(val); 91 | // If there is nothing on the list, set the head and tail 92 | // point to that new node 93 | if(!this.head) { 94 | this.head = newNode; 95 | this.tail = newNode; 96 | } else { 97 | // In order to set the head value points to the head, 98 | // we have to set the current head to the next item of newNode 99 | newNode.next = this.head; 100 | // and now we can assign the head to newNode! 101 | this.head = newNode 102 | } 103 | // Increment the length after adding the new head 104 | this.length++; 105 | return this; 106 | } 107 | 108 | // 5th method: get 109 | get(i) { 110 | // get accepts an index in and find the specific value 111 | // If i is less than zero, or greater and equal to the length 112 | // of the current link list, return null; 113 | if(i < 0 || i >= this.length) return null; 114 | // Use the counter to find the value 115 | var counter = 0; 116 | var current = this.head; 117 | while(counter !== i) { 118 | current = current.next; 119 | counter++ 120 | } 121 | // Found it and return 122 | return current 123 | } 124 | 125 | // 6th method: set 126 | // Use the given index to find the target value and change it with the new 127 | // given value 128 | set(i, val) { 129 | var targetNode = this.get(i); 130 | if(targetNode) { 131 | targetNode.val = val; 132 | return true; 133 | } 134 | return false; 135 | } 136 | 137 | // 8th method: remove (from any index) 138 | remove(i) { 139 | // Check if there's anything on the list 140 | if(i < 0 || i >= this.length) return undefined; 141 | if(i === 0) return this.shift(); 142 | if(i === this.length - 1) return this.pop(); 143 | // Get the previous item of the target 144 | var previousTarget = this.get(i - 1); 145 | // Since we've got the previous item of the target, 146 | // we now can remove the target by setting the next item of previousTarget 147 | // to the next item of "removed" 148 | var removed = previousTarget.next; 149 | previousTarget.next = removed.next 150 | // Decrease the length 151 | this.length--; 152 | return removed; 153 | } 154 | 155 | // 9th method: reverse 156 | reverse() { 157 | // Firstly we have to set the head to the tail, 158 | // and the tail to the head 159 | var target = this.head; 160 | this.head = this.tail; 161 | this.tail = target; 162 | // Now we have to re-arrange those next & previous 163 | // items of the list 164 | var next; 165 | var prev = null; 166 | // Loop through every single item on the list 167 | for(let i = 0; i < this.length; i++) { 168 | // This part is a bit confusing, let's take an example 169 | // Example = [1, 2, 3, 4, 5], T = target, P = previous, N = next 170 | next = target.next; 171 | // Firstly, the target is 1 172 | // [1, 2, 3, 4, 5] 173 | // T 174 | // And target.next is 2 175 | // [1, 2, 3, 4, 5] 176 | // T N 177 | target.next = prev; 178 | // Remember our target is 1 & prev is null? Now it said the next item of 179 | // 1 is null, 180 | // 1 -> null 181 | prev = target; 182 | // Now we're setting the "prev = null" to the target value 183 | // which now equals to "prev = 1" 184 | // [1, 2, 3, 4, 5] 185 | // P N 186 | target = next; 187 | // And lastly we set the "next" value to be T 188 | // [1, 2, 3, 4, 5] 189 | // P T 190 | 191 | 192 | // So the cycle repeats again, now let's go through 1 more cycle 193 | // [1, 2, 3, 4, 5] 194 | // P T 195 | // next = target.next 196 | // [1, 2, 3, 4, 5] 197 | // P T N 198 | // target.next = prev 199 | // Remember we have the list (1 -> null)? 200 | // now target.next = prev means the next item of 2 is 1 201 | // 2 -> 1 -> null 202 | // prev = target 203 | // Now 2 is prev 204 | // [1, 2, 3, 4, 5] 205 | // P N 206 | // target = next 207 | // And 3 is now the target 208 | // [1, 2, 3, 4, 5] 209 | // P T 210 | // And the cycle repeats again until the target reach the end of the list... 211 | } 212 | return this; 213 | } 214 | 215 | // 10th method: insert 216 | insert(i, val) { 217 | // Check the requirements 218 | if(i < 0 || i >= this.length) return false; 219 | if(i === this.length) return !!this.push(val); 220 | if(i === 0) return !!this.unshift(val); 221 | 222 | // Initialize a new node 223 | var newNode = new Node(val); 224 | // Get the previous node of newNode 225 | var prevNode = this.get(i - 1); 226 | // Remember we haven't insert the newNode into the list! 227 | // And also store the next item of prevNode in a temporary variable 228 | // because we are going to set it to the next item of newNode later 229 | var temp = prevNode.next; 230 | // Now we can set the next item of prevNode to newNode 231 | prevNode.next = newNode; 232 | // Then the next item of newNode will be the temporary item we store 233 | newNode.next = temp; 234 | // Increment the length 235 | this.length++; 236 | return true; 237 | } 238 | 239 | } 240 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | We are accepting all pull requests. [Read More](https://github.com/AllAlgorithms/algorithms/issues/40) 2 | 3 |
4 |
5 |
6 |
7 |
8 | Algorithms Logo 9 |
10 |
11 |
12 |
13 |
14 |
15 | 16 |

17 | What is an algorithm?    18 | Contributing    19 | Stickers & T-Shirts 20 |

21 | 22 | 23 |

24 | 25 | Twitter 26 |     27 | 28 | Instagram 29 |     30 | 31 | Github 32 |     33 |

34 | 35 |
36 |

37 | Huge collection of All ▲lgorithms implemented in multiple languages 38 |

39 |
40 | 41 | 42 | 43 | 44 | 45 | 46 |
47 | 48 | ## See 49 | 50 | - [What is an algorithm](#what-is-an-algorithm) 51 | - [Contributing](https://github.com/AllAlgorithms/algorithms/blob/master/.github/contributing.md) 52 | - [Code of Conduct](https://github.com/AllAlgorithms/algorithms/blob/master/.github/code-of-conduct.md) 53 | - [Stickers and T-Shirts](https://www.redbubble.com/people/abranhe/works/34285088) 54 | - [Twitter](https://twitter.com/AllAlgorithms) 55 | - [Instagram](https://instagram.com/AllAlgorithms) 56 | - [Algorithms Categories](#categories) 57 | - [Maintainers](#maintainers) 58 | - [License](#license) 59 | 60 | 61 | ## What is an algorithm? 62 | 63 | Informally, an algorithm is any well-defined computational procedure that takes 64 | some value, or set of values, as input and produces some value, or set of values, as 65 | output. An algorithm is thus a sequence of computational steps that transform the 66 | input into the output. 67 | 68 | An algorithm should have three important characteristics to be considered valid: 69 | 70 | - **It should be finite**: If your algorithm never ends trying to solve the problem 71 | it was designed to solve then it is useless 72 | - **It should have well defined instructions**: Each step of the algorithm has to 73 | be precisely defined; the instructions should be unambiguously specified for each case. 74 | - **It should be effective**: The algorithm should solve the problem it was designed 75 | to solve. And it should be possible to demonstrate that the algorithm converges with 76 | just a paper and pencil. 77 | 78 | ## Categories 79 | 80 | > Structure of The All ▲lgoritms project 81 | 82 | - [Artificial Intelligence](#artificial-intelligence) 83 | - [Backtracking](#backtracking) 84 | - [Bit Manipulation](#bit-manipulation) 85 | - [Cellular Automaton](#cellular-automaton) 86 | - [Ciphers](#ciphers) 87 | - [Computational Geometry](#computational-geometry) 88 | - [Cryptography](#cryptography) 89 | - [Data Structures](#data-structures) 90 | - [Divide and conquer](#divide-and-conquer) 91 | - [Dynamic Programming](#dynamic-programming) 92 | - [Gaming Theory](#gaming-theory) 93 | - [Graphs](#graphs) 94 | - [Greedy Algorithms](#greedy-algorithms) 95 | - [Math](#math) 96 | - [Networking](#networking) 97 | - [Numerical Analysis](#numerical-analysis) 98 | - [Operating system](#operating-system) 99 | - [Randomized Algorithms](#randomized-algorithms) 100 | - [Searches](#searches) 101 | - [Selections Algorithms](#selections-algorithms) 102 | - [Sorting](#sorting) 103 | - [Strings](#strings) 104 | - [Online Challenges](#online-challenges) 105 | - [Others](#others) 106 | 107 | ## [Artificial Intelligence](artificial-intelligence) 108 | 109 | - [Density-based spatial clustering of applications with noise (DBSCAN Clustering)](https://allalgorithms.com/docs/dbscan) 110 | - [Interactive Self-Organizing Data Analysis Technique yAy! (ISODATA Clustering)](https://allalgorithms.com/docs/isodata) 111 | - [Linear Regression](https://allalgorithms.com/docs/linear-regression) 112 | - [Logistic Regression](https://allalgorithms.com/docs/logistic-regression) 113 | - [Neutral Style Transfer](https://allalgorithms.com/docs/neutral-style-transfer) 114 | - [SATisfiable (SAT)](https://allalgorithms.com/docs/sat) 115 | - [Travelling salesman problem (TSP)](https://allalgorithms.com/docs/tsp) 116 | - [A* (A Star)](https://allalgorithms.com/docs/a-star) 117 | - [Artificial Neutral Network](https://allalgorithms.com/docs/artificial-neutral-network) 118 | - [Convolutional Neutral Network](https://allalgorithms.com/docs/convolutional-neutral-network) 119 | - [Decision Tree](https://allalgorithms.com/docs/decision-tree) 120 | - [Factorization Machines](https://allalgorithms.com/docs/factorization-machines) 121 | - [Gaussian Mixture Model](https://allalgorithms.com/docs/gaussian-mixtrue-model) 122 | - [Gradient Boosting Trees](https://allalgorithms.com/docs/gradient-boostring-trees) 123 | - [Hierachical Clustering](https://allalgorithms.com/docs/hierachical-clustering) 124 | - [Image Processing](https://allalgorithms.com/docs/image-processing) 125 | - [K Nearest Neighbors](https://allalgorithms.com/docs/k-nearest-neighbors) 126 | - [K Means](https://allalgorithms.com/docs/k-means) 127 | - [Minimax](https://allalgorithms.com/docs/minimax) 128 | - [Native Bayes](https://allalgorithms.com/docs/native-bayes) 129 | - [Nearest Sequence Memory](https://allalgorithms.com/docs/nearest-sequence-memory) 130 | - [Neutral Network](https://allalgorithms.com/docs/neutral-network) 131 | - [Perceptron](https://allalgorithms.com/docs/perceptron) 132 | - [Principal Component Analysis](https://allalgorithms.com/docs/principal-component-analysis) 133 | - [Q Learing](https://allalgorithms.com/docs/q-learning) 134 | - [Random Forests](https://allalgorithms.com/docs/random-forest) 135 | - [Restricted Boltzman Machine](https://allalgorithms.com/docs/restricted-boltzman-machine) 136 | 137 | ## [Backtracking](backtracking) 138 | 139 | - [Algorithm X](backtracking/algorithm-x) 140 | - [Crossword Puzzle](backtracking/crossword-Puzzle) 141 | - [Knight Tour](backtracking/knight-tour) 142 | - [M Coloring Problem](backtracking/m-coloring-problem) 143 | - [N Queen](backtracking/n-queen) 144 | - [Number of ways in Maze](backtracking/number-of-ways-in-maze) 145 | - [Partitions of set](backtracking/partitions-of-set) 146 | - [Permutation of Strings](backtracking/permutation-of-strings) 147 | - [Powerset](backtracking/powerset) 148 | - [Rat in maze](backtracking/rat-in-maze) 149 | - [Subset Sum](backtracking/subset-sum) 150 | - [Sudoku Solve](backtracking/sudoku-solve) 151 | 152 | ## [Bit Manipulation](bit-manipulation) 153 | 154 | - [Addition using bits](bit-manipulation/adding-using-bits) 155 | - [Bit divisor](bit-manipulation/bit-divisor) 156 | - [Byte swapper](bit-manipulation/byte-swapper) 157 | - [Convert numbers to binary](bit-manipulation/convert-numbers-to-binary) 158 | - [Count set bits](bit-manipulation/count-set-bits) 159 | - [Flip bits](bit-manipulation/flip-bits) 160 | - [Hamming distance](bit-manipulation/hamming-distace) 161 | - [Invert bit](bit-manipulation/invert-bit) 162 | - [Lonely integer](bit-manipulation/lonely-integer) 163 | - [Magic Number](bit-manipulation/magic-number) 164 | - [Maximum XOR Value](bit-manipulation/maximun-xor-value) 165 | - [Power of 2](bit-manipulation/power-of-2) 166 | - [Subset Generation](bit-manipulation/subset-generation) 167 | - [Sum binary numbers](bit-manipulation/sum-binary-numbers) 168 | - [Sum equals XOR](bit-manipulation/sum-equals-xor) 169 | - [Thrice unique number](bit-manipulation/thrice-unique-number) 170 | - [Twice unique number](bit-manipulation/twice-unique-number) 171 | - [XOR Swap](bit-manipulation/xor-swap) 172 | 173 | ## [Cellular Automaton](cellular-automaton) 174 | 175 | - [Brians Brain](cellular-automaton/brians-brain) 176 | - [Conways Game of life](cellular-automaton/conways-game-of-life) 177 | - [Elementary Cellular Automata](cellular-automaton/elementary-cellular-automata) 178 | - [Generic Algorithm](cellular-automaton/generic-algorithm) 179 | - [Langtons Ant](cellular-automaton/langtons-ant) 180 | - [Nobili Cellular Automata](cellular-automaton/nobili-cellular-automata) 181 | - [Von Neoumann Cellular Automata](cellular-automaton/von-neoumann-cellular-automata) 182 | 183 | ## [Computational Geometry](computational-geometry) 184 | 185 | - [2D Line intersection](computational-geometry/) 186 | - [2D Separating Axis test](computational-geometry/) 187 | - [Area of polygon](computational-geometry/) 188 | - [Area of triangle](computational-geometry/) 189 | - [Axis aligned bounding box collision](computational-geometry/) 190 | - [Bresenham Line](computational-geometry/) 191 | - [Chans Algorithm](computational-geometry/) 192 | - [Cohen Sutherland Lineclip](computational-geometry/) 193 | - [Distance between points](computational-geometry/) 194 | - [Graham Scan](computational-geometry/) 195 | - [Halfplane intersection](computational-geometry/) 196 | - [Jarvis March](computational-geometry/) 197 | - [Quickull](computational-geometry/) 198 | - [Sphere tetrahedron intersection](computational-geometry/) 199 | - [Sutherland Hodgeman clipping](computational-geometry/) 200 | 201 | ## [Cryptography](cryptography) 202 | 203 | - [Affine Cipher](cryptography/) 204 | - [Atbash Cipher](cryptography/) 205 | - [Autokey Cipher](cryptography/) 206 | - [Baconian Cipher](cryptography/) 207 | - [Caesar Cipher](cryptography/) 208 | - [Colummnar Cipher](cryptography/) 209 | - [Vigenere Cipher](cryptography/) 210 | 211 | ## [Data Structures](data-structures) 212 | 213 | - [Bag](data-structures/bag/) 214 | - [Hashes](data-structures/hashes/) 215 | - [Linked List](data-structures/linked-list/) 216 | - [List](data-structures/list/) 217 | - [Queue](data-structures/queue/) 218 | - [Stack](data-structures/stack/) 219 | - [Tree](data-structures/tree/) 220 | 221 | ## [Divide and conquer](divide-and-conquer) 222 | 223 | - [Strassen Matrix Manipulation](divide-and-conquer/) 224 | - [Closest Pair of Point](divide-and-conquer/) 225 | - [Inversion Count](divide-and-conquer/) 226 | - [Karatsuba Multiplication](divide-and-conquer/) 227 | - [Maximum Contiguous subsequence sum](divide-and-conquer/) 228 | - [Merge Sort using divide and conquer](divide-and-conquer/) 229 | - [Quick Sort using divide and conquer](divide-and-conquer/) 230 | - [Tournament Method to find min max](divide-and-conquer/) 231 | - [Warnock Algorithm](divide-and-conquer/) 232 | - [X Power Y](divide-and-conquer/) 233 | 234 | ## [Dynamic Programming](dynamic-programming) 235 | 236 | - [Array Median](dynamic-programming) 237 | - [Optima Binary Search Tree](dynamic-programming) 238 | - [Binomial Coefficient](dynamic-programming) 239 | 240 | ## [Gaming Theory](gaming-theory) 241 | 242 | - [Nim Next Best Move Game](gaming-theory/) 243 | - [Nim Win Loss Game](gaming-theory/) 244 | - [Grundy Numbers Kayle Game](gaming-theory/) 245 | 246 | ## [Graphs](graphs) 247 | 248 | - [Bipartite Check](graphs/) 249 | - [Adjacency Lists graphs representation](graphs/) 250 | - [A* (A Star)](https://allalgorithms.com/docs/a-star) 251 | 252 | ## [Greedy Algorithms](greedy-algorithms) 253 | 254 | - [Activity Selection](greedy-algorithms) 255 | - [Dijkstra Shortest Path](greedy-algorithms) 256 | - [Egyptian Fraction](greedy-algorithms) 257 | 258 | ## [Math](math) 259 | 260 | - [2 Sum](math/) 261 | - [Add Polynomials](math/) 262 | - [Amicable Numbers](math/) 263 | - [Armstrong Numbers](math/) 264 | - [Automorphic Numbers](math/) 265 | - [Average Stream Numbers](math/) 266 | - [Babylonian Method](math/) 267 | - [Binomial Coefficient](math/) 268 | - [Catalan Number](math/) 269 | - [Check is Square](math/) 270 | - [Convolution](math/) 271 | - [Coprime Numbers](math/) 272 | - [Count Digits](math/) 273 | - [Count Trailing Zeroes](math/) 274 | - [Decoding of String](math/) 275 | - [Delannoy Number](math/) 276 | - [Derangements](math/) 277 | - [DFA Division](math/) 278 | - [Diophantine](math/) 279 | - [Divided Differences](math/) 280 | - [Euler Totient](math/) 281 | - [Exponentiation Power](math/) 282 | - [Factorial](math/factorial) 283 | - [Fast Fourier transform](math/) 284 | - [Fast inverse (sqrt) Square Root](math/) 285 | 286 | ## [Networking](networking) 287 | 288 | - [Packet Sniffer](networking/) 289 | - [Determine Endianess](networking/) 290 | - [Validate IP](networking/) 291 | 292 | ## [Numerical Analysis](numerical-analysis) 293 | 294 | - [Integral](numerical-analysis/integral) 295 | - [Monte Carlo](numerical-analysis/monte-carlo) 296 | - [Runge Kutt](numerical-analysis/runge-kutt) 297 | 298 | ## [Operating system](operating-system) 299 | 300 | - [Currency](operating-system/) 301 | - [Deadlocks](operating-system/) 302 | - [Memory Management](operating-system/) 303 | - [Scheduling](operating-system/) 304 | - [Shell](operating-system/) 305 | 306 | ## [Randomized Algorithms](randomized-algorithms) 307 | 308 | - [Birthday Paradox](randomized-algorithms) 309 | - [Karger Minimum Cut Algorithm](randomized-algorithms) 310 | - [Kth Smallest Element Algorithm](randomized-algorithms) 311 | - [Random from Stream](randomized-algorithms) 312 | - [Random Node Linked list](randomized-algorithms) 313 | - [Randomized Quicksort](randomized-algorithms) 314 | - [Reservoir Sampling](randomized-algorithms) 315 | - [Shuffle an Array](randomized-algorithms) 316 | 317 | ## [Searches](searches) 318 | 319 | - [Binary Search](searches) 320 | - [Exponential Search](searches) 321 | - [Fibonacci Search](searches) 322 | - [Fuzzy Search](searches) 323 | - [Interpolation Search](searches) 324 | - [Jump Search](searches) 325 | - [Linear Search](searches) 326 | - [Ternay Search](searches) 327 | 328 | ## [Selections Algorithms](selections-algorithms) 329 | 330 | - [Median of Medians](selections-algorithms) 331 | - [Quick Select](selections-algorithms) 332 | 333 | ## [Sorting](sorting) 334 | 335 | - [Bead Sort](sorting/) 336 | - [Bogo Sort](sorting/) 337 | - [Bubble Sort](sorting/) 338 | - [Bucket Sort](sorting/) 339 | - [Circle Sort](sorting/) 340 | - [Comb Sort](sorting/) 341 | - [Counting Sort](sorting/) 342 | - [Cycle Sort](sorting/) 343 | - [Flash Sort](sorting/) 344 | - [Gnome Sort](sorting/) 345 | - [Heap Sort](sorting/) 346 | - [Insertion Sort](sorting/) 347 | - [Intro Sort](sorting/) 348 | - [Median Sort](sorting/) 349 | - [Merge Sort](sorting/) 350 | - [Pipeonhole Sort](sorting/) 351 | - [Quick Sort](sorting/) 352 | - [Radix Sort](sorting/) 353 | - [Selection Sort](sorting/) 354 | - [Shaker Sort](sorting/) 355 | - [Shell Sort](sorting/) 356 | - [Sleep Sort](sorting/) 357 | - [Stooge Sort](sorting/) 358 | - [Topological Sort](sorting/) 359 | - [Tree Sort](sorting/) 360 | 361 | ## [Strings](strings) 362 | 363 | - [Aho Corasick Algorithm](strings) 364 | - [Anagram Search](strings) 365 | - [Arithmetic on large numbers](strings) 366 | - [Boyer Moore Algorithm](strings) 367 | - [Finite Automata](strings) 368 | - [Kasai Algorithm](strings) 369 | - [Kmp Algorithm](strings) 370 | - [Levenshteing Distance](strings) 371 | - [Lipogram Checker](strings) 372 | 373 | ## [Online Challenges](online-challenges) 374 | 375 | - [Coderbyte](online-challenges/coderbyte) 376 | - [Code Chef](online-challenges/code-chef) 377 | - [Code Eval](online-challenges/code-eval) 378 | - [Hackerearth](online-challenges/hackerearth) 379 | - [Hackerrank](online-challenges/hackerrank) 380 | - [LeetCode](online-challenges/leetcode) 381 | - [Project Euler](online-challenges/project-euler) 382 | - [Rosalind](online-challenges/rosalind) 383 | - [SPOJ](online-challenges/spoj) 384 | - [Top Coder](online-challenges/top-coder)` 385 | 386 | ## [Others](others) 387 | 388 | - [Average](others/) 389 | - [Biggest of n numbers](others/) 390 | - [Biggest Suffix](others/) 391 | - [Fifteen Puzzle](others/) 392 | - [Jaccard Similarity](others/) 393 | - [Jose Phus Problem](others/) 394 | - [Lapindrom Checker](others/) 395 | - [Leap Year](others/) 396 | - [Magic Square](others/) 397 | - [Majority Element](others/) 398 | - [Minimum subarray size with degree](others/) 399 | - [No operator addition](others/) 400 | - [Paint fill](others/) 401 | - [Split list](others/) 402 | - [Tokenizer](others/) 403 | - [Unique number](others/) 404 | 405 | ## License 406 | 407 | This work is released under MIT License. 408 | 409 | To the extent possible under law, [Abraham Hernandez (@abranhe)](https://go.abranhe.com/github) has waived all copyright and related or neighboring rights to this work. 410 | 411 |
412 | 413 | 414 | 415 |
416 |
--------------------------------------------------------------------------------