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/README.md b/README.md deleted file mode 100644 index 731a705..0000000 --- a/README.md +++ /dev/null @@ -1,42 +0,0 @@ -
- -
-
- -
-
-

All ▲lgorithms implemented in Javascript

- - - - - - -
- -## Contents - -- [Arithmetic Analysis]() -- [File Transfer Protocol]() -- [Graphs]() -- [Math]() -- [Neutral Network]() -- [Ciphers]() -- [Data Structures]() -- [Dynamic Programming]() -- [Hashes]() -- [Searches]() -- [Sorting]() -- [Strings]() -- [Traversals]() - -## License - -This work is licensed under a [MIT License](https://github.com/abranhe/algorithms/blob/master/LICENSE) - -[![MIT IMG][mit-license]]((https://github.com/abranhe/algorithms/blob/master/LICENSE)) - -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. - - -[mit-license]: https://cdn.abraham.gq/projects/algorithms/mit-license.png diff --git a/algorithms/ciphers/rot13.js b/algorithms/ciphers/rot13.js new file mode 100644 index 0000000..30a9b22 --- /dev/null +++ b/algorithms/ciphers/rot13.js @@ -0,0 +1,18 @@ +// JavaScript implementation of ROT13 +// +// Author: NIEZWAN ABDUL WAHID + +function rot13(str) { + var string = []; + + for (var i = 0; i < str.length; i++) { + if ((str.charCodeAt(i) > 77 && str.charCodeAt(i) <= 90) || (str.charCodeAt(i) > 109 && str.charCodeAt(i) <= 122)) { + string.push(String.fromCharCode(str.charCodeAt(i) - 13)); + } else { + string.push(String.fromCharCode(str.charCodeAt(i) + 13)); + } + } + return string.join(""); +} + +// rot13("hello") == "uryyb" \ No newline at end of file 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/algorithms/data-structures/doublyLinkedList.js b/algorithms/data-structures/doublyLinkedList.js new file mode 100644 index 0000000..59cbd19 --- /dev/null +++ b/algorithms/data-structures/doublyLinkedList.js @@ -0,0 +1,226 @@ +/** + * @author Rashik Ansar + * + * Implementation of doubly linked list + * Doubly linked list is a linear data structure + */ + +class Node { + constructor(data) { + this.data = data; + this.next = null; + this.prev = null; + } +} + +class DoublyLinkedList { + constructor() { + this.head = null; + this.tail = null; + this.length = 0; + } + + /** + * Adding new node as a tail of the linked list + * @param {any} data This dataue is added at the end of list + * @returns {DoublyLinkedList} LinkedList after adding new node as tail + */ + push(data) { + let temp = new Node(data); + if (!this.head) { + this.head = temp; + this.tail = temp; + } else { + this.tail.next = temp; + temp.prev = this.tail; + this.tail = temp; + } + this.length++; + return this; + } + + /** + * Adding new node as a head of the linked list + * @param {any} data This dataue is added at the beginning of the list + * @returns {DoublyLinkedList} LinkedList after adding a new node as head + */ + unshift(data) { + let current = new Node(data); + if (!this.head) { + this.head = current; + this.tail = current; + } else { + this.head.prev = current; + current.next = this.head; + this.head = current; + } + this.length++; + return this; + } + + /** + * Adding a node to the linkedList at specified position + * @param {number} index Position at which new node to insert + * @param {any} data dataue in the new node + * @returns {DoublyLinkedList} LinkedList after inserting a new node + */ + insert(index, data) { + if (index < 0 || index > this.length) { + throw Error('Given index is out of range'); + } + if (index === this.length) { + return this.push(data); + } + if (index === 0) { + return this.unshift(data); + } + let insertNode = new Node(data); + let previous = this.get(index - 1); + let temp = previous.next; + previous.next = insertNode; + insertNode.prev = previous; + insertNode.next = temp; + temp.prev = insertNode; + this.length++; + return this; + } + + /** + * Removes the node at the end of linked list(tail of linked list) + * @returns {Node} the node which is going to pop + */ + pop() { + if (!this.head) { + throw Error( + 'UNDERFLOW :::: LinkedList is empty, there is nothing to remove' + ); + } + let temp = this.tail; + if (this.length === 1) { + this.head = null; + this.tail = null; + } else { + this.tail = temp.prev; + this.tail.next = null; + temp.prev = null; + } + this.length--; + return temp; + } + + /** + * Removes the node from the beginnig of linked list(head of linked list) + * @returns {Node} the node which is going to shift + */ + shift() { + if (!this.head) { + throw Error( + 'UNDERFLOW :::: LinkedList is empty, there is nothing to remove' + ); + } + let current = this.head; + if (this.length === 1) { + this.head = null; + this.tail = null; + } else { + this.head = current.next; + this.head.prev = null; + current.next = null; + } + this.length--; + return current; + } + + /** + * Removes a node from the linkedList at specified position + * @param {number} index + * @returns {Node} Node which is removed from LinkedList + */ + remove(index) { + if (index < 0 || index > this.length) { + throw Error('Given index is out of range'); + } + if (index === this.length - 1) { + return this.pop(); + } + if (index === 0) { + return this.shift(); + } + let removeNode = this.get(index); + let before = removeNode.prev; + let after = removeNode.next; + before.next = after; + after.prev = before; + removeNode.next = null; + removeNode.prev = null; + this.length--; + return removeNode; + } + + /** + * Retrieve the node at specified index + * @param {number} index Index of the node + * @returns {Node} LinkedList Node at specified index + */ + get(index) { + if (index < 0 || index >= this.length) { + throw Error('Given index is out of range'); + } + let current; + if (index <= this.length / 2) { + let counter = 0; + current = this.head; + while (counter !== index) { + current = current.next; + counter++; + } + } else { + let counter = this.length - 1; + current = this.tail; + while (counter !== index) { + current = current.prev; + counter--; + } + } + return current; + } + + /** + * Change the data of node at specified index + * @param {number} index Index of the node + * @param {any} data data replaces the current data at given index + * @returns {DoublyLinkedList} LinkedList + */ + set(index, data) { + let existedNode = this.get(index); + if (existedNode) { + existedNode.data = data; + return this; + } + } + + /** + * Traversing or Printing the Linked list + */ + traverse() { + let current = this.head; + console.log(this.length); + while (current) { + console.log(current.data); + current = current.next; + } + } + + /** + * @returns {[]} Linkedlist data as elements in Array + */ + listAsArray() { + let arr = []; + let current = this.head; + while (current) { + arr.push(current.data); + current = current.next; + } + return arr; + } +} diff --git a/algorithms/data-structures/hashTable.js b/algorithms/data-structures/hashTable.js new file mode 100644 index 0000000..603c9d2 --- /dev/null +++ b/algorithms/data-structures/hashTable.js @@ -0,0 +1,76 @@ +/** + * @author Rashik Ansar + * + * Implementation of Hash Table + */ + +class HashTable { + constructor(size = 47) { + this.keyMap = new Array(size); + } + + /** + * Hash Function + * Private method to generate hash of the given data + * @param {*} key data to hash + */ + _hash(key) { + let total = 0; + const RANDOM_PRIME = 31; + for (let i = 0; i < Math.min(key.length, 100); i++) { + let char = key[i]; + let value = char.charCodeAt(0) - 96; + total = (total * RANDOM_PRIME + value) % this.keyMap.length; + } + return total; + } + + set(key, value) { + let index = this._hash(key); + if (!this.keyMap[index]) { + this.keyMap[index] = []; + } + this.keyMap[index].push([key, value]); + return this; + } + + get(key) { + let index = this._hash(key); + if (this.keyMap[index]) { + for (let i = 0; i < this.keyMap[index].length; i++) { + if (this.keyMap[index][i][0] === key) { + return this.keyMap[index][i]; + } + } + } + return undefined; + } + + values() { + let valArray = []; + for (let i = 0; i < this.keyMap.length; i++) { + if (this.keyMap[i]) { + for (let j = 0; j < this.keyMap[i].length; j++) { + if (!valArray.includes(this.keyMap[i][j][1])) { + valArray.push(this.keyMap[i][j][1]); + } + } + } + } + return valArray; + } + + keys() { + let keysArray = []; + for (let i = 0; i < this.keyMap.length; i++) { + if (this.keyMap[i]) { + for (let j = 0; j < this.keyMap[i].length; j++) { + if (!keysArray.includes(this.keyMap[i][j][0])) { + keysArray.push(this.keyMap[i][j][0]); + } + } + } + } + return keysArray; + } +} 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/algorithms/data-structures/priorityQueue.js b/algorithms/data-structures/priorityQueue.js new file mode 100644 index 0000000..1eb68ca --- /dev/null +++ b/algorithms/data-structures/priorityQueue.js @@ -0,0 +1,117 @@ +/** + * @author Rashik Ansar + * + * Implemntaion of priority queue + * Lower the priority value higher its priority + * under the hood its implementing minBinaryHeap + */ +class PriorityQueue { + constructor() { + this.values = []; + } + + /** + * Adding data to the queue + * @param {*} data Data to add into queue + * @param {*} priority Priority of the data + * @returns {PriorityQueue} + */ + enqueue(data, priority) { + let temp = new Node(data, priority); + this.values.push(temp); + this.bubbleUp(); + return this; + } + + /** + * removing a node from the queue + * @returns {Node} + */ + dequeue() { + const min = this.values[0]; + const end = this.values.pop(); + if (this.values.length > 0) { + this.values[0] = end; + this.sinkDown(); + } + return min; + } + + /** + * enqueue helper function + */ + bubbleUp() { + let index = this.values.length - 1; + const element = this.values[index]; + while (index > 0) { + let parentIndex = Math.floor((index - 1) / 2); + let parent = this.values[parentIndex]; + // if (element.priority <= parent.priority) break; //maxBinaryHeap condition + if (element.priority >= parent.priority) break; //minBinaryHeap condition + this.values[parentIndex] = element; + this.values[index] = parent; + index = parentIndex; + } + } + + /** + * dequeue helper function + */ + sinkDown() { + let index = 0; + const length = this.values.length; + const element = this.values[index]; + while (true) { + let leftChildIndex = 2 * index + 1; + let rightChildIndex = 2 * index + 2; + let leftChild; + let rightChild; + let swap = null; + + if (leftChildIndex < length) { + leftChild = this.values[leftChildIndex]; + // Change below comparision operators to make maxBinaryHeap + if (leftChild.priority < element.priority) { + swap = leftChildIndex; + } + } + + if (rightChildIndex < length) { + rightChild = this.values[rightChildIndex]; + // Change below comparision operators to make maxBinaryHeap + if ( + (!swap && rightChild.priority < element.priority) || + (swap && rightChild.priority < leftChild.priority) + ) { + swap = rightChildIndex; + } + } + + if (!swap) break; + + this.values[index] = this.values[swap]; + this.values[swap] = element; + index = swap; + } + } +} + +class Node { + constructor(data, priority) { + this.data = data; + this.priority = priority; + } +} + +let a = new PriorityQueue(); +a.enqueue('Common Cold', 10); +a.enqueue('Gunshot wound', 2); +a.enqueue('Fever', 8); + +console.log(a); +a.dequeue(); +console.log(a); +a.dequeue(); +console.log(a); +a.dequeue(); +console.log(a); diff --git a/algorithms/data-structures/queue.js b/algorithms/data-structures/queue.js new file mode 100644 index 0000000..098ad47 --- /dev/null +++ b/algorithms/data-structures/queue.js @@ -0,0 +1,68 @@ +/** + * @author Rashik Ansar + * + * Implementation of Queue Data structure + * Queue follows FIFO (First In First Out) Principle + */ + +class Node { + constructor(data) { + this.data = data; + this.next = null; + } +} + +class Queue { + constructor() { + this.first = null; + this.last = null; + this.size = 0; + } + + /** + * Adding data to the end of queue + * @param {*} data Data to add in the queue + * @returns {Queue} Returns the queue after adding new data + */ + enqueue(data) { + let newNode = new Node(data); + if (!this.first) { + this.first = newNode; + this.last = newNode; + } else { + this.last.next = newNode; + this.last = newNode; + } + this.size++; + return this; + } + + /** + * Removing data from the beginning of the queue + * @returns Data that is removing from queue + */ + dequeue() { + if (!this.first) { + throw Error( + 'UNDERFLOW::: The queue is empty, there is nothing to remove' + ); + } + let temp = this.first; + if (this.first === this.last) { + this.last = null; + } + this.first = this.first.next; + this.size--; + return temp.data; + } + + /** + * @returns First element in the queue + */ + peek() { + if (!this.first) { + throw Error('Stack is empty'); + } + return this.first.data; + } +} diff --git a/algorithms/data-structures/singlyLinkedList.js b/algorithms/data-structures/singlyLinkedList.js new file mode 100644 index 0000000..72b091e --- /dev/null +++ b/algorithms/data-structures/singlyLinkedList.js @@ -0,0 +1,233 @@ +/** + * @author Rashik Ansar + * + * Implementation of singly linked list + * Singly linked list is a linear data strucutre + */ + +class Node { + constructor(data) { + this.data = data; + this.next = null; + } +} + +class SinglyLinkedList { + constructor() { + this.head = null; + this.tail = null; + this.length = 0; + } + + /** + * Adding new node as a tail of the linked list + * @param {any} data This dataue is added at the end of list + * @returns {SinglyLinkedList} LinkedList after adding new node as tail + */ + push(data) { + let temp = new Node(data); + if (!this.head) { + this.head = temp; + this.tail = this.head; // temp + } else { + this.tail.next = temp; + this.tail = temp; + } + this.length++; + return this; + } + + /** + * Adding new node as a head of the linked list + * @param {any} data This dataue is added at the beginning of the list + * @returns {SinglyLinkedList} LinkedList after adding a new node as head + */ + unshift(data) { + let temp = new Node(data); + if (!this.head) { + this.head = temp; + this.tail = this.head; + } else { + temp.next = this.head; + this.head = temp; + } + this.length++; + return this; + } + + /** + * Adding a node to the linkedList at specified position + * @param {number} index Position at which new node to insert + * @param {any} data dataue in the new node + * @returns {SinglyLinkedList} LinkedList after inserting a new node + */ + insert(index, data) { + if (index < 0 || index > this.length) { + throw Error('Given index is out of range'); + } + if (index === this.length) { + return this.push(data); + } + if (index === 0) { + return this.unshift(data); + } + let insertNode = new Node(data); + let previous = this.get(index - 1); + let temp = previous.next; + previous.next = insertNode; + insertNode.next = temp; + this.length++; + return this; + } + + /** + * Removes the node at the end of linked list(tail of linked list) + * @returns {Node} the node which is going to pop + */ + pop() { + if (!this.head) { + throw Error( + 'UNDERFLOW :::: LinkedList is empty, there is nothing to remove' + ); + } + let current = this.head; + let temp = current; + while (current.next) { + temp = current; + current = current.next; + } + this.tail = temp; + this.tail.next = null; + this.length--; + this.emptyListCheck(); + return current; + } + + /** + * Removes the node from the beginnig of linked list(head of linked list) + * @returns {Node} the node which is going to shift + */ + shift() { + if (!this.head) { + throw Error( + 'UNDERFLOW :::: LinkedList is empty, there is nothing to remove' + ); + } + let current = this.head; + this.head = current.next; + this.length--; + this.emptyListCheck(); + return current; + } + + /** + * Removes a node from the linkedList at specified position + * @param {number} index + * @returns {Node} Node which is removed from LinkedList + */ + remove(index) { + if (index < 0 || index > this.length) { + throw Error('Given index is out of range'); + } + if (index === this.length - 1) { + return this.pop(); + } + if (index === 0) { + return this.shift(); + } + let previous = this.get(index - 1); + let temp = previous.next; + previous.next = temp.next; + this.length--; + return temp; + } + + /** + * Retrieve the node at specified index + * @param {number} index Index of the node + * @returns {Node} LinkedList Node at specified index + */ + get(index) { + if (index < 0 || index >= this.length) { + throw Error('Given index is out of range'); + } + let counter = 0; + let current = this.head; + while (counter !== index) { + current = current.next; + counter++; + } + return current; + } + + /** + * Change the data of node at specified index + * @param {number} index Index of the node + * @param {any} data data replaces the current data at given index + * @returns {SinglyLinkedList} LinkedList + */ + set(index, data) { + // Here error checking will be done by the get method itself + // No need to specify explicitly + let existedNode = this.get(index); + if (existedNode) { + existedNode.data = data; + return this; + } + } + + /** + * Reversing the Linked list + * @returns {SinglyLinkedList} LinkedList + */ + reverse() { + let temp = this.head; + this.head = this.tail; + this.tail = temp; + + let previous = null; + let after = null; + while (temp) { + after = temp.next; + temp.next = previous; + previous = temp; + temp = after; + } + return this; + } + + /** + * Traversing or Printing the Linked list + */ + traverse() { + let current = this.head; + while (current) { + console.log(current.data); + current = current.next; + } + } + + /** + * @returns {[]} Linkedlist data as elements in Array + */ + listAsArray() { + let arr = []; + let current = this.head; + while (current) { + arr.push(current.data); + current = current.next; + } + return arr; + } + + /** + * Utility Function (PRIVATE FUNCTION) + * if the length is zero then assign null to both head and tail + */ + emptyListCheck() { + if (this.length === 0) { + this.head = null; + this.tail = null; + } + } +} diff --git a/algorithms/data-structures/stack.js b/algorithms/data-structures/stack.js new file mode 100644 index 0000000..62a772b --- /dev/null +++ b/algorithms/data-structures/stack.js @@ -0,0 +1,113 @@ +/** +* @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 { + /** + * initialize stack instances with null + */ + constructor() { + this.first = null; + this.last = null; + this.size = 0; + } + + /** + * Adding data to Top of the stack + * @param {*} data + * @returns {Stack} + */ + push(data) { + let newNode = new Node(data); + if (!this.first) { + this.first = newNode; + this.last = newNode; + } else { + let temp = this.first; + this.first = newNode; + this.first.next = temp; + } + this.size++; + return this; + } + + /** + * Removing data frpm Top of the stack + * @returns {Node.data} The data that is removing from the stack + */ + pop() { + if (!this.first) { + throw Error('UNDERFLOW :::: Stack is empty, there is nothing to remove'); + } + let current = this.first; + if (this.first === this.last) { + this.last = null; + } + this.first = current.next; + this.size--; + return current.data; + } + + /** + * @returns {Node.data} Top most element of the stack + */ + peek() { + if (!this.first) { + throw Error('Stack is empty'); + } + 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 { + constructor(data) { + 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/algorithms/dynamic-programming/linkedList.js b/algorithms/dynamic-programming/linkedList.js new file mode 100644 index 0000000..4df144c --- /dev/null +++ b/algorithms/dynamic-programming/linkedList.js @@ -0,0 +1,111 @@ +// LinkedList and Node function Constructor +function LinkedList() { + this.head = null; + this.tail = null; +}; + +function Node(value, next, prev) { + this.value = value; + this.next = next; + this.prev = prev; +}; + +// Add to head + +LinkedList.prototype.addHead = function(value) { + var newNode = new Node(value, this.head, null); + if(this.head) { + this.head.prev = newNode; + } else { + this.tail = newNode; + } + this.head = newNode; +}; + +var LL = new LinkedList(); +LL.addHead(100); +LL.addHead(200); +LL.addHead(300); +LL.addHead(200); +console.log(LL); + +// Add to tail +LinkedList.prototype.addTail = function(value) { + var newNode = new Node(value, null, this.tail); + if(this.tail) { + this.tail.next = newNode; + }else { + this.head = newNode; + } + this.tail = newNode; +}; + +LL.addTail(100); +LL.addTail(200); +LL.addTail(300); +console.log(LL); +console.log(ll.head.value); + +// Remove from head +LinkedList.prototype.removeHead = function(){ + if(this.head == null) { + return null; + } + else { + var val = this.head.value; + this.head = this.head.next; + } + if(!this.head) this.tail = null; + return val; +}; + +var ll = new LinkedList(); +console.log(LL.removeHead()); +console.log(LL); + +// Remove from tail +LinkedList.prototype.removeTail = function() { + if(!this.tail) return null; + var val = this.tail.value; + this.tail = this.tail.prev; + if(this.tail) this.tail.next = null; + else this.head = null; + return val; +} + +console.log(LL.removeTail()); +console.log(LL.removeTail()); +console.log(LL.removeTail()); +console.log(LL); + +// search in LinkedList +LinkedList.prototype.search = function(searchValue) { + if(!this.head) return null; + var currentNode = this.head; + while(currentNode){ + if(currentNode.value === searchValue) return currentNode.value; + currentNode = currentNode.next; + } + return null; +} + +console.log(LL.search(100)); + +// find indexOf element in LinkedList +LinkedList.prototype.indexOf = function(value) { + if(!this.head) return null; + var currentNode = this.head; + var counter = 0; + var indexArr = new Array; + while(currentNode){ + if(currentNode.value === value){ + indexArr.push(counter); + } + counter++; + currentNode = currentNode.next; + } + return indexArr; +} + +console.log(LL.indexOf(200)); + diff --git a/algorithms/dynamic-programming/singlyLinkedList.js b/algorithms/dynamic-programming/singlyLinkedList.js new file mode 100644 index 0000000..06eb92b --- /dev/null +++ b/algorithms/dynamic-programming/singlyLinkedList.js @@ -0,0 +1,239 @@ +// Implementation of single link list +// Author: Sheary Tan + +class Node { + constructor(val) { + this.val = val; + this.next = null; + } +} + +class SinglyList { + constructor() { + // Initializing... + // There is nothing at the beginning so + // the head & the tail should be empty, + // and the length should be zero too + this.head = null; + this.tail = null; + this.length = 0; + } + + // 1st method: push (push the val into the end of the list) + push(val) { + // Firstly, we have to accept a new value + var newNode = new Node(val); + // If there is no head, means there is nothing on the list, + // set the head & tail pointers to this value. + if(!this.head) { + this.head = newNode; + this.tail = newNode; + } else { + // If there is value existed, assign the newNode to the next value + // of the current existing value + this.tail.next = newNode; + // Update the tail to it! + this.tail = newNode; + } + // Increment the length and return the newly created link-list + this.length++; + return this; + } + + // 2nd method: pop (remove the last item) + pop() { + // If there is nothing on the list, return undefined + if (!this.head) return undefined; + // Loop through to find the last item + var current = this.head; + var newTail = current; + while(current.next) { + newTail = current; + current = current.next + } + // Set the found tail to tail + this.tail = newTail; + // The next one will be null since we + // would like to remove it + this.tail.next = null; + // Decrease the length + this.length--; + // If there is nothing left after removing + // set the head and tail to be null + if(this.length === 0) { + this.head = null; + this.tail = null; + } + return current; + } + + // 3rd method: shift (remove the first item) + shift() { + // If there is no nothing on the list, return undefined + if(!this.head) return undefined; + // Store the current head in a new variable + var currentHead = this.head; + // Shift the head to the next value of the currentHead + this.head = currentHead.next; + // Decrement the length since we have removed the head + this.length--; + if(this.length === 0) { + this.head = null; + this.tail = null; + } + return currentHead; + } + + // 4th method: unshift (add item to the beginning ) + unshift(val) { + // Initialize the value to a new node; + var newNode = new Node(val); + // If there is nothing on the list, set the head and tail + // point to that new node + if(!this.head) { + this.head = newNode; + this.tail = newNode; + } else { + // In order to set the head value points to the head, + // we have to set the current head to the next item of newNode + newNode.next = this.head; + // and now we can assign the head to newNode! + this.head = newNode + } + // Increment the length after adding the new head + this.length++; + return this; + } + + // 5th method: get + get(i) { + // get accepts an index in and find the specific value + // If i is less than zero, or greater and equal to the length + // of the current link list, return null; + if(i < 0 || i >= this.length) return null; + // Use the counter to find the value + var counter = 0; + var current = this.head; + while(counter !== i) { + current = current.next; + counter++ + } + // Found it and return + return current + } + + // 6th method: set + // Use the given index to find the target value and change it with the new + // given value + set(i, val) { + var targetNode = this.get(i); + if(targetNode) { + targetNode.val = val; + return true; + } + return false; + } + + // 8th method: remove (from any index) + remove(i) { + // Check if there's anything on the list + if(i < 0 || i >= this.length) return undefined; + if(i === 0) return this.shift(); + if(i === this.length - 1) return this.pop(); + // Get the previous item of the target + var previousTarget = this.get(i - 1); + // Since we've got the previous item of the target, + // we now can remove the target by setting the next item of previousTarget + // to the next item of "removed" + var removed = previousTarget.next; + previousTarget.next = removed.next + // Decrease the length + this.length--; + return removed; + } + + // 9th method: reverse + reverse() { + // Firstly we have to set the head to the tail, + // and the tail to the head + var target = this.head; + this.head = this.tail; + this.tail = target; + // Now we have to re-arrange those next & previous + // items of the list + var next; + var prev = null; + // Loop through every single item on the list + for(let i = 0; i < this.length; i++) { + // This part is a bit confusing, let's take an example + // Example = [1, 2, 3, 4, 5], T = target, P = previous, N = next + next = target.next; + // Firstly, the target is 1 + // [1, 2, 3, 4, 5] + // T + // And target.next is 2 + // [1, 2, 3, 4, 5] + // T N + target.next = prev; + // Remember our target is 1 & prev is null? Now it said the next item of + // 1 is null, + // 1 -> null + prev = target; + // Now we're setting the "prev = null" to the target value + // which now equals to "prev = 1" + // [1, 2, 3, 4, 5] + // P N + target = next; + // And lastly we set the "next" value to be T + // [1, 2, 3, 4, 5] + // P T + + + // So the cycle repeats again, now let's go through 1 more cycle + // [1, 2, 3, 4, 5] + // P T + // next = target.next + // [1, 2, 3, 4, 5] + // P T N + // target.next = prev + // Remember we have the list (1 -> null)? + // now target.next = prev means the next item of 2 is 1 + // 2 -> 1 -> null + // prev = target + // Now 2 is prev + // [1, 2, 3, 4, 5] + // P N + // target = next + // And 3 is now the target + // [1, 2, 3, 4, 5] + // P T + // And the cycle repeats again until the target reach the end of the list... + } + return this; + } + + // 10th method: insert + insert(i, val) { + // Check the requirements + if(i < 0 || i >= this.length) return false; + if(i === this.length) return !!this.push(val); + if(i === 0) return !!this.unshift(val); + + // Initialize a new node + var newNode = new Node(val); + // Get the previous node of newNode + var prevNode = this.get(i - 1); + // Remember we haven't insert the newNode into the list! + // And also store the next item of prevNode in a temporary variable + // because we are going to set it to the next item of newNode later + var temp = prevNode.next; + // Now we can set the next item of prevNode to newNode + prevNode.next = newNode; + // Then the next item of newNode will be the temporary item we store + newNode.next = temp; + // Increment the length + this.length++; + return true; + } + +} diff --git a/algorithms/graphs/bfs.js b/algorithms/graphs/bfs.js new file mode 100644 index 0000000..96f6348 --- /dev/null +++ b/algorithms/graphs/bfs.js @@ -0,0 +1,44 @@ +/* + A non-recursive implementation of bfs with worst-case space complexity O(|E|) +*/ + +function Vertex (name, neighbours) { + this.name = name; + this.neighbours = neighbours; +} + +function bfs (root) { + var visited = {} + var stack = [] + + stack.push(root) + while(!!stack.length) { + var vertex = stack.shift() + + if (!visited[vertex.name]) { + visited[vertex.name] = true + console.log('Visiting vertex ', vertex.name) + + var len = vertex.neighbours.length + for (var index = 0; index < len; index++) { + stack.push(vertex.neighbours[index]) + } + } + } +} + +var root = new Vertex('root', [ + new Vertex('child 1', [ + new Vertex('grandchild 1', []), new Vertex('grandchild 2', []) + ]), + new Vertex('child 2', [ + new Vertex('grandchild 3', []), + ]), + new Vertex('child 3', [ + new Vertex('grandchild 4', [ + new Vertex('grandgrandchild 1', []) + ]), + ]), +]) + +bfs(root) diff --git a/algorithms/graphs/breadth-first-search.js b/algorithms/graphs/breadth-first-search.js new file mode 100644 index 0000000..e1cbe9b --- /dev/null +++ b/algorithms/graphs/breadth-first-search.js @@ -0,0 +1,93 @@ +// Breadth-first Search +// author: Pavel Kalugin + +class Graph { + constructor(n) { + // the number of vertexes + this.n = n; + + // adjacency list representation + this.adjList = Array.from(Array(n), () => []); + } + + addDirectedEdge(from, to) { + this.adjList[from].push(to); + } + + addEdge(v, w) { + this.adjList[v].push(w); + this.adjList[w].push(v); + } + + // s - the number of the starting vertex + // to - the number of the end vertex + breadthFirstSearch(s) { + if (s < 0 || s >= this.n) { + throw Error('Wrong starting vertex'); + } + + let queue = []; + let visited = new Array(this.n); + let path = new Array(this.n); + let time = new Array(this.n).fill(-1); + + // The first iteration + queue.push(s); + visited[s] = true; + path[s] = -1; + time[s] = 0; + + while (queue.length > 0) { + let v = queue.shift(); + + for (let to of this.adjList[v]) { + if (!visited[to]) { + queue.push(to); + visited[to] = true; + path[to] = v; + time[to] = time[v] + 1; + } + } + } + + return { visited, path, time }; + } + + // Array of distances to vertexes from the starting one + BFS(s) { + return this.breadthFirstSearch(s).time; + } + + findPathToVertex(s, to) { + let { visited, path } = this.breadthFirstSearch(s); + + if (!visited[to]) { + return 'No path'; + } + + let realPath = []; + + for (let v = to; v !== -1; v = path[v]) { + realPath.unshift(v); + } + + return realPath.reduce((out, i) => `${out} ${i}`, `Path from ${s} to ${to}:`); + } +} + +function test() { + let g = new Graph(5); + + g.addDirectedEdge(0, 1); + g.addDirectedEdge(1, 2); + g.addDirectedEdge(2, 3); + g.addDirectedEdge(3, 3); + g.addDirectedEdge(4, 2) + g.addEdge(2, 0); + + + console.log(g.BFS(2)); + console.log(g.findPathToVertex(4, 1)); +} + +test(); diff --git a/algorithms/graphs/dfs.js b/algorithms/graphs/dfs.js new file mode 100644 index 0000000..bcbfe8e --- /dev/null +++ b/algorithms/graphs/dfs.js @@ -0,0 +1,46 @@ +/* + A non-recursive implementation of DFS with worst-case space complexity O(|E|) + + according to wiki pseudocode https://en.wikipedia.org/wiki/Depth-first_search +*/ + +function Vertex (name, neighbours) { + this.name = name; + this.neighbours = neighbours; +} + +function dfs (root) { + var visited = {} + var stack = [] + + stack.push(root) + while(!!stack.length) { + var vertex = stack.pop() + + if (!visited[vertex.name]) { + visited[vertex.name] = true + console.log('Visiting vertex ', vertex.name) + + var len = vertex.neighbours.length + for (var index = 0; index < len; index++) { + stack.push(vertex.neighbours[index]) + } + } + } +} + +var root = new Vertex('root', [ + new Vertex('child 1', [ + new Vertex('grandchild 1', []), new Vertex('grandchild 2', []) + ]), + new Vertex('child 2', [ + new Vertex('grandchild 3', []), + ]), + new Vertex('child 3', [ + new Vertex('grandchild 4', [ + new Vertex('grandgrandchild 1', []) + ]), + ]), +]) + +dfs(root) diff --git a/algorithms/graphs/dijkstra.js b/algorithms/graphs/dijkstra.js new file mode 100644 index 0000000..46d2308 --- /dev/null +++ b/algorithms/graphs/dijkstra.js @@ -0,0 +1,99 @@ +// One of the algorithms I was to use in my Microsoft interview was Dijkstra's algorithm. Here is a basic implementation. +function PriorityQueue() { + this._nodes = []; + + this.enqueue = function(priority, key) { + this._nodes.push({key: key, priority: priority }); + this.sort(); + }; + this.dequeue = function() { + return this._nodes.shift().key; + }; + this.sort = function() { + this._nodes.sort(function (a, b) { + return a.priority - b.priority; + }); + }; + this.isEmpty = function() { + return !this._nodes.length; + }; +} + +/** + * Pathfinding starts here + */ +function Graph(){ + var INFINITY = 1/0; + this.vertices = {}; + + this.addVertex = function(name, edges){ + this.vertices[name] = edges; + }; + + this.shortestPath = function(start, finish) { + var nodes = new PriorityQueue(), + distances = {}, + previous = {}, + path = [], + smallest, vertex, neighbor, alt; + + for (vertex in this.vertices) { + if (vertex === start) { + distances[vertex] = 0; + nodes.enqueue(0, vertex); + } + else { + distances[vertex] = INFINITY; + nodes.enqueue(INFINITY, vertex); + } + + previous[vertex] = null; + } + + while (!nodes.isEmpty()) { + smallest = nodes.dequeue(); + + if (smallest === finish) { + path = []; + + while (previous[smallest]) { + path.push(smallest); + smallest = previous[smallest]; + } + + break; + } + + if (!smallest || distances[smallest] === INFINITY){ + continue; + } + + for (neighbor in this.vertices[smallest]) { + alt = distances[smallest] + this.vertices[smallest][neighbor]; + + if (alt < distances[neighbor]) { + distances[neighbor] = alt; + previous[neighbor] = smallest; + + nodes.enqueue(alt, neighbor); + } + } + } + + return path; + }; +} + +var g = new Graph(); + +g.addVertex('A', {B: 7, C: 8}); +g.addVertex('B', {A: 7, F: 2}); +g.addVertex('C', {A: 8, F: 6, G: 4}); +g.addVertex('D', {F: 8}); +g.addVertex('E', {H: 1}); +g.addVertex('F', {B: 2, C: 6, D: 8, G: 9, H: 3}); +g.addVertex('G', {C: 4, F: 9}); +g.addVertex('H', {E: 1, F: 3}); + +// Log test, with the addition of reversing the path and prepending the first node so it's more readable +console.log(g.shortestPath('A', 'H').concat(['A']).reverse()); diff --git a/algorithms/graphs/unweightedGraph.js b/algorithms/graphs/unweightedGraph.js new file mode 100644 index 0000000..7d48e5a --- /dev/null +++ b/algorithms/graphs/unweightedGraph.js @@ -0,0 +1,154 @@ +/** + * @author Rashik Ansar + * Implemtaion of graph with the help of Adjacency List + * Its Unweighted graph implemetation + */ + +class Graph { + constructor() { + this.adjacencyList = {}; + } + + /** + * Adding a vertex to the graph + * @param {*} vertex The data of the vertex to add into graph + * @returns {Graph} + */ + addVertex(vertex) { + if (this.adjacencyList[vertex]) { + throw Error(`${vertex} already exist in graph... `); + } else { + this.adjacencyList[vertex] = []; + } + // return this; + } + + /** + * Removing a vertex from the graph + * @param {*} vertex The data of the vertex to remove from graph + */ + removeVertex(vertex) { + if (this.adjacencyList[vertex]) { + while (this.adjacencyList[vertex].length) { + const itemInArray = this.adjacencyList[vertex].pop(); + this.removeEdge(vertex, itemInArray); + } + delete this.adjacencyList[vertex]; + // return this; // Added for testing before traversal methods + } else { + throw Error(`${vertex} doesn't exist...`); + } + } + + /** + * Adding an edge between two vertices in the graph + * @param {*} vertex1 + * @param {*} vertex2 + */ + addEdge(vertex1, vertex2) { + if (this.adjacencyList[vertex1] && this.adjacencyList[vertex2]) { + this.adjacencyList[vertex1].push(vertex2); + this.adjacencyList[vertex2].push(vertex1); + // return this; + } else { + throw Error('Given vertex/vertices might not exist in graph...'); + } + } + + /** + * Removing an existing edge between two vertices in the graph + * @param {*} vertex1 + * @param {*} vertex2 + */ + removeEdge(vertex1, vertex2) { + if (this.adjacencyList[vertex1] && this.adjacencyList[vertex2]) { + this.adjacencyList[vertex1] = this.adjacencyList[vertex1].filter( + i => i !== vertex2 + ); + this.adjacencyList[vertex2] = this.adjacencyList[vertex2].filter( + i => i !== vertex1 + ); + // return this; + } else { + throw Error('Given vertex/vertices might not exist in graph...'); + } + } + + /** + * Travesal of the graph by breadth-first approach + * @param {*} start Starting vertex for traversal + * @returns {[]} + */ + breadthFirstTraversal(start) { + const queue = []; + const result = []; + const visited = {}; + let current; + queue.push(start); + visited[start] = true; + + while (queue.length) { + current = queue.shift(); + result.push(current); + this.adjacencyList[current].forEach(x => { + if (!visited[x]) { + visited[x] = true; + queue.push(x); + } + }); + } + return result; + } + + /** + * Depth First Traversal (recursive approach) + * + * @param {*} start Starting vertex for traversal + * @returns {[]} + */ + DFTrecursuive(start) { + const visited = {}; + const result = []; + const adjacencyList = this.adjacencyList; + function dfs(vertex) { + if (!vertex) { + throw Error('Incorrect starting vertex!'); + } + visited[vertex] = true; + result.push(vertex); + adjacencyList[vertex].forEach(x => { + if (!visited[x]) { + return dfs(x); + } + }); + } + dfs(start); + return result; + } + /** + * Depth First Traversal (Iterative approach) + * + * @param {*} start Starting vertex for traversal + * @returns {[]} + */ + DFTiterative(start) { + const stack = []; + const visited = {}; + const result = []; + let current; + + stack.push(start); + visited[start] = true; + while (stack.length) { + current = stack.pop(); + result.push(current); + this.adjacencyList[current].forEach(x => { + if (!visited[x]) { + visited[x] = true; + stack.push(x); + } + }); + } + return result; + } +} 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/algorithms/math/checkPrime.js b/algorithms/math/checkPrime.js new file mode 100644 index 0000000..bf2f4b8 --- /dev/null +++ b/algorithms/math/checkPrime.js @@ -0,0 +1,25 @@ +// JavaScript implementation of prime number checking +// +// Author: Nikolas Huebecker + +function isPrime(n){ + var divisor = 2; + + while (n > divisor){ + if(n % divisor == 0){ + return false; + }else { + divisor++; + } + } + return true; +} + +// Test + +console.log("The number 137 is prime:" +console.log(isPrime(137)) + + +console.log("The number 16 is prime:" +console.log(isPrime(16)) diff --git a/algorithms/math/collatz.js b/algorithms/math/collatz.js new file mode 100644 index 0000000..aebbe70 --- /dev/null +++ b/algorithms/math/collatz.js @@ -0,0 +1,31 @@ +/* Collatz conjecture */ + +function collatz(n) { + var numbers = [] + + while (n > 1) { + numbers.push(n) + if (n % 2 === 0) { + n = n / 2; + } else { + n = (3 * n) + 1; + } + } + numbers.push(n) + return numbers +} + +console.log( + 'Collatz conjecture for n = 11', + collatz(11) +) + +console.log( + 'Collatz conjecture for n = 27', + collatz(27) +) + +console.log( + 'Collatz conjecture for n = 51', + collatz(51) +) diff --git a/algorithms/math/computeNCR.js b/algorithms/math/computeNCR.js new file mode 100644 index 0000000..0d3c7f1 --- /dev/null +++ b/algorithms/math/computeNCR.js @@ -0,0 +1,17 @@ +// JavaScript implementation of nCr computation +// +// Author: Shriharsha KL + +function fact(n) { + if (n === 0) + return 1; + + return n * fact(n - 1); +} + +function nCr(n, r) { + return fact(n) / (fact(r) * fact(n - r)); +} + +// Test +console.log(nCr(10, 2)) \ No newline at end of file diff --git a/algorithms/math/degreeRadianConversion.js b/algorithms/math/degreeRadianConversion.js new file mode 100644 index 0000000..8356f6d --- /dev/null +++ b/algorithms/math/degreeRadianConversion.js @@ -0,0 +1,16 @@ +// JavaScript implementation of Degree-Radian Conversion + +// Author: Niezwan Abdul Wahid + +function degreeToRadian(degree) { + return degree * (Math.PI / 180); +} + +function radianToDegree(radian) { + return radian * (180 / Math.PI); +} + + +//degreeToRadian(180) === 3.1415926 + +//radianToDegree(3.1415) === 179.994 \ No newline at end of file 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/algorithms/math/factorial-recursive.js b/algorithms/math/factorial-recursive.js new file mode 100644 index 0000000..8f7a73b --- /dev/null +++ b/algorithms/math/factorial-recursive.js @@ -0,0 +1,15 @@ +// JavaScript implementation of recursive factorial + +// Author: Jay McDoniel + +function factorial(number) { + let retNum = number ? number : 1; + if (number >= 2) { + retNum *= factorial(number - 1); + } + return retNum; +} + +for (let i = 0; i < 20; i++) { + console.log(factorial(i)); +} \ No newline at end of file diff --git a/algorithms/math/factorial.js b/algorithms/math/factorial.js new file mode 100644 index 0000000..03820a6 --- /dev/null +++ b/algorithms/math/factorial.js @@ -0,0 +1,15 @@ +// JavaScript implementation of Factorial + +// Author: Niezwan Abdul Wahid + +function factorial(number) { + let val = 1; + + for (let i = 2; i <= number; i += 1) { + val *= i; + } + + return val; +} + +//factorial(13) === 6 227 020 800 \ No newline at end of file diff --git a/algorithms/math/fibonacci-recursive.js b/algorithms/math/fibonacci-recursive.js new file mode 100644 index 0000000..2cc2ae6 --- /dev/null +++ b/algorithms/math/fibonacci-recursive.js @@ -0,0 +1,20 @@ +/ JavaScript recursive implementation of Fibonacci item finder +// +// Author: Nikoals Huebecker + +// Time Complexity O(2^n) + +function fibonacci(n){ + if(n<=1) + return n; + else + return fibonacci(n-1) + fibonacci (n-2); +} + +// Test + +console.log("The first item of the sequence is:") +console.log(fibonacci(1)) + +console.log("The tweleth item of the sequence is:") +console.log(fibonacci(12)) diff --git a/algorithms/math/fibonacci.js b/algorithms/math/fibonacci.js new file mode 100644 index 0000000..458673a --- /dev/null +++ b/algorithms/math/fibonacci.js @@ -0,0 +1,25 @@ +// JavaScript implementation of Fibonacci item finder +// +// Author: Nikoals Huebecker + +// Time Complexity O(n) + +function fibonacci(n){ + var fib = [0, 1]; + + if (n <= 2) return 1; + + for (var i = 2; i <=n; i++ ){ + fib[i] = fib[i-1]+fib[i-2]; + } + + return fib[n]; +} + +// Test + +console.log("The first item of the sequence is:") +console.log(fibonacci(1)) + +console.log("The tweleth item of the sequence is:") +console.log(fibonacci(12)) diff --git a/algorithms/math/fibonnaci.js b/algorithms/math/fibonnaci.js new file mode 100644 index 0000000..65e343d --- /dev/null +++ b/algorithms/math/fibonnaci.js @@ -0,0 +1,17 @@ +// FIBONACCI SEQUENCE + +var fibonacci_series = function (n) +{ + if (n===1) + { + return [0, 1]; + } + else + { + var s = fibonacci_series(n - 1); + s.push(s[s.length - 1] + s[s.length - 2]); + return s; + } +}; + + console.log(fibonacci_series(8)); diff --git a/algorithms/math/gcd.js b/algorithms/math/gcd.js new file mode 100644 index 0000000..f7f4889 --- /dev/null +++ b/algorithms/math/gcd.js @@ -0,0 +1,13 @@ +// GCD - greatest common divisor or HCF - highest common factor + +function gcd (small, large) { + if (small === 0) { return large } else { return gcd(large % small, small) } +} + +const gcdList = [[6, 9], [6, 12], [12, 18], [7, 14], [7, 13]] + +for (const set of gcdList) { + const small = set[0] + const large = set[1] + console.log(`GCD for ${small} and ${large} is ${gcd(small, large)}`) +} diff --git a/algorithms/math/greatestCommonDivisor.js b/algorithms/math/greatestCommonDivisor.js new file mode 100644 index 0000000..62a85c6 --- /dev/null +++ b/algorithms/math/greatestCommonDivisor.js @@ -0,0 +1,11 @@ +// JavaScript implementation of greatest common divisor of two positive number + +let gcd = function(a, b) { + if (!b) { + return a; + } + + return gcd(b, a % b); +}; + +console.log(gcd(2154, 458)); \ No newline at end of file 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/algorithms/math/naturalNumbersSum.js b/algorithms/math/naturalNumbersSum.js new file mode 100644 index 0000000..1cab9d1 --- /dev/null +++ b/algorithms/math/naturalNumbersSum.js @@ -0,0 +1,7 @@ +// Change this as the limit of numbers to be added +// const lastNumber = 4 // 1+2+3+4 +const lastNumber = 5 // 1+2+3+4+4 + + +let sum = lastNumber*(1+lastNumber)*0.5 +console.log(sum) 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/algorithms/math/quadrant.js b/algorithms/math/quadrant.js new file mode 100644 index 0000000..020fa29 --- /dev/null +++ b/algorithms/math/quadrant.js @@ -0,0 +1,21 @@ +// Author: Ferdhika Yudira +// Quadrant detector + +var quadrant = function (x, y){ + var quadrant = 4; + + if(x > 0 && y > 0){ + quadrant = 1; + }else if(x < 0 && y > 0){ + quadrant = 2; + }else if(x < 0 && y < 0){ + quadrant = 3; + } + + return quadrant; +} + +// test +console.log(quadrant(-5, 2)); +console.log(quadrant(5, 2)); +console.log(quadrant(-5, -2)); \ No newline at end of file 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/algorithms/math/smallest-common-multiple.js b/algorithms/math/smallest-common-multiple.js new file mode 100644 index 0000000..7bcbaa6 --- /dev/null +++ b/algorithms/math/smallest-common-multiple.js @@ -0,0 +1,32 @@ +// Find the smallest common multiple of the given parameters that can be evenly divided by both, as well as +// by all numbers in the range between these parameters. +// The range is an array of two numbers, not necessarily be in numerical order. + +function smallestCommons(arr) { + arr.sort(function(a, b) { //sorting given numbers + return b - a; + }); + + var num = []; + for (var i = arr[0]; i >= arr[1]; i--) { //create array of all nums + num.push(i); + } + + var quot = 0; //variables for the quotient that can access them outside the loop + var loop = 1; + var n; + // Run code while n is not the same as the array length. + do { + quot = num[0] * loop * num[1]; + for (n = 2; n < num.length; n++) { + if (quot % num[n] !== 0) { + break; + } + } + loop++; + } while (n !== num.length); + + return quot; +} + +smallestCommons([1,5]); //Example of given numbers diff --git a/algorithms/math/spiralMatrix.js b/algorithms/math/spiralMatrix.js new file mode 100644 index 0000000..761c1f8 --- /dev/null +++ b/algorithms/math/spiralMatrix.js @@ -0,0 +1,39 @@ +function getSpiralMatrix (n) { + const matrix = [] + for (let i = 0; i < n; ++i) { matrix.push([]) } + let counter = 1 + let startRow = 0 + let endRow = n - 1 + let startCol = 0 + let endCol = n - 1 + + while (startCol <= endCol && startRow <= endRow) { + for (let i = startCol; i <= endCol; ++i) { + matrix[startRow][i] = counter + counter++ + } + startRow++ + + for (let i = startRow; i <= endRow; ++i) { + matrix[i][endCol] = counter + counter++ + } + endCol-- + + for (let i = endCol; i >= startCol; --i) { + matrix[endRow][i] = counter + counter++ + } + endRow-- + + for (let i = endRow; i >= startRow; --i) { + matrix[i][startCol] = counter + counter++ + } + startCol++ + } + return matrix +} + +const matrix = getSpiralMatrix(3) +console.log(matrix) diff --git a/algorithms/others/bigonotaion.js b/algorithms/others/bigonotaion.js new file mode 100644 index 0000000..54f495c --- /dev/null +++ b/algorithms/others/bigonotaion.js @@ -0,0 +1,56 @@ +// Constant runtime - Big O Notation: "O (1)" +function log(array) { + console.log(array[0]); + console.log(array[1]); +} + +log([1, 2, 3, 4]); +log([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); + + +// Linear runtime - Big O Notation: "O (n)" +function logAll(array) { + for (var i = 0; i < array.length; i++) { + console.log(array[i]); + } +} + +logAll([1, 2, 3, 4, 5]); +logAll([1, 2, 3, 4, 5, 6]); +logAll([1, 2, 3, 4, 5, 6, 7]); + + +// Exponential runtime - Big O Notation: "O (n^2)" +function addAndLog(array) { + for (var i = 0; i < array.length; i++) { + for (var j = 0; j < array.length; j++) { + console.log(array[i] + array[j]); + } + } +} + +addAndLog(['A', 'B', 'C']); // 9 pairs logged out +addAndLog(['A', 'B', 'C', 'D']); // 16 pairs logged out +addAndLog(['A', 'B', 'C', 'D', 'E']); // 25 pairs logged out + + +// Logarithmic runtime - Big O Notation: O (log n) +function binarySearch(array, key) { + var low = 0; + var high = array.length - 1; + var mid; + var element; + + while (low <= high) { + mid = Math.floor((low + high) / 2, 10); + element = array[mid]; + if (element < key) { + low = mid + 1; + } else if (element > key) { + high = mid - 1; + } else { + return mid; + } + } + return -1; +} diff --git a/algorithms/others/checkPrime.js b/algorithms/others/checkPrime.js new file mode 100644 index 0000000..d3a7bad --- /dev/null +++ b/algorithms/others/checkPrime.js @@ -0,0 +1,17 @@ +function isPrime(n){ + var divisor = 2; + + while (n > divisor){ + if(n % divisor == 0){ + return false; + } + else + divisor++; + } + return true; +} + +isPrime(137); +// -> 'true' +isPrime(237); +// -> 'false' diff --git a/algorithms/others/primeFactors.js b/algorithms/others/primeFactors.js new file mode 100644 index 0000000..386b5f2 --- /dev/null +++ b/algorithms/others/primeFactors.js @@ -0,0 +1,18 @@ +function primeFactors(n){ + var factors = [], + divisor = 2; + + while(n>2){ + if(n % divisor == 0){ + factors.push(divisor); + n= n/ divisor; + } + else{ + divisor++; + } + } + return factors; +} + +primeFactors(69); +// -> [3, 23] diff --git a/algorithms/searches/binarySearch.js b/algorithms/searches/binarySearch.js new file mode 100644 index 0000000..21e780b --- /dev/null +++ b/algorithms/searches/binarySearch.js @@ -0,0 +1,32 @@ +// JavaScript implementation of Binary Search + +// Author: Niezwan Abdul Wahid + +// Binary Search only applicable to a sorted array + +let arrayOfItems = [1, 3, 5, 7, 9, 11, 13, 15, 16, 19, 22]; + +function binarySearch(arrayOfItems, itemToFind) { + let low = 0; + let high = arrayOfItems.length - 1; + let mid, pointer; + + while(low <= high) { + mid = Math.floor((low + high) / 2), + pointer = arrayOfItems[mid]; + + if(pointer === itemToFind) { + console.log('Found ' + pointer + " at index " + mid); + return; + } + if(itemToFind < pointer) { + high = mid - 1; + } else { + low = mid + 1; + } + } + console.log("Item not found"); + return null; +} + +binarySearch(arrayOfItems, 7); \ No newline at end of file diff --git a/algorithms/searches/sequentialSearch.js b/algorithms/searches/sequentialSearch.js new file mode 100644 index 0000000..c9bb298 --- /dev/null +++ b/algorithms/searches/sequentialSearch.js @@ -0,0 +1,20 @@ +// JavaScript implementation of Sequential Search + +// Author: Niezwan Abdul Wahid + +let items = [3,7,33,42,5,66,44,65,20,34] + +function sequentialSearch(item) { + for(let i=0; i < items.length; i++) { + if(items[i] === item) { + console.log( item + " found at index " + i); + return true; + } + } + return false; +} + +let item = sequentialSearch(33); +if(!item) { + console.log('Item is not in array.'); +} \ No newline at end of file diff --git a/algorithms/searching/binarySearch.js b/algorithms/searching/binarySearch.js new file mode 100644 index 0000000..715fdce --- /dev/null +++ b/algorithms/searching/binarySearch.js @@ -0,0 +1,57 @@ +/** + JavaScript implementation of the binary search algorithm. + + Author: Brendan Albert + + This is a JavaScript iterative (rather than recursive) implementation of the binary search algorithm. + + The binary search algorithm works by looking at the middle element of a list. + The list must be sorted to work correctly. + This implementation uses ascending order. + + If the value being searched for is not the middle element, then we check + if the value is smaller or larger than the middle element. + + This allows the size of the list being searched to be halved each iteration. + + The big O runtime of this algorithm is log(n). + Log(n) is nice because it means that given a huge list, say of 1 million IDs, + it will take no more than 20 iterations to determine if the ID is present. + + Arguments: value (that we are searching for), list_to_search (the list) + + Return: the value if it is found in the list or -1 if the value is not found. + */ +function binarySearch(value, list_to_search) { + + search_value = -1 + max_index = list_to_search.length - 1 + min_index = 0 + middle_index = Math.floor( (max_index + min_index) / 2) + current_element = list_to_search[middle_index] + + while (max_index >= min_index) { + + if (current_element == value) + return current_element + + else if (value > current_element) + min_index = middle_index + 1 + + else if (value < current_element) + max_index = middle_index - 1 + + middle_index = Math.floor( (min_index + max_index) / 2) + current_element = list_to_search[middle_index] + + } + + return search_value +} + +// Sample lists to test with +id_list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] +odd_list = [1,3,5,7,9,11,13,15,17,19] +short_list = ['allie', 'ben', 'charlie', 'danielle', 'emilio', 'fred', 'gina', 'henry', 'isabella'] + +console.log(binarySearch(3, odd_list)) 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/algorithms/searching/linearSearch.js b/algorithms/searching/linearSearch.js new file mode 100644 index 0000000..25d2b73 --- /dev/null +++ b/algorithms/searching/linearSearch.js @@ -0,0 +1,26 @@ +/** + * + * @author Rashik Ansar + * + * @param {number[]} arr Array of numbers to search + * @param {number} val Value to search in the given array + * @return {number[] | -1 } return array of indices at which the given value present or -1 + */ +function linearSearch(arr, val) { + let indices = []; + for (let i in arr) { + if (arr[i] === val) { + indices.push(i); + } + } + if (indices.length) return indices; + + return -1; +} + +let a = [1, 2, 3, 1, 1, 525, 5884, 545, 6854, 3, 1, 4]; + +let x = linearSearch(a, 1); +console.log(x); +let y = linearSearch(a, 545); +console.log(y); diff --git a/algorithms/searching/naivePatternSearching.js b/algorithms/searching/naivePatternSearching.js new file mode 100644 index 0000000..f23eb80 --- /dev/null +++ b/algorithms/searching/naivePatternSearching.js @@ -0,0 +1,26 @@ +/** + * @author Rashik Ansar + * + * @param {string} txt The text in which pattern has to be searched + * @param {string} pat Pattern to search in string + * @returns {number} The total count of given pattern occurence/s in the text + */ +function naiveSearch(txt, pat) { + let count = 0; + for (let i = 0; i < txt.length; i++) { + for (let j = 0; j < pat.length; j++) { + if (pat[j] !== txt[i + j]) { + break; + } + if (j === pat.length - 1) { + count++; + } + } + } + return count; +} + +let x = naiveSearch('aaabbcbaabcabcaaabcaccaabcaade', 'abc'); +console.log(x); //4 +let y = naiveSearch('meow', 'ow'); +console.log(y); //1 diff --git a/algorithms/sorting/BogoSort.js b/algorithms/sorting/BogoSort.js new file mode 100644 index 0000000..1fb43e0 --- /dev/null +++ b/algorithms/sorting/BogoSort.js @@ -0,0 +1,47 @@ +/* +* 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. +*/ + +function Bogosort(arr){ + var isSorted = function(arr){ + for(var i = 1; i < arr.length; i++){ + if (arr[i-1] > arr[i]) { + return false; + } + } + return true; + }; + + function shuffle(arr){ + var count = arr.length, temp, index; + + while(count > 0){ + index = Math.floor(Math.random() * count); + count--; + + temp = arr[count]; + arr[count] = arr[index]; + arr[index] = temp; + } + + return arr; + } + + function sort(arr){ + var sorted = false; + while(!sorted){ + arr = shuffle(arr); + sorted = isSorted(arr); + } + return arr; + } + + return sort(arr); +} + + +var array = [3, 0, 2, 5, -1, 4, 1]; +console.log("Original Array Elements"); +console.log(array); +console.log("Sorted Array Elements"); +console.log(Bogosort(array)); \ No newline at end of file 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/algorithms/sorting/countingSort.js b/algorithms/sorting/countingSort.js new file mode 100644 index 0000000..ddc557b --- /dev/null +++ b/algorithms/sorting/countingSort.js @@ -0,0 +1,31 @@ +// JavaScript implementation of counting sort +// +// Author: Dito Baskoro + +function countingSort(arr, min, max) + { + let i, z = 0, count = []; + + for (i = min; i <= max; i++) { + count[i] = 0; + } + + for (i=0; i < arr.length; i++) { + count[arr[i]]++; + } + + for (i = min; i <= max; i++) { + while (count[i]-- > 0) { + arr[z++] = i; + } + } + return arr; +} + +//Test +let array = [2, 0, 3, 5, 4, 1]; +console.log(array.length); +console.log("Original Array"); +console.log(array); +console.log("Sorted Array"); +console.log(countingSort(array, 0, 5)); diff --git a/algorithms/sorting/flashSort.js b/algorithms/sorting/flashSort.js new file mode 100644 index 0000000..a16027b --- /dev/null +++ b/algorithms/sorting/flashSort.js @@ -0,0 +1,83 @@ +// JavaScript implementation of flash sort +// Flashsort is a distribution sorting algorithm showing linear computational complexity O(n) +// +// Author: Dito Baskoro + +function flash_sort(arr) + { + let max = 0, min = arr[0]; + let n = arr.length; + let m = ~~(0.45 * n); + let l = new Array(m); + + for (let i = 1; i < n; ++i) { + if (arr[i] < min) { + min = arr[i]; + } + if (arr[i] > arr[max]) { + max = i; + } + } + + if (min === arr[max]) { + return arr; + } + + let c1 = (m - 1) / (arr[max] - min); + + + for (let k = 0; k < m; k++) { + l[k] = 0; + } + for (let j = 0; j < n; ++j) { + k = ~~(c1 * (arr[j] - min)); + ++l[k]; + } + + for (let p = 1; p < m; ++p) { + l[p] = l[p] + l[p - 1]; + } + + let hold = arr[max]; + arr[max] = arr[0]; + arr[0] = hold; + + //permutation + let move = 0, t, flash; + j = 0; + k = m - 1; + + while (move < (n - 1)) { + while (j > (l[k] - 1)) { + ++j; + k = ~~(c1 * (arr[j] - min)); + } + if (k < 0) break; + flash = arr[j]; + while (j !== l[k]) { + k = ~~(c1 * (flash - min)); + hold = arr[t = --l[k]]; + arr[t] = flash; + flash = hold; + ++move; + } + } + + //insertion + for (j = 1; j < n; j++) { + hold = arr[j]; + i = j - 1; + while (i >= 0 && arr[i] > hold) { + arr[i + 1] = arr[i--]; + } + arr[i + 1] = hold; + } + return arr; +} + +//test +const array = [3, 0, 2, 5, -1, 4, 1, -2]; +console.log("Original Array"); +console.log(array); +console.log("Sorted Array"); +console.log(flash_sort(array, 0, 5)); diff --git a/algorithms/sorting/gnomeSort.js b/algorithms/sorting/gnomeSort.js new file mode 100644 index 0000000..4bf15af --- /dev/null +++ b/algorithms/sorting/gnomeSort.js @@ -0,0 +1,27 @@ +// JavaScript implementation of gnome sort +// +// Author: Dito Baskoro + +function gnomeSort(arr) +{ + function moveBack(i) + { + for( ; i > 0 && arr[i-1] > arr[i]; i--) + { + let t = arr[i]; + arr[i] = arr[i-1]; + arr[i-1] = t; + } + } + for (let i = 1; i < arr.length; i++) + { + if (arr[i-1] > arr[i]) moveBack(i); + } + return arr; +} + +const array = [3, 0, 2, 5, -1, 4, 1, -2]; +console.log("Original Array"); +console.log(array); +console.log("Sorted Array"); +console.log(gnomeSort(array)); diff --git a/algorithms/sorting/gulagSort.js b/algorithms/sorting/gulagSort.js new file mode 100644 index 0000000..71b9895 --- /dev/null +++ b/algorithms/sorting/gulagSort.js @@ -0,0 +1,9 @@ +const gulagSort = ls => { + if (!ls.length) return [] + + const [x, y, ...xs] = ls + + return y == null ? + [x] : x < y ? + [x, ...gulagSort([y, ...xs])] : gulagSort([y, ...xs]) +} diff --git a/algorithms/sorting/heapSort.js b/algorithms/sorting/heapSort.js new file mode 100644 index 0000000..002f4ad --- /dev/null +++ b/algorithms/sorting/heapSort.js @@ -0,0 +1,52 @@ +// JavaScript implementation of heap sort +// +// Author: Dito Baskoro + +let array_length; +/* to create MAX array */ +function heap_root(input, i) { + let left = 2 * i + 1; + let right = 2 * i + 2; + let max = i; + + if (left < array_length && input[left] > input[max]) { + max = left; + } + + if (right < array_length && input[right] > input[max]) { + max = right; + } + + if (max != i) { + swap(input, i, max); + heap_root(input, max); + } +} + +function swap(input, index_A, index_B) { + let temp = input[index_A]; + + input[index_A] = input[index_B]; + input[index_B] = temp; +} + +function heapSort(input) { + + array_length = input.length; + + for (let i = Math.floor(array_length / 2); i >= 0; i -= 1) { + heap_root(input, i); + } + + for (i = input.length - 1; i > 0; i--) { + swap(input, 0, i); + array_length--; + + + heap_root(input, 0); + } +} + +const arr = [3, 0, 2, 5, -1, 4, 1, -2]; +heapSort(arr); +console.log(arr); diff --git a/algorithms/sorting/insertionSort.js b/algorithms/sorting/insertionSort.js new file mode 100644 index 0000000..84c77f6 --- /dev/null +++ b/algorithms/sorting/insertionSort.js @@ -0,0 +1,18 @@ +function insertionSort (items) { + for (var i = 0; i < items.length; i++) { + let value = items[i] + // store the current item value so it can be placed right + for (var j = i - 1; j > -1 && items[j] > value; j--) { + // loop through the items in the sorted array (the items from the current to the beginning) + // copy each item to the next one + items[j + 1] = items[j] + } + // the last item we've reached should now hold the value of the currently sorted item + items[j + 1] = value + } + + return list +} + +const list = [54, 26, 93, 17, 77, 31, 44, 55, 20] +console.log(insertionSort(list)) // [ 17, 20, 26, 31, 44, 54, 55, 77, 93 ] diff --git a/algorithms/sorting/mergeSort.js b/algorithms/sorting/mergeSort.js new file mode 100644 index 0000000..c3d57bc --- /dev/null +++ b/algorithms/sorting/mergeSort.js @@ -0,0 +1,42 @@ + +// Split the array into halves and merge them recursively +function mergeSort(arr) { + if (arr.length === 1) { + // return once we hit an array with a single item + return arr + } + + const middle = Math.floor(arr.length / 2) // get the middle item of the array rounded down + const left = arr.slice(0, middle) // items on the left side + const right = arr.slice(middle) // items on the right side + + return merge( + mergeSort(left), + mergeSort(right) + ) +} + +// compare the arrays item by item and return the concatenated result +function merge(left, right) { + let result = [] + let indexLeft = 0 + let indexRight = 0 + + while (indexLeft < left.length && indexRight < right.length) { + if (left[indexLeft] < right[indexRight]) { + result.push(left[indexLeft]) + indexLeft++ + } else { + result.push(right[indexRight]) + indexRight++ + } + } + + return result.concat(left.slice(indexLeft)).concat(right.slice(indexRight)) +} + +const list = [2, 5, 1, 3, 7, 2, 3, 8, 6, 3] +console.log(mergeSort(list)) + + +//A. Kondov, Medium \ No newline at end of file diff --git a/algorithms/sorting/pancakeSort.js b/algorithms/sorting/pancakeSort.js new file mode 100644 index 0000000..8adee30 --- /dev/null +++ b/algorithms/sorting/pancakeSort.js @@ -0,0 +1,39 @@ +// JavaScript implementation of pancake sort + +function pancake_sort(arr) { + for (let i = arr.length - 1; i >= 1; i--) { + // find the index of the largest element not yet sorted + let max_idx = 0; + let max = arr[0]; + for (let j = 1; j <= i; j++) { + if (arr[j] > max) { + max = arr[j]; + max_idx = j; + } + } + + if (max_idx == i) + continue; // element already in place + + let new_slice; + + // flip arr max element to index 0 + if (max_idx > 0) { + new_slice = arr.slice(0, max_idx+1).reverse(); + for ( j = 0; j <= max_idx; j++) + arr[j] = new_slice[j]; + } + + // then flip the max element to its place + new_slice = arr.slice(0, i+1).reverse(); + for ( j = 0; j <= i; j++) + arr[j] = new_slice[j]; + } + return arr; +} + +const array = [3, 0, 2, 5, -1, 4, 1]; +console.log("Original Array"); +console.log(array); +console.log("Sorted Array"); +console.log(pancake_sort(array, 0, 5)); diff --git a/algorithms/sorting/quickSort.js b/algorithms/sorting/quickSort.js new file mode 100644 index 0000000..7aad746 --- /dev/null +++ b/algorithms/sorting/quickSort.js @@ -0,0 +1,58 @@ +function quickSort (recievedArray) { + const sortedArray = Object.assign([], recievedArray) + + function partition (array, begin, end) { + const pivot = array[Math.floor((end + begin) / 2)] + let i = begin + let j = end + + while (i <= j) { + while (array[i] < pivot) { + i++ + } + + while (array[j] > pivot) { + j-- + } + + if (i <= j) { + swap(array, i, j) + i++ + j-- + } + } + + return i + } + + function sort (array, begin, end) { + let index + + if (array.length > 1) { + index = partition(array, begin, end) + + if (begin < index - 1) + sort(array, begin, index - 1) + + if (index < end) + sort(array, index, end) + } + + return array + } + + function swap (array, firstIndex, secondIndex) { + const temp = array[firstIndex] + array[firstIndex] = array[secondIndex] + array[secondIndex] = temp + } + + return sort(sortedArray, 0, sortedArray.length - 1) +} + +const array = [3, 2, 9, 7, 24, 11] + +const sortedArray = quickSort(array) + +console.log('array', array) +console.log('sortedArray', sortedArray) diff --git a/algorithms/sorting/radixSort.js b/algorithms/sorting/radixSort.js new file mode 100644 index 0000000..cd01fe7 --- /dev/null +++ b/algorithms/sorting/radixSort.js @@ -0,0 +1,52 @@ +/** + * Gives the number at specified digits place + * @param {number} num + * @param {number} place + */ +function getDigit(num, place) { + return Math.floor(Math.abs(num) / Math.pow(10, place)) % 10; +} + +/** + * Calculate the number of digits in a given number + * @param {number} num + */ +function digits(num) { + if (num !== 0) { + return Math.floor(Math.log10(Math.abs(num))) + 1; + } + return 1; +} + +/** + * Find the maxDigits element in the given array + * @param {number[]} arr + */ +function maxDigits(arr) { + let max = 0; + for (let i = 0; i < arr.length; i++) { + max = Math.max(max, digits(arr[i])); + } + return max; +} + +/** + * Its default base10 digit sorting + * @param {number[]} arr + */ +function radixSort(arr) { + let max = maxDigits(arr); + for (let i = 0; i < max; i++) { + let buckets = Array.from({ length: 10 }, () => []); + for (let j = 0; j < arr.length; j++) { + let digitsValue = getDigit(arr[j], i); + buckets[digitsValue].push(arr[j]); + } + arr = [].concat(...buckets); + } + return arr; +} + +let a = [234, 364, 12, 64, 21315, 75, 23425]; +let b = radixSort(a); +console.log(b); diff --git a/algorithms/sorting/selectionSort.js b/algorithms/sorting/selectionSort.js new file mode 100644 index 0000000..09a8870 --- /dev/null +++ b/algorithms/sorting/selectionSort.js @@ -0,0 +1,28 @@ +// JavaScript implementation of selection sort +// +// Author: Niezwan Abdul Wahid + +function selectionSort(arr){ + let min, temp; + let len = arr.length; + for(let i = 0; i < len; i++){ + min = i; + for(let j = i+1; j= gap && array[j - gap] > temp; j -= gap) { + array[j] = array[j - gap]; + } + array[j] = temp; + } + } + return array; +} 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/algorithms/strings/checkPalindrome.js b/algorithms/strings/checkPalindrome.js new file mode 100644 index 0000000..42fd27c --- /dev/null +++ b/algorithms/strings/checkPalindrome.js @@ -0,0 +1,42 @@ +// JavaScript implementation of palindrome check +// +// Author: Shriharsha KL + +/** + * @description Check if the input is a palindrome + * + * @param {string|number} input + * @returns {boolean} is input a palindrome? + */ +function checkPalindrome(input) { + // Only strings and numbers can be palindrome + if (typeof input !== 'string' && typeof input !== 'number') { + return null; + } + + // Convert given number to string + if (typeof input === 'number') { + input = String(input); + } + + return input === input.split('').reverse().join(''); +} + +// Test +let input = 'ABCDCBA'; +console.log(checkPalindrome(input)); // true + +input = 12321; +console.log(checkPalindrome(input)); // true + +input = 123.321; +console.log(checkPalindrome(input)); // true + +input = 'ABCD'; +console.log(checkPalindrome(input)); // false + +input = 123.4; +console.log(checkPalindrome(input)); // false + +input = {}; +console.log(checkPalindrome(input)) // null diff --git a/algorithms/strings/integerReversal.js b/algorithms/strings/integerReversal.js new file mode 100644 index 0000000..f4ce808 --- /dev/null +++ b/algorithms/strings/integerReversal.js @@ -0,0 +1,19 @@ +// JS algorithm of Integer Reversal +// Author: Irsyad + +// Sample input and output +// reverse(81) will produce 18 +// reverse(-67) will produce -76 +// reverse(-500) will produce -5 + +const reverse = integer => + parseInt(integer + .toString() + .split("") + .reverse() + .join("") + ) * Math.sign(integer); + +// Test +console.log(reverse(4729)); +console.log(reverse(-270)); \ No newline at end of file diff --git a/algorithms/strings/largestSumOfTwo.js b/algorithms/strings/largestSumOfTwo.js new file mode 100644 index 0000000..a55f2ab --- /dev/null +++ b/algorithms/strings/largestSumOfTwo.js @@ -0,0 +1,29 @@ +function topSum(arr){ + + var biggest = arr[0], + second = arr[1], + len = arr.length, + i = 2; + + if (len<2) return null; + + if (biggest biggest){ + second = biggest; + biggest = arr[i]; + } + else if (arr[i]>second){ + second = arr[i]; + } + + } + return biggest + second; +} + +topSum([5, 2, 6, 1, 3]); \ No newline at end of file diff --git a/algorithms/strings/missingNumber.js b/algorithms/strings/missingNumber.js new file mode 100644 index 0000000..d47cedc --- /dev/null +++ b/algorithms/strings/missingNumber.js @@ -0,0 +1,13 @@ +function missingNumber(arr){ + var n = arr.length+1, + sum = 0, + expectedSum = n* (n+1)/2; + + for(var i = 0, len = arr.length; i < len; i++){ + sum += arr[i]; + } + + return expectedSum - sum; +} + +missingNumber([5, 2, 6, 1, 3]); diff --git a/algorithms/strings/palindrome.js b/algorithms/strings/palindrome.js new file mode 100644 index 0000000..7b50aa9 --- /dev/null +++ b/algorithms/strings/palindrome.js @@ -0,0 +1,31 @@ +// Author: Ferdhika Yudira +// Palindrome + +var isPalindrome = function (text){ + text = text.split(''); + index=0; + palindrom=true; + + pTeks=text.length; + + i=0; + while((i { + const vows = ['a', 'e', 'i', 'o', 'u'], + res = str.split('') + + if(vows.includes(str.charAt(0))) { + return str += 'way' + } else { + for(let i = 0; i < str.length; i++) { + if(!vows.includes(str[i])) { + res.push(res.shift()) + } else { + res.push('ay') + return res.join('') + } + } + } +} \ No newline at end of file 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 new file mode 100644 index 0000000..dd64172 --- /dev/null +++ b/readme.md @@ -0,0 +1,416 @@ +We are accepting all pull requests. [Read More](https://github.com/AllAlgorithms/algorithms/issues/40) + +
+
+
+
+
+ Algorithms Logo +
+
+
+
+
+
+ +

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

+ + +

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

+ +
+

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

+
+ + + + + + +
+ +## See + +- [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/) + +## [Data Structures](data-structures) + +- [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/) + +## [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/) + +## [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/src/.gitkeep b/src/.gitkeep new file mode 100644 index 0000000..e69de29