diff --git a/.github/code-of-conduct.md b/.github/code-of-conduct.md new file mode 100644 index 0000000..f809c8b --- /dev/null +++ b/.github/code-of-conduct.md @@ -0,0 +1,40 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +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. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a professional setting + +## Our Responsibilities + +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. + +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. + +## Scope + +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. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ diff --git a/.github/contributing.md b/.github/contributing.md new file mode 100644 index 0000000..01f6600 --- /dev/null +++ b/.github/contributing.md @@ -0,0 +1,3 @@ +## Contributing + +> 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. \ No newline at end of file diff --git a/.github/issue-template.md b/.github/issue-template.md new file mode 100644 index 0000000..99764fe --- /dev/null +++ b/.github/issue-template.md @@ -0,0 +1 @@ +I am creating an issue because... diff --git a/.github/pull-request-template.md b/.github/pull-request-template.md new file mode 100644 index 0000000..3bc0935 --- /dev/null +++ b/.github/pull-request-template.md @@ -0,0 +1,6 @@ +I am creating a pull request for... + +- [ ] New algorithm +- [ ] Update to an algorithm +- [ ] Fix an error +- [ ] Other - *Describe below* \ No newline at end of file diff --git a/ciphers/rot13.js b/algorithms/ciphers/rot13.js similarity index 100% rename from ciphers/rot13.js rename to algorithms/ciphers/rot13.js diff --git a/algorithms/ciphers/vigenere.js b/algorithms/ciphers/vigenere.js new file mode 100644 index 0000000..1cfe027 --- /dev/null +++ b/algorithms/ciphers/vigenere.js @@ -0,0 +1,21 @@ +function vigenere(plaintext, key) { + const upperKey = key.toUpperCase(); + let decryptedMessage = ''; + for (let i = 0, keyIndex = 0; i < plaintext.length; keyIndex += 1, i += 1) { + const char = plaintext.charCodeAt(i); + const keyCode = upperKey.charCodeAt(keyIndex % upperKey.length); + if (char >= 97 && char <= 122) { + const index = ((char - 97 + keyCode - 65) % 26); + decryptedMessage += String.fromCharCode(index + 97); + } else if (char >= 65 && char <= 90) { + const index = ((char - 65 + keyCode - 65) % 26); + decryptedMessage += String.fromCharCode(index + 65); + } else { + keyIndex -= 1; + decryptedMessage += String.fromCharCode(char); + } + } + return decryptedMessage; +} + +console.log(vigenere('The quick brown fox jumps over the lazy dog.', 'key')); // Dlc aygmo zbsux jmh nswtq yzcb xfo pyjc byk. diff --git a/algorithms/classes/Tree.js b/algorithms/classes/Tree.js new file mode 100644 index 0000000..931518f --- /dev/null +++ b/algorithms/classes/Tree.js @@ -0,0 +1,58 @@ +// JavaScript implementation of Binary Search + +// Author: Youcef Madadi + +// Binary Tree +class BinaryTree{ + left=null; + right=null; + value; + + constructor(value,left,right) { + this.value = value; + if(left instanceof BinaryTree)this.left = left; + if(right instanceof BinaryTree)this.right= right; + } + AddValue(value){ + if(value>this.value){ + if(this.right) return this.right.AddValue(value); + this.right=new BinaryTree(value) + }else if(value value ) { + if(this.left)return this.left.findValue(value); + } + else if( this.value < value ) { + if(this.right) return this.right.findValue(value); + } + else return true + return false; + } + static CreateRandomTree(){ + let root=new BinaryTree(Math.floor(Math.random() * 100)), + deep= Math.floor(Math.random() * 50); + for( let i=0 ; i current.value) { + current = current.right; + } else { + found = true; + } + } + if (!found) return undefined; + return current; + } + + contains(value) { + if (this.root === null) return false; + var current = this.root, + found = false; + while (current && !found) { + if (value < current.value) current = current.left; + else if (value > current.value) current = current.right; + else return true; + } + return false; + } + + BreadthFirstSearch() { + let node = this.root, + data = [], + queue = []; + queue.push(node); + + while (queue.length) { + node = queue.shift(); + data.push(node.value); + if (node.left) queue.push(node.left); + if (node.right) queue.push(node.right); + } + + return data; + } + + DepthFirstSearchPreOrder() { + let data = []; + function traverse(node) { + data.push(node.value); + if (node.left) traverse(node.left); + if (node.right) traverse(node.right); + } + traverse(this.root); + return data; + } + DepthFirstSearchPostOrder() { + let data = []; + function traverse(node) { + if (node.left) traverse(node.left); + if (node.right) traverse(node.right); + data.push(node.value); + } + traverse(this.root); + return data; + } + DepthFirstSearchInOrder() { + let data = []; + function traverse(node) { + if (node.left) traverse(node.left); + data.push(node.value); + if (node.right) traverse(node.right); + } + traverse(this.root); + return data; + } +} + +// 10 +// 5 13 +// 2 7 11 16 + +var tree = new BinarySearchTree(); +tree.insert(10); +tree.insert(5); +tree.insert(13); +tree.insert(11); +tree.insert(2); +tree.insert(16); +tree.insert(7); + +console.log("node with value 13:", tree.find(13)); +console.log("node with value 19:", tree.find(19)); + +console.log("tree coontais node with value 2:", tree.contains(2)); +console.log("tree coontais node with value 534:", tree.contains(534)); + +console.log("BreadthFirstSearch:", tree.BreadthFirstSearch()); +console.log("DepthFirstSearchPreOrder:", tree.DepthFirstSearchPreOrder()); +console.log("DepthFirstSearchPostOrder:", tree.DepthFirstSearchPostOrder()); +console.log("DepthFirstSearchInOrder:", tree.DepthFirstSearchInOrder()); diff --git a/data-structures/doublyLinkedList.js b/algorithms/data-structures/doublyLinkedList.js similarity index 100% rename from data-structures/doublyLinkedList.js rename to algorithms/data-structures/doublyLinkedList.js diff --git a/data-structures/hashTable.js b/algorithms/data-structures/hashTable.js similarity index 100% rename from data-structures/hashTable.js rename to algorithms/data-structures/hashTable.js diff --git a/algorithms/data-structures/maxHeap.js b/algorithms/data-structures/maxHeap.js new file mode 100644 index 0000000..5d3f91d --- /dev/null +++ b/algorithms/data-structures/maxHeap.js @@ -0,0 +1,77 @@ +class BinaryHeap { + constructor() { + this.heap = []; + } + + insert(value) { + this.heap.push(value); + this.heapify(); + } + + size() { + return this.heap.length; + } + + empty() { + return this.size() === 0; + } + + heapify() { + let index = this.size() - 1; + + while (index > 0) { + const element = this.heap[index]; + const parentIndex = Math.floor((index - 1) / 2); + const parent = this.heap[parentIndex]; + + if (parent[0] >= element[0]) break; + this.heap[index] = parent; + this.heap[parentIndex] = element; + index = parentIndex; + } + } + + extractMax() { + const max = this.heap[0]; + const tmp = this.heap.pop(); + if (!this.empty()) { + this.heap[0] = tmp; + this.sinkDown(0); + } + return max; + } + + sinkDown(index) { + const left = 2 * index + 1; + const right = 2 * index + 2; + let largest = index; + const length = this.size(); + + if (left < length && this.heap[left][0] > this.heap[largest][0]) { + largest = left; + } + if (right < length && this.heap[right][0] > this.heap[largest][0]) { + largest = right; + } + // swap + if (largest !== index) { + const tmp = this.heap[largest]; + this.heap[largest] = this.heap[index]; + this.heap[index] = tmp; + this.sinkDown(largest); + } + } +} + +const maxHeap = new BinaryHeap(); +maxHeap.insert([4]); +maxHeap.insert([3]); +maxHeap.insert([6]); +maxHeap.insert([1]); +maxHeap.insert([8]); +maxHeap.insert([2]); + +while (!maxHeap.empty()) { + const mx = maxHeap.extractMax(); + console.log(mx); +} diff --git a/data-structures/priorityQueue.js b/algorithms/data-structures/priorityQueue.js similarity index 100% rename from data-structures/priorityQueue.js rename to algorithms/data-structures/priorityQueue.js diff --git a/data-structures/queue.js b/algorithms/data-structures/queue.js similarity index 100% rename from data-structures/queue.js rename to algorithms/data-structures/queue.js diff --git a/data-structures/singlyLinkedList.js b/algorithms/data-structures/singlyLinkedList.js similarity index 100% rename from data-structures/singlyLinkedList.js rename to algorithms/data-structures/singlyLinkedList.js diff --git a/data-structures/stack.js b/algorithms/data-structures/stack.js similarity index 58% rename from data-structures/stack.js rename to algorithms/data-structures/stack.js index d74fe16..62a772b 100644 --- a/data-structures/stack.js +++ b/algorithms/data-structures/stack.js @@ -1,11 +1,15 @@ /** - * @author Rashik Ansar - * - * Implemtaion of Stack data structure - * Stack follows LIFO (Last In First Out) priniciple - * For Insertion and Deletion its complexity is O(1) - * For Accessing and Searching its complexity is O(n) - */ +* @author Rashik Ansar and Luiz Guerra +* +* Implemtaion of Stack data structure +* Stack follows LIFO (Last In First Out) priniciple +* For Insertion and Deletion its complexity is O(1) +* For Accessing and Searching its complexity is O(n) +* +* @author Jan Tabacki +* Fix in toString method, display all elements and get data property instead of element +* which does no exist. +*/ class Stack { /** @@ -62,6 +66,43 @@ class Stack { } return this.first.data; } + + /** + * @returns size of the Stack + */ + size() { + return this.size; + } + + /** + * @returns if Stack is empty + */ + isEmpty() { + return this.size == 0; + } + + /** + * clears the Stack + */ + clear() { + this.first = null; + this.last = null; + this.size = 0; + } + + /** + * @returns the Stack + */ + toString() { + let str = ""; + let aux = this.first; + while (aux) { + str += aux.data + " "; + aux = aux.next; + } + return str; + } + } class Node { @@ -69,4 +110,4 @@ class Node { this.data = data; this.next = null; } -} +} \ No newline at end of file diff --git a/algorithms/dynamic-programming/cookies_function.js b/algorithms/dynamic-programming/cookies_function.js new file mode 100644 index 0000000..f522ec1 --- /dev/null +++ b/algorithms/dynamic-programming/cookies_function.js @@ -0,0 +1,48 @@ +// Useful Functions to create , read and delete the cookies. + +(function ($) { + 'use strict'; + + function createCookie(name, value, days) { + var expires; + + if (days) { + var date = new Date(); + date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000); + expires = '; expires=' + date.toGMTString(); + } else { + expires = ''; + } + document.cookie = + encodeURIComponent(name) + + '=' + + encodeURIComponent(value) + + expires + + '; path=/'; + } + + // How to Create Cookies? + createCookie('el_data', 'Prajakta'); + + function readCookie(name) { + var nameEQ = encodeURIComponent(name) + '='; + var ca = document.cookie.split(';'); + for (var i = 0; i < ca.length; i++) { + var c = ca[i]; + while (c.charAt(0) === ' ') c = c.substring(1, c.length); + if (c.indexOf(nameEQ) === 0) + return decodeURIComponent(c.substring(nameEQ.length, c.length)); + } + return null; + } + + // How to read cookies? + var name = readCookie('el_data'); + + function eraseCookie(name) { + createCookie(name, '', -1); + } + + // How to delete cookies? + eraseCookie('el_data'); +})(jQuery); diff --git a/dynamic-programming/linkedList.js b/algorithms/dynamic-programming/linkedList.js similarity index 100% rename from dynamic-programming/linkedList.js rename to algorithms/dynamic-programming/linkedList.js diff --git a/dynamic-programming/singlyLinkedList.js b/algorithms/dynamic-programming/singlyLinkedList.js similarity index 100% rename from dynamic-programming/singlyLinkedList.js rename to algorithms/dynamic-programming/singlyLinkedList.js diff --git a/graphs/bfs.js b/algorithms/graphs/bfs.js similarity index 100% rename from graphs/bfs.js rename to algorithms/graphs/bfs.js diff --git a/graphs/breadth-first-search.js b/algorithms/graphs/breadth-first-search.js similarity index 100% rename from graphs/breadth-first-search.js rename to algorithms/graphs/breadth-first-search.js diff --git a/graphs/dfs.js b/algorithms/graphs/dfs.js similarity index 100% rename from graphs/dfs.js rename to algorithms/graphs/dfs.js diff --git a/graphs/dijkstra.js b/algorithms/graphs/dijkstra.js similarity index 100% rename from graphs/dijkstra.js rename to algorithms/graphs/dijkstra.js diff --git a/graphs/unweightedGraph.js b/algorithms/graphs/unweightedGraph.js similarity index 100% rename from graphs/unweightedGraph.js rename to algorithms/graphs/unweightedGraph.js diff --git a/algorithms/math/2sum.js b/algorithms/math/2sum.js new file mode 100644 index 0000000..d5c0ea3 --- /dev/null +++ b/algorithms/math/2sum.js @@ -0,0 +1,30 @@ +// File name: 2sum.js +// Author: boasmarbun (https://github.com/boasmarbun) +// Date created: 02/10/2020 + +function twoSum (nums, target) { + var diff = 0; + for (var firstIndex = 0; firstIndex <= nums.length; firstIndex++) { + diff = target - nums[firstIndex]; + var secondIndex = nums.indexOf(diff, firstIndex+1); + if(secondIndex != -1) { + return [firstIndex, secondIndex]; + } + } + return [0]; +}; + +// uncomment below for testing +// var testArray1 = [1,2,3,9] +// var target1 = 5 +// var testArray2 = [0,3,4,0] +// var target2 = 0 +// var testArray3 = [-2, -3, -7, -13, -6] +// var target3 = -8 +// var testArray4 = [] +// var target4 = 2 + +// console.log(twoSum(testArray1, target1)) +// console.log(twoSum(testArray2, target2)) +// console.log(twoSum(testArray3, target3)) +// console.log(twoSum(testArray4, target4)) \ No newline at end of file diff --git a/math/checkPrime.js b/algorithms/math/checkPrime.js similarity index 100% rename from math/checkPrime.js rename to algorithms/math/checkPrime.js diff --git a/math/collatz.js b/algorithms/math/collatz.js similarity index 100% rename from math/collatz.js rename to algorithms/math/collatz.js diff --git a/math/computeNCR.js b/algorithms/math/computeNCR.js similarity index 100% rename from math/computeNCR.js rename to algorithms/math/computeNCR.js diff --git a/math/degreeRadianConversion.js b/algorithms/math/degreeRadianConversion.js similarity index 100% rename from math/degreeRadianConversion.js rename to algorithms/math/degreeRadianConversion.js diff --git a/algorithms/math/euclidean.js b/algorithms/math/euclidean.js new file mode 100644 index 0000000..ddeb520 --- /dev/null +++ b/algorithms/math/euclidean.js @@ -0,0 +1,9 @@ +function euclideanAlgorithm(originalA, originalB) { + const a = Math.abs(originalA); + const b = Math.abs(originalB); + + return b === 0 ? a : euclideanAlgorithm(b, a % b); +} + +var gcd = euclideanAlgorithm(1, 3); +console.log(gcd); diff --git a/algorithms/math/euclideanIterative.js b/algorithms/math/euclideanIterative.js new file mode 100644 index 0000000..77fde72 --- /dev/null +++ b/algorithms/math/euclideanIterative.js @@ -0,0 +1,12 @@ +function euclideanAlgorithmIterative(originalA, originalB) { + let a = Math.abs(originalA); + let b = Math.abs(originalB); + while (a && b && a !== b) { + [a, b] = a > b ? [a - b, b] : [a, b - a]; + } + return a || b; +} + +var gcd = euclideanAlgorithmIterative(4, 7); + +console.log(gcd); diff --git a/algorithms/math/evenNumbers.js b/algorithms/math/evenNumbers.js new file mode 100644 index 0000000..ec5bf6d --- /dev/null +++ b/algorithms/math/evenNumbers.js @@ -0,0 +1,7 @@ +// Check For Even Numbers +// Author: Abejide Femi + +function evenNumber(arr) { + return arr.filter(a => a % 2 === 0); +} +console.log([1,2,5,6,8,12]) // returns [2,6,8,12] \ No newline at end of file diff --git a/math/factorial-recursive.js b/algorithms/math/factorial-recursive.js similarity index 100% rename from math/factorial-recursive.js rename to algorithms/math/factorial-recursive.js diff --git a/math/factorial.js b/algorithms/math/factorial.js similarity index 100% rename from math/factorial.js rename to algorithms/math/factorial.js diff --git a/math/fibonacci-recursive.js b/algorithms/math/fibonacci-recursive.js similarity index 100% rename from math/fibonacci-recursive.js rename to algorithms/math/fibonacci-recursive.js diff --git a/math/fibonacci.js b/algorithms/math/fibonacci.js similarity index 100% rename from math/fibonacci.js rename to algorithms/math/fibonacci.js diff --git a/math/fibonnaci.js b/algorithms/math/fibonnaci.js similarity index 100% rename from math/fibonnaci.js rename to algorithms/math/fibonnaci.js diff --git a/math/gcd.js b/algorithms/math/gcd.js similarity index 100% rename from math/gcd.js rename to algorithms/math/gcd.js diff --git a/math/greatestCommonDivisor.js b/algorithms/math/greatestCommonDivisor.js similarity index 100% rename from math/greatestCommonDivisor.js rename to algorithms/math/greatestCommonDivisor.js diff --git a/algorithms/math/isPerfectSquare.js b/algorithms/math/isPerfectSquare.js new file mode 100644 index 0000000..18a4dff --- /dev/null +++ b/algorithms/math/isPerfectSquare.js @@ -0,0 +1,15 @@ +// JavaScript implementation of to check if a number is a perfect square +// +// Author: Ayoola Akindolani + +var isPerfectSquare = function(num) { + if (num >= 0 && Math.sqrt(num) % 1 === 0) { + console.log("Number is a perfect square."); + } else { + console.log("Number is not a perfect square."); + } +}; + +isPerfectSquare(81); +isPerfectSquare(9); +isPerfectSquare(8); diff --git a/math/naturalNumbersSum.js b/algorithms/math/naturalNumbersSum.js similarity index 100% rename from math/naturalNumbersSum.js rename to algorithms/math/naturalNumbersSum.js diff --git a/algorithms/math/pascalsTriangle.js b/algorithms/math/pascalsTriangle.js new file mode 100644 index 0000000..7104eb6 --- /dev/null +++ b/algorithms/math/pascalsTriangle.js @@ -0,0 +1,23 @@ +function pascalTriangleRecursive(lineNumber) { + if (lineNumber === 0) { + return [1]; + } + + const currentLineSize = lineNumber + 1; + const previousLineSize = currentLineSize - 1; + + const currentLine = []; + + const previousLine = pascalTriangleRecursive(lineNumber - 1); + + for (let numIndex = 0; numIndex < currentLineSize; numIndex += 1) { + const leftCoefficient = numIndex - 1 >= 0 ? previousLine[numIndex - 1] : 0; + const rightCoefficient = + numIndex < previousLineSize ? previousLine[numIndex] : 0; + + currentLine[numIndex] = leftCoefficient + rightCoefficient; + } + + return currentLine; +} +console.log(pascalTriangleRecursive(40)); diff --git a/math/quadrant.js b/algorithms/math/quadrant.js similarity index 100% rename from math/quadrant.js rename to algorithms/math/quadrant.js diff --git a/algorithms/math/randomNumber.js b/algorithms/math/randomNumber.js new file mode 100644 index 0000000..4490bfb --- /dev/null +++ b/algorithms/math/randomNumber.js @@ -0,0 +1,11 @@ +const randomNumber = ({ min, max, integer }) => { + + const number = Math.random() * (max - min) + min; + + if (integer) { + return Math.round(number); + } + + return number; + +} diff --git a/math/smallest-common-multiple.js b/algorithms/math/smallest-common-multiple.js similarity index 100% rename from math/smallest-common-multiple.js rename to algorithms/math/smallest-common-multiple.js diff --git a/math/spiralMatrix.js b/algorithms/math/spiralMatrix.js similarity index 100% rename from math/spiralMatrix.js rename to algorithms/math/spiralMatrix.js diff --git a/others/bigonotaion.js b/algorithms/others/bigonotaion.js similarity index 100% rename from others/bigonotaion.js rename to algorithms/others/bigonotaion.js diff --git a/others/checkPrime.js b/algorithms/others/checkPrime.js similarity index 100% rename from others/checkPrime.js rename to algorithms/others/checkPrime.js diff --git a/others/primeFactors.js b/algorithms/others/primeFactors.js similarity index 100% rename from others/primeFactors.js rename to algorithms/others/primeFactors.js diff --git a/searches/binarySearch.js b/algorithms/searches/binarySearch.js similarity index 100% rename from searches/binarySearch.js rename to algorithms/searches/binarySearch.js diff --git a/searches/sequentialSearch.js b/algorithms/searches/sequentialSearch.js similarity index 100% rename from searches/sequentialSearch.js rename to algorithms/searches/sequentialSearch.js diff --git a/searching/binarySearch.js b/algorithms/searching/binarySearch.js similarity index 100% rename from searching/binarySearch.js rename to algorithms/searching/binarySearch.js diff --git a/algorithms/searching/jumpSearch.js b/algorithms/searching/jumpSearch.js new file mode 100644 index 0000000..66c1f9c --- /dev/null +++ b/algorithms/searching/jumpSearch.js @@ -0,0 +1,29 @@ +/** + * + * @param {Array} arr + * @param {Number} x + */ +function jumpSearch(arr, x) { + let len = arr.length; + let step = Math.sqrt(len); + + let prev = 0; + while (arr[parseInt(Math.min(step, len) - 1)] < x) { + prev = step; + step += Math.sqrt(len); + if (prev >= len) return -1; + } + + while (arr[parseInt(prev)] < x) { + prev += 1; + + if (prev === Math.min(step, len)) return -1; + } + if (arr[parseInt(prev)] === x) return prev; + + return -1; +} + +let arr = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]; + +console.log(jumpSearch(arr, 610)); diff --git a/searching/linearSearch.js b/algorithms/searching/linearSearch.js similarity index 100% rename from searching/linearSearch.js rename to algorithms/searching/linearSearch.js diff --git a/searching/naivePatternSearching.js b/algorithms/searching/naivePatternSearching.js similarity index 100% rename from searching/naivePatternSearching.js rename to algorithms/searching/naivePatternSearching.js diff --git a/sorting/BogoSort.js b/algorithms/sorting/BogoSort.js similarity index 100% rename from sorting/BogoSort.js rename to algorithms/sorting/BogoSort.js diff --git a/algorithms/sorting/Distance.js b/algorithms/sorting/Distance.js new file mode 100644 index 0000000..797710c --- /dev/null +++ b/algorithms/sorting/Distance.js @@ -0,0 +1,18 @@ +function GetDistanceBetweenPoints(v1, v2) { + let dx = v1.x - v2.x; + let dy = v1.y - v2.y; + let dz = v1.z - v2.z; + + return Math.sqrt(dx * dx + dy * dy + dz * dz); +} +function GetDistanceBetweenPointsXZ(v1, v2) { + let v13f = new Vector3f(v1.x, 0.0, v1.z); + let v14f = new Vector3f(v2.x, 0.0, v2.z); + return GetDistanceBetweenPoints(v13f, v14f); +} + +function GetDistanceBetweenPointsXY(v1, v2) { + let v13f = new Vector3f(v1.x, v1.y, 0.0); + let v14f = new Vector3f(v2.x, v2.y, 0.0); + return GetDistanceBetweenPoints(v13f, v14f); +} diff --git a/sorting/bubbleSort.js b/algorithms/sorting/bubbleSort.js similarity index 100% rename from sorting/bubbleSort.js rename to algorithms/sorting/bubbleSort.js diff --git a/algorithms/sorting/color.js b/algorithms/sorting/color.js new file mode 100644 index 0000000..3b25098 --- /dev/null +++ b/algorithms/sorting/color.js @@ -0,0 +1,14 @@ +function HexToRGB(hex) +{ + var bigint = parseInt(hex, 16); + var r = (bigint >> 16) & 255; + var g = (bigint >> 8) & 255; + var b = bigint & 255; + + return new RGB(r, g, b); + +} + +function RGBToHex(rgb) { + return '#' + ((1 << 24) + (rgb.r << 16) + (rgb.g << 8) + rgb.b).toString(16).slice(1); + } diff --git a/sorting/countingSort.js b/algorithms/sorting/countingSort.js similarity index 100% rename from sorting/countingSort.js rename to algorithms/sorting/countingSort.js diff --git a/sorting/flashSort.js b/algorithms/sorting/flashSort.js similarity index 100% rename from sorting/flashSort.js rename to algorithms/sorting/flashSort.js diff --git a/sorting/gnomeSort.js b/algorithms/sorting/gnomeSort.js similarity index 100% rename from sorting/gnomeSort.js rename to algorithms/sorting/gnomeSort.js diff --git a/sorting/gulagSort.js b/algorithms/sorting/gulagSort.js similarity index 100% rename from sorting/gulagSort.js rename to algorithms/sorting/gulagSort.js diff --git a/sorting/heapSort.js b/algorithms/sorting/heapSort.js similarity index 100% rename from sorting/heapSort.js rename to algorithms/sorting/heapSort.js diff --git a/sorting/insertionSort.js b/algorithms/sorting/insertionSort.js similarity index 100% rename from sorting/insertionSort.js rename to algorithms/sorting/insertionSort.js diff --git a/sorting/mergeSort.js b/algorithms/sorting/mergeSort.js similarity index 100% rename from sorting/mergeSort.js rename to algorithms/sorting/mergeSort.js diff --git a/sorting/pancakeSort.js b/algorithms/sorting/pancakeSort.js similarity index 100% rename from sorting/pancakeSort.js rename to algorithms/sorting/pancakeSort.js diff --git a/sorting/quickSort.js b/algorithms/sorting/quickSort.js similarity index 100% rename from sorting/quickSort.js rename to algorithms/sorting/quickSort.js diff --git a/sorting/radixSort.js b/algorithms/sorting/radixSort.js similarity index 100% rename from sorting/radixSort.js rename to algorithms/sorting/radixSort.js diff --git a/sorting/selectionSort.js b/algorithms/sorting/selectionSort.js similarity index 100% rename from sorting/selectionSort.js rename to algorithms/sorting/selectionSort.js diff --git a/sorting/shellSort.js b/algorithms/sorting/shellSort.js similarity index 100% rename from sorting/shellSort.js rename to algorithms/sorting/shellSort.js diff --git a/algorithms/strings/anagram.js b/algorithms/strings/anagram.js new file mode 100644 index 0000000..c5c1085 --- /dev/null +++ b/algorithms/strings/anagram.js @@ -0,0 +1,9 @@ +//Check if 2 words are anagrams of each other. +var o1 = "arms"; +var o2 = "mars" +//Remove non-letter characters, and sort the letters in alphabetical order. +var n1 = o1.replace(/\W+/g,'').toLowerCase().split("").sort().join(""); +var n2 = o2.replace(/\W+/g,'').toLowerCase().split("").sort().join(""); +var isAnagram = n1==n2; +if(isAnagram) console.log("The two words are anagrams"); +else console.log("The two words are not anagrams"); diff --git a/strings/checkPalindrome.js b/algorithms/strings/checkPalindrome.js similarity index 100% rename from strings/checkPalindrome.js rename to algorithms/strings/checkPalindrome.js diff --git a/strings/integerReversal.js b/algorithms/strings/integerReversal.js similarity index 100% rename from strings/integerReversal.js rename to algorithms/strings/integerReversal.js diff --git a/strings/largestSumOfTwo.js b/algorithms/strings/largestSumOfTwo.js similarity index 100% rename from strings/largestSumOfTwo.js rename to algorithms/strings/largestSumOfTwo.js diff --git a/strings/missingNumber.js b/algorithms/strings/missingNumber.js similarity index 100% rename from strings/missingNumber.js rename to algorithms/strings/missingNumber.js diff --git a/strings/palindrome.js b/algorithms/strings/palindrome.js similarity index 100% rename from strings/palindrome.js rename to algorithms/strings/palindrome.js diff --git a/strings/pigLatin.js b/algorithms/strings/pigLatin.js similarity index 100% rename from strings/pigLatin.js rename to algorithms/strings/pigLatin.js diff --git a/license b/license new file mode 100644 index 0000000..559a12b --- /dev/null +++ b/license @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2018 All Algorithms and its contributors (allalgorithms.com) +Copyright (c) 2018 Carlos Abraham (abranhe.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/readme.md b/readme.md index 4deee00..dd64172 100644 --- a/readme.md +++ b/readme.md @@ -1,51 +1,416 @@ -
- +We are accepting all pull requests. [Read More](https://github.com/AllAlgorithms/algorithms/issues/40) + +




- -
+ Algorithms Logo +
+

-

All ▲lgorithms implemented in Javascript

- - - - - - +
+
+
+ +

+ What is an algorithm?    + Contributing    + Stickers & T-Shirts +

+ + +

+ + Twitter +    + + Instagram +    + + Github +    +

+ +
+

+ Huge collection of All ▲lgorithms implemented in multiple languages +

+
+ + + + + +
-## Contents - -- [Greedy Algorithms](greedy-algorithms) -- [Graphs](graphs) -- [Math](math) -- [Neutral Network](neutral-network) -- [Ciphers](ciphers) -- [Data Structures](data-structures) -- [Dynamic Programming](dynamic-programming) -- [Hashes](hashes) -- [Searches](searches) -- [Sorting](sorting) -- [Strings](strings) -- [Traversals](traversals) -- [Others](others) +## See -## License +- [What is an algorithm](#what-is-an-algorithm) +- [Contributing](https://github.com/AllAlgorithms/algorithms/blob/master/.github/contributing.md) +- [Code of Conduct](https://github.com/AllAlgorithms/algorithms/blob/master/.github/code-of-conduct.md) +- [Stickers and T-Shirts](https://www.redbubble.com/people/abranhe/works/34285088) +- [Twitter](https://twitter.com/AllAlgorithms) +- [Instagram](https://instagram.com/AllAlgorithms) +- [Algorithms Categories](#categories) +- [Maintainers](#maintainers) +- [License](#license) + + +## What is an algorithm? + +Informally, an algorithm is any well-defined computational procedure that takes +some value, or set of values, as input and produces some value, or set of values, as +output. An algorithm is thus a sequence of computational steps that transform the +input into the output. + +An algorithm should have three important characteristics to be considered valid: + +- **It should be finite**: If your algorithm never ends trying to solve the problem +it was designed to solve then it is useless +- **It should have well defined instructions**: Each step of the algorithm has to +be precisely defined; the instructions should be unambiguously specified for each case. +- **It should be effective**: The algorithm should solve the problem it was designed +to solve. And it should be possible to demonstrate that the algorithm converges with +just a paper and pencil. + +## Categories + +> Structure of The All ▲lgoritms project + +- [Artificial Intelligence](#artificial-intelligence) +- [Backtracking](#backtracking) +- [Bit Manipulation](#bit-manipulation) +- [Cellular Automaton](#cellular-automaton) +- [Ciphers](#ciphers) +- [Computational Geometry](#computational-geometry) +- [Cryptography](#cryptography) +- [Data Structures](#data-structures) +- [Divide and conquer](#divide-and-conquer) +- [Dynamic Programming](#dynamic-programming) +- [Gaming Theory](#gaming-theory) +- [Graphs](#graphs) +- [Greedy Algorithms](#greedy-algorithms) +- [Math](#math) +- [Networking](#networking) +- [Numerical Analysis](#numerical-analysis) +- [Operating system](#operating-system) +- [Randomized Algorithms](#randomized-algorithms) +- [Searches](#searches) +- [Selections Algorithms](#selections-algorithms) +- [Sorting](#sorting) +- [Strings](#strings) +- [Online Challenges](#online-challenges) +- [Others](#others) + +## [Artificial Intelligence](artificial-intelligence) + +- [Density-based spatial clustering of applications with noise (DBSCAN Clustering)](https://allalgorithms.com/docs/dbscan) +- [Interactive Self-Organizing Data Analysis Technique yAy! (ISODATA Clustering)](https://allalgorithms.com/docs/isodata) +- [Linear Regression](https://allalgorithms.com/docs/linear-regression) +- [Logistic Regression](https://allalgorithms.com/docs/logistic-regression) +- [Neutral Style Transfer](https://allalgorithms.com/docs/neutral-style-transfer) +- [SATisfiable (SAT)](https://allalgorithms.com/docs/sat) +- [Travelling salesman problem (TSP)](https://allalgorithms.com/docs/tsp) +- [A* (A Star)](https://allalgorithms.com/docs/a-star) +- [Artificial Neutral Network](https://allalgorithms.com/docs/artificial-neutral-network) +- [Convolutional Neutral Network](https://allalgorithms.com/docs/convolutional-neutral-network) +- [Decision Tree](https://allalgorithms.com/docs/decision-tree) +- [Factorization Machines](https://allalgorithms.com/docs/factorization-machines) +- [Gaussian Mixture Model](https://allalgorithms.com/docs/gaussian-mixtrue-model) +- [Gradient Boosting Trees](https://allalgorithms.com/docs/gradient-boostring-trees) +- [Hierachical Clustering](https://allalgorithms.com/docs/hierachical-clustering) +- [Image Processing](https://allalgorithms.com/docs/image-processing) +- [K Nearest Neighbors](https://allalgorithms.com/docs/k-nearest-neighbors) +- [K Means](https://allalgorithms.com/docs/k-means) +- [Minimax](https://allalgorithms.com/docs/minimax) +- [Native Bayes](https://allalgorithms.com/docs/native-bayes) +- [Nearest Sequence Memory](https://allalgorithms.com/docs/nearest-sequence-memory) +- [Neutral Network](https://allalgorithms.com/docs/neutral-network) +- [Perceptron](https://allalgorithms.com/docs/perceptron) +- [Principal Component Analysis](https://allalgorithms.com/docs/principal-component-analysis) +- [Q Learing](https://allalgorithms.com/docs/q-learning) +- [Random Forests](https://allalgorithms.com/docs/random-forest) +- [Restricted Boltzman Machine](https://allalgorithms.com/docs/restricted-boltzman-machine) + +## [Backtracking](backtracking) + +- [Algorithm X](backtracking/algorithm-x) +- [Crossword Puzzle](backtracking/crossword-Puzzle) +- [Knight Tour](backtracking/knight-tour) +- [M Coloring Problem](backtracking/m-coloring-problem) +- [N Queen](backtracking/n-queen) +- [Number of ways in Maze](backtracking/number-of-ways-in-maze) +- [Partitions of set](backtracking/partitions-of-set) +- [Permutation of Strings](backtracking/permutation-of-strings) +- [Powerset](backtracking/powerset) +- [Rat in maze](backtracking/rat-in-maze) +- [Subset Sum](backtracking/subset-sum) +- [Sudoku Solve](backtracking/sudoku-solve) + +## [Bit Manipulation](bit-manipulation) + +- [Addition using bits](bit-manipulation/adding-using-bits) +- [Bit divisor](bit-manipulation/bit-divisor) +- [Byte swapper](bit-manipulation/byte-swapper) +- [Convert numbers to binary](bit-manipulation/convert-numbers-to-binary) +- [Count set bits](bit-manipulation/count-set-bits) +- [Flip bits](bit-manipulation/flip-bits) +- [Hamming distance](bit-manipulation/hamming-distace) +- [Invert bit](bit-manipulation/invert-bit) +- [Lonely integer](bit-manipulation/lonely-integer) +- [Magic Number](bit-manipulation/magic-number) +- [Maximum XOR Value](bit-manipulation/maximun-xor-value) +- [Power of 2](bit-manipulation/power-of-2) +- [Subset Generation](bit-manipulation/subset-generation) +- [Sum binary numbers](bit-manipulation/sum-binary-numbers) +- [Sum equals XOR](bit-manipulation/sum-equals-xor) +- [Thrice unique number](bit-manipulation/thrice-unique-number) +- [Twice unique number](bit-manipulation/twice-unique-number) +- [XOR Swap](bit-manipulation/xor-swap) + +## [Cellular Automaton](cellular-automaton) + +- [Brians Brain](cellular-automaton/brians-brain) +- [Conways Game of life](cellular-automaton/conways-game-of-life) +- [Elementary Cellular Automata](cellular-automaton/elementary-cellular-automata) +- [Generic Algorithm](cellular-automaton/generic-algorithm) +- [Langtons Ant](cellular-automaton/langtons-ant) +- [Nobili Cellular Automata](cellular-automaton/nobili-cellular-automata) +- [Von Neoumann Cellular Automata](cellular-automaton/von-neoumann-cellular-automata) + +## [Computational Geometry](computational-geometry) + +- [2D Line intersection](computational-geometry/) +- [2D Separating Axis test](computational-geometry/) +- [Area of polygon](computational-geometry/) +- [Area of triangle](computational-geometry/) +- [Axis aligned bounding box collision](computational-geometry/) +- [Bresenham Line](computational-geometry/) +- [Chans Algorithm](computational-geometry/) +- [Cohen Sutherland Lineclip](computational-geometry/) +- [Distance between points](computational-geometry/) +- [Graham Scan](computational-geometry/) +- [Halfplane intersection](computational-geometry/) +- [Jarvis March](computational-geometry/) +- [Quickull](computational-geometry/) +- [Sphere tetrahedron intersection](computational-geometry/) +- [Sutherland Hodgeman clipping](computational-geometry/) + +## [Cryptography](cryptography) + +- [Affine Cipher](cryptography/) +- [Atbash Cipher](cryptography/) +- [Autokey Cipher](cryptography/) +- [Baconian Cipher](cryptography/) +- [Caesar Cipher](cryptography/) +- [Colummnar Cipher](cryptography/) +- [Vigenere Cipher](cryptography/) -This work is licensed under a [MIT License](https://github.com/abranhe/algorithms/blob/master/LICENSE) +## [Data Structures](data-structures) -[![MIT IMG][mit-license]]((https://github.com/abranhe/algorithms/blob/master/LICENSE)) +- [Bag](data-structures/bag/) +- [Hashes](data-structures/hashes/) +- [Linked List](data-structures/linked-list/) +- [List](data-structures/list/) +- [Queue](data-structures/queue/) +- [Stack](data-structures/stack/) +- [Tree](data-structures/tree/) -To the extent possible under law, [Carlos Abraham](https://go.abranhe.com/github) has waived all copyright and related or neighboring rights to this work. +## [Divide and conquer](divide-and-conquer) +- [Strassen Matrix Manipulation](divide-and-conquer/) +- [Closest Pair of Point](divide-and-conquer/) +- [Inversion Count](divide-and-conquer/) +- [Karatsuba Multiplication](divide-and-conquer/) +- [Maximum Contiguous subsequence sum](divide-and-conquer/) +- [Merge Sort using divide and conquer](divide-and-conquer/) +- [Quick Sort using divide and conquer](divide-and-conquer/) +- [Tournament Method to find min max](divide-and-conquer/) +- [Warnock Algorithm](divide-and-conquer/) +- [X Power Y](divide-and-conquer/) -[mit-license]: https://cdn.abranhe.com/projects/algorithms/mit-license.png +## [Dynamic Programming](dynamic-programming) + +- [Array Median](dynamic-programming) +- [Optima Binary Search Tree](dynamic-programming) +- [Binomial Coefficient](dynamic-programming) + +## [Gaming Theory](gaming-theory) + +- [Nim Next Best Move Game](gaming-theory/) +- [Nim Win Loss Game](gaming-theory/) +- [Grundy Numbers Kayle Game](gaming-theory/) + +## [Graphs](graphs) + +- [Bipartite Check](graphs/) +- [Adjacency Lists graphs representation](graphs/) +- [A* (A Star)](https://allalgorithms.com/docs/a-star) + +## [Greedy Algorithms](greedy-algorithms) + +- [Activity Selection](greedy-algorithms) +- [Dijkstra Shortest Path](greedy-algorithms) +- [Egyptian Fraction](greedy-algorithms) + +## [Math](math) + +- [2 Sum](math/) +- [Add Polynomials](math/) +- [Amicable Numbers](math/) +- [Armstrong Numbers](math/) +- [Automorphic Numbers](math/) +- [Average Stream Numbers](math/) +- [Babylonian Method](math/) +- [Binomial Coefficient](math/) +- [Catalan Number](math/) +- [Check is Square](math/) +- [Convolution](math/) +- [Coprime Numbers](math/) +- [Count Digits](math/) +- [Count Trailing Zeroes](math/) +- [Decoding of String](math/) +- [Delannoy Number](math/) +- [Derangements](math/) +- [DFA Division](math/) +- [Diophantine](math/) +- [Divided Differences](math/) +- [Euler Totient](math/) +- [Exponentiation Power](math/) +- [Factorial](math/factorial) +- [Fast Fourier transform](math/) +- [Fast inverse (sqrt) Square Root](math/) + +## [Networking](networking) + +- [Packet Sniffer](networking/) +- [Determine Endianess](networking/) +- [Validate IP](networking/) + +## [Numerical Analysis](numerical-analysis) + +- [Integral](numerical-analysis/integral) +- [Monte Carlo](numerical-analysis/monte-carlo) +- [Runge Kutt](numerical-analysis/runge-kutt) + +## [Operating system](operating-system) + +- [Currency](operating-system/) +- [Deadlocks](operating-system/) +- [Memory Management](operating-system/) +- [Scheduling](operating-system/) +- [Shell](operating-system/) + +## [Randomized Algorithms](randomized-algorithms) + +- [Birthday Paradox](randomized-algorithms) +- [Karger Minimum Cut Algorithm](randomized-algorithms) +- [Kth Smallest Element Algorithm](randomized-algorithms) +- [Random from Stream](randomized-algorithms) +- [Random Node Linked list](randomized-algorithms) +- [Randomized Quicksort](randomized-algorithms) +- [Reservoir Sampling](randomized-algorithms) +- [Shuffle an Array](randomized-algorithms) + +## [Searches](searches) + +- [Binary Search](searches) +- [Exponential Search](searches) +- [Fibonacci Search](searches) +- [Fuzzy Search](searches) +- [Interpolation Search](searches) +- [Jump Search](searches) +- [Linear Search](searches) +- [Ternay Search](searches) + +## [Selections Algorithms](selections-algorithms) + +- [Median of Medians](selections-algorithms) +- [Quick Select](selections-algorithms) + +## [Sorting](sorting) + +- [Bead Sort](sorting/) +- [Bogo Sort](sorting/) +- [Bubble Sort](sorting/) +- [Bucket Sort](sorting/) +- [Circle Sort](sorting/) +- [Comb Sort](sorting/) +- [Counting Sort](sorting/) +- [Cycle Sort](sorting/) +- [Flash Sort](sorting/) +- [Gnome Sort](sorting/) +- [Heap Sort](sorting/) +- [Insertion Sort](sorting/) +- [Intro Sort](sorting/) +- [Median Sort](sorting/) +- [Merge Sort](sorting/) +- [Pipeonhole Sort](sorting/) +- [Quick Sort](sorting/) +- [Radix Sort](sorting/) +- [Selection Sort](sorting/) +- [Shaker Sort](sorting/) +- [Shell Sort](sorting/) +- [Sleep Sort](sorting/) +- [Stooge Sort](sorting/) +- [Topological Sort](sorting/) +- [Tree Sort](sorting/) + +## [Strings](strings) + +- [Aho Corasick Algorithm](strings) +- [Anagram Search](strings) +- [Arithmetic on large numbers](strings) +- [Boyer Moore Algorithm](strings) +- [Finite Automata](strings) +- [Kasai Algorithm](strings) +- [Kmp Algorithm](strings) +- [Levenshteing Distance](strings) +- [Lipogram Checker](strings) + +## [Online Challenges](online-challenges) + +- [Coderbyte](online-challenges/coderbyte) +- [Code Chef](online-challenges/code-chef) +- [Code Eval](online-challenges/code-eval) +- [Hackerearth](online-challenges/hackerearth) +- [Hackerrank](online-challenges/hackerrank) +- [LeetCode](online-challenges/leetcode) +- [Project Euler](online-challenges/project-euler) +- [Rosalind](online-challenges/rosalind) +- [SPOJ](online-challenges/spoj) +- [Top Coder](online-challenges/top-coder)` + +## [Others](others) + +- [Average](others/) +- [Biggest of n numbers](others/) +- [Biggest Suffix](others/) +- [Fifteen Puzzle](others/) +- [Jaccard Similarity](others/) +- [Jose Phus Problem](others/) +- [Lapindrom Checker](others/) +- [Leap Year](others/) +- [Magic Square](others/) +- [Majority Element](others/) +- [Minimum subarray size with degree](others/) +- [No operator addition](others/) +- [Paint fill](others/) +- [Split list](others/) +- [Tokenizer](others/) +- [Unique number](others/) + +## License + +This work is released under MIT License. + +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.

-
+
\ No newline at end of file diff --git a/sorting/ShellSort.js b/sorting/ShellSort.js deleted file mode 100644 index 61df2d9..0000000 --- a/sorting/ShellSort.js +++ /dev/null @@ -1,29 +0,0 @@ -/* "Shell sort or Shell's method, is an in-place comparison sort. -It can be seen as either a generalization of sorting by exchange (bubble sort) or sorting by insertion (insertion sort). -The method starts by sorting pairs of elements far apart from each other, then progressively reducing the gap between elements to be compared. -Starting with far apart elements can move some out-of-place elements into position faster than a simple nearest neighbor exchange." */ - -function shellSort(arr) { - var increment = arr.length / 2; - while (increment > 0) { - for (i = increment; i < arr.length; i++) { - var j = i; - var temp = arr[i]; - - while (j >= increment && arr[j-increment] > temp) { - arr[j] = arr[j-increment]; - j = j - increment; - } - - arr[j] = temp; - } - - if (increment == 2) { - increment = 1; - } else { - increment = parseInt(increment*5 / 11); - } - } - return arr; -} - diff --git a/src/.gitkeep b/src/.gitkeep new file mode 100644 index 0000000..e69de29