diff --git a/CP/DecemberCookOff2017/prob1.py b/CP/DecemberCookOff2017/prob1.py
new file mode 100644
index 0000000..9415ad4
--- /dev/null
+++ b/CP/DecemberCookOff2017/prob1.py
@@ -0,0 +1,23 @@
+for i in xrange(input()):
+ n = input()
+ l = []
+ for i in xrange(n):
+ l.append(raw_input())
+ #print(l)
+ l2 = list(set(l))
+ #print(l2)
+ if len(l2) == 0:
+ print "Draw"
+ continue
+ if len(l2) == 1:
+ print l2[0]
+ continue
+ c1 = l.count(l2[0])
+ c2 = l.count(l2[1])
+ if c1!=c2:
+ if c1 > c2:
+ print l2[0]
+ else:
+ print l2[1]
+ else:
+ print "Draw"
diff --git a/CP/January Challenge 2018/root.cpp b/CP/January Challenge 2018/root.cpp
new file mode 100644
index 0000000..e69de29
diff --git a/misc/algos-master/avl_tree/AvlTree.java b/misc/algos-master/avl_tree/AvlTree.java
deleted file mode 100644
index 6246c1a..0000000
--- a/misc/algos-master/avl_tree/AvlTree.java
+++ /dev/null
@@ -1,277 +0,0 @@
-import java.util.NoSuchElementException;
-import java.util.Random;
-
-public class AvlTree {
-
- public static void main(String[] args) {
- AVL avl = new AVL();
- Random rand = new Random();
- int inp = 10;
- System.out.println(avl.isEmpty());
- for (int i = 0; i < inp; i++) {
- avl.root = avl.insert(avl.root, rand.nextInt(100));
- }
- avl.prntIn(avl.root);
- System.out.println(" ");
- System.out.println(avl.isEmpty());
- avl.delNode(avl.root,avl.root.data);
- avl.prntIn(avl.root);
- System.out.println(" ");
- try {
- avl.delNode(avl.root,1111);
- } catch(NoSuchElementException e) {
- System.out.println("Cannot delete element");
- }
- }
-}
-
-class AVL {
- public NodeAVL root;
-
- public AVL(){
- root = null;
- }
-
- public NodeAVL insert(NodeAVL node, int data) {
- // These method takes care of rotation needed after insertion
- if (node == null) {
- node = new NodeAVL(data);
- return node;
- } else {
- if (node.data > data) {
- node.left = insert(node.left, data);
- if (node.left == null)
- node.hLeft = 0;
- else
- node.hLeft = Math.max(node.left.hLeft, node.left.hRight) + 1;
- } else {
- node.right = insert(node.right, data);
- if (node.right == null)
- node.hRight = 0;
- else
- node.hRight = Math.max(node.right.hLeft, node.right.hRight) + 1;
- }
- node = isRotate(node);
- }
- return node;
- }
-
- private NodeAVL rotateLR(NodeAVL node) {
- NodeAVL sec = node.left;
- NodeAVL temp = sec.right;
- node.left = temp;
- sec.right = temp.left;
- temp.left = sec;
- node.left = temp.right;
- temp.right = node;
- if (node.left == null)
- node.hLeft = 0;
- else
- node.hLeft = Math.max(node.left.hLeft, node.left.hRight) + 1;
- if (sec.right == null)
- sec.hRight = 0;
- else
- sec.hRight = Math.max(sec.right.hLeft, sec.right.hRight) + 1;
- temp.hLeft = Math.max(sec.hLeft, sec.hRight) + 1;
- temp.hRight = Math.max(node.hLeft, node.hRight) + 1;
- return temp;
- }
-
- private NodeAVL rotateRL(NodeAVL node) {
- NodeAVL sec = node.right;
- NodeAVL temp = sec.left;
- node.right = temp;
- sec.left = temp.right;
- temp.right = sec;
- node.right = temp.left;
- temp.left = node;
- if (node.right == null)
- node.hRight = 0;
- else
- node.hRight = Math.max(node.right.hLeft, node.right.hRight) + 1;
- if (sec.left == null)
- sec.hLeft = 0;
- else
- sec.hLeft = Math.max(sec.left.hLeft, sec.left.hRight) + 1;
- temp.hRight = Math.max(sec.hLeft, sec.hRight) + 1;
- temp.hLeft = Math.max(node.hLeft, node.hRight) + 1;
- return temp;
- }
-
- private NodeAVL rotateLL(NodeAVL node) {
- NodeAVL temp = node.left;
- node.left = temp.right;
- temp.right = node;
- if (node.left == null)
- node.hLeft = 0;
- else
- node.hLeft = Math.max(node.left.hRight, node.left.hLeft) + 1;
- temp.hRight = Math.max(node.hRight, node.hLeft) + 1;
- return temp;
- }
-
- private NodeAVL rotateRR(NodeAVL node) {
- NodeAVL temp = node.right;
- node.right = temp.left;
- temp.left = node;
- if (node.right == null)
- node.hRight = 0;
- else
- node.hRight = Math.max(node.right.hRight, node.right.hLeft) + 1;
- temp.hLeft = Math.max(node.hRight, node.hLeft) + 1;
- return temp;
- }
-
- private NodeAVL isRotate(NodeAVL node) {
- // This Method see if there is nessesity for rotation and if
- // there is need, it'll do suitable rotation
- if (node.hRight - node.hLeft >= 2) {
- if (node.right.hRight - node.right.hLeft >= 1)
- node = rotateRR(node);
- else if (node.right.hRight - node.right.hLeft <= -1)
- node = rotateRL(node);
- } else if (node.hRight - node.hLeft <= -2) {
- if (node.left.hRight - node.left.hLeft <= -1)
- node = rotateLL(node);
- else if (node.left.hRight - node.left.hLeft >= 1)
- node = rotateLR(node);
- }
- return node;
- }
-
- public boolean isEmpty() {
- return root == null;
- }
-
- public void prntIn(NodeAVL node) {
- if (node == null)
- return;
- else if (node.left == null && node.right == null)
- System.out.print(node.data + " ");
- else {
- prntIn(node.left);
- System.out.print(node.data + " ");
- prntIn(node.right);
- }
- }
-
- public void delNode(NodeAVL node, int data) {
- // These is the method to delete node if it exist
- // Otherwise it throws an exception
- NodeAVL root = node;
- if (root == null) {
- throw new NoSuchElementException("AVL Tree is Empty!!!");
- }
- if (root.data == data) {
- NodeAVL temp = root.right;
- if (root.left == null && root.right == null)
- root = null;
- else if (root.left == null)
- root = root.right;
- else if (temp == null)
- root = root.left;
- else {
- int dta = 0;
- if (root.right.left == null) {
- root.right.left = root.left;
- root = root.right;
- } else {
- dta = transverseLeftmost(temp);
- root.data = dta;
- }
- if (root.right == null)
- root.hRight = 0;
- else
- root.hRight = Math.max(root.right.hLeft, root.right.hLeft);
- root = isRotate(root);
- }
- }
- else if (node.right == null && node.left == null) {
- throw new NoSuchElementException("element you wanna delete not exist");
- }
- else if (node.right != null && node.right.data == data) {
- NodeAVL del = node.right;
- if (del.right == null && del.left == null)
- node.right = null;
- else if (del.left == null)
- node.right = del.right;
- else if (del.right == null)
- node.right = del.left;
- else {
- NodeAVL temp = del.right;
- if (temp.left == null)
- node.right = node.right.right;
- else
- del.data = transverseLeftmost(temp);
- del.hRight = Math.max(del.right.hLeft, del.right.hRight);
- }
- } else if (node.left != null && node.left.data == data) {
- NodeAVL del = node.left;
- if (del.right == null && del.left == null)
- node.left = null;
- else if (del.left == null)
- node.left = del.right;
- else if (del.right == null)
- node.left = del.left;
- else {
- NodeAVL temp = del.right;
- if (temp.left == null)
- node.left = node.left.right;
- del.data = transverseLeftmost(temp);
- del.hRight = Math.max(del.right.hLeft, del.right.hRight);
- }
- } else if (node.data > data) {
- delNode(node.left, data);
- if (node.left == null)
- node.hLeft = 0;
- else
- node.hLeft = Math.max(node.left.hLeft, node.left.hRight) + 1;
- } else if (node.data < data) {
- delNode(node.right, data);
- if (node.right == null)
- node.hRight = 0;
- else
- node.hRight = Math.max(node.right.hLeft, node.right.hRight) + 1;
- }
- node = isRotate(node);
- }
-
- private int transverseLeftmost(NodeAVL node) {
- // These method is special method which comes
- // in play when we have to delete a node
- // which have both childeren.
- if (node.left.left == null) {
- int data;
- if (node.left != null)
- data = node.left.data;
- else
- data = node.data;
- node.left = null;
- return data;
- }
- node = node.left;
- int data = transverseLeftmost(node);
- if (node.left == null)
- node.hLeft = 0;
- else
- node.hLeft = Math.max(node.left.hLeft, node.left.hLeft);
- node = isRotate(node);
- return data;
- }
-}
-
-class NodeAVL {
- protected int hLeft;
- protected int hRight;
- public int data;
- public NodeAVL left;
- public NodeAVL right;
-
- public NodeAVL(int data) {
- hLeft = 0;
- hRight = 0;
- this.data = data;
- left = null;
- right = null;
- }
-}
diff --git a/misc/algos-master/binary_search/BinarySearch.cs b/misc/algos-master/binary_search/BinarySearch.cs
deleted file mode 100644
index 99e0822..0000000
--- a/misc/algos-master/binary_search/BinarySearch.cs
+++ /dev/null
@@ -1,41 +0,0 @@
-using System;
-
-public class BinarySearch
-{
- public static void Main()
- {
- int[] data = new int[] {1, 5, 6, 8, 13, 45, 65, 121, 123, 163, 245, 334};
- int target = 123;
- int index = Search(data, target);
- if(index >= 0)
- {
- Console.WriteLine("Index of target: " + index);
- }
- else
- {
- Console.WriteLine("Not found\n");
- }
- }
-
- public static int Search(int[] data, int target)
- {
- int left = 0, right = data.Length;
- while(left <= right)
- {
- int mid = (left + right) / 2;
- if (data[mid] == target)
- {
- return mid;
- }
- if (data[mid] < target)
- {
- left = mid + 1;
- }
- else
- {
- right = mid - 1;
- }
- }
- return -1;
- }
-}
diff --git a/misc/algos-master/binary_search/BinarySearch.java b/misc/algos-master/binary_search/BinarySearch.java
deleted file mode 100644
index 6620f98..0000000
--- a/misc/algos-master/binary_search/BinarySearch.java
+++ /dev/null
@@ -1,49 +0,0 @@
-public class BinarySearch {
-
- /**
- *
Searches searchElement in arr and returns the index where it's found or -1 if not found.
- *
- * The given array must be already sorted otherwise the results are undefined.
- *
- * If there a duplicate elements, there is no guarantee which one will be found.
- *
- * This implementation avoids a possible overflow while calculating the index for the middle element.
- * @see Extra, Extra -
- * Read All About It: Nearly All Binary Searches and Mergesorts are Broken
- *
- * @param arr
- * @param searchElement
- * @return
- */
- public static int binarySearch(int[] arr, int searchElement) {
- int left = 0;
- int right = arr.length - 1;
- while (left <= right) {
- int mid = left + (right - left) / 2; // identical to (left + right) / 2 but avoids overflow
- if (arr[mid] == searchElement) { // Element found
- return mid;
- }
- if (arr[mid] < searchElement) { // Look in right half
- left = mid + 1;
- } else { // Look in left half
- right = mid - 1;
- }
- }
-
- return -1; // Element not found
- }
-
- public static void main(String[] args) {
- int[] arr = new int[] {1, 5, 35, 112, 258, 324};
- int[] searchArr = new int[] {1, 35, 112, 324, 67};
- int pos;
- for (int i = 0; i < searchArr.length; i++) {
- pos = binarySearch(arr, searchArr[i]); //search key and get poistion
- if (pos >= 0) {
- System.out.println(searchArr[i] + "-> found at index : " + pos);
- } else {
- System.out.println(searchArr[i] + "-> not found");
- }
- }
- }
-}
diff --git a/misc/algos-master/binary_search/binarySearch.js b/misc/algos-master/binary_search/binarySearch.js
deleted file mode 100644
index dece598..0000000
--- a/misc/algos-master/binary_search/binarySearch.js
+++ /dev/null
@@ -1,62 +0,0 @@
-function binarySearchIterative (arr, item) {
- /*
- Performs a binary search iteratively
- :param arr: List of elements to search from
- :param item: Element to search for
- :return: returns index if element found else -1
- */
- let begin = 0;
- let end = arr.length - 1;
- while (begin <= end) {
- let mid = Math.floor((begin + end) / 2);
- if (arr[mid] === item) {
- return mid;
- } else if (arr[mid] > item) {
- end = mid - 1;
- } else {
- begin = mid + 1;
- }
- }
- return -1;
-}
-
-function binarySearchRecursive (arr, item, begin, end) {
- /*
- Performs a binary search recursively
- :param arr: List of elements to search from
- :param item: Element to search for
- :param begin: Left limit of array
- :param end: Right limit of array
- :return: returns index if element found else -1
- */
- if (begin <= end) {
- let mid = Math.floor((begin + end) / 2);
- if (arr[mid] === item) {
- return mid;
- } else if (arr[mid] > item) {
- return binarySearchRecursive(arr, item, begin, mid - 1);
- } else {
- return binarySearchRecursive(arr, item, mid + 1, end);
- }
- } else {
- return -1;
- }
-}
-
-function main () {
- let arr = [2, 5, 6, 7, 8, 9, 10];
- let item = 5;
- if (binarySearchIterative(arr, item) === -1) {
- console.log('Element is not found');
- } else {
- console.log('Element is found');
- }
-
- if (binarySearchRecursive(arr, item, 0, arr.length - 1) === -1) {
- console.log('Element is not found');
- } else {
- console.log('Element is found');
- }
-}
-
-main();
diff --git a/misc/algos-master/binary_search/binary_search.go b/misc/algos-master/binary_search/binary_search.go
deleted file mode 100644
index 27d6849..0000000
--- a/misc/algos-master/binary_search/binary_search.go
+++ /dev/null
@@ -1,31 +0,0 @@
-package main
-
-import "fmt"
-
-// BinarySearch perform Binary Search by Iterative Method.
-// Time Complexity : O(log(len(array)))
-func BinarySearch(array []int, target int) int {
- left, right := 0, len(array)-1
- for left <= right {
- mid := (left + right) / 2
- if array[mid] == target {
- return mid
- }
- if array[mid] < target {
- left = mid + 1
- } else {
- right = mid - 1
- }
- }
- return -1
-}
-
-func main() {
- array := []int{1, 5, 35, 112, 258, 324, 456, 512}
- index := BinarySearch(array, 112)
- if index == -1 {
- fmt.Println("Element is not present in array")
- } else {
- fmt.Println("Element is present at index :", index)
- }
-}
diff --git a/misc/algos-master/binary_search_tree/BinarySearchTree.java b/misc/algos-master/binary_search_tree/BinarySearchTree.java
deleted file mode 100644
index 68206eb..0000000
--- a/misc/algos-master/binary_search_tree/BinarySearchTree.java
+++ /dev/null
@@ -1,183 +0,0 @@
-import java.util.NoSuchElementException;
-
-class Node { // Node for Binary Search Tree
- public int data;
- public Node left;
- public Node right;
-
- public Node(int data) { // Initializes node with given data and no chlid
- this.data = data;
- this.left = null;
- this.right = null;
- }
-}
-
-class BST {
- private Node root; // Root of Binary Search Tree
-
- public BST() { // Initializes empty BST
- root = null;
- }
-
- public BST(int data) { // Initializes root of BST
- root = new Node(data);
- }
-
- public void insert(int data) {
- if (root == null) {
- root = new Node(data); // Initialize root with the given data
- return;
- }
- Node newNode = new Node(data); // Create Node for new entry
- Node iterator = root; // Temp Node for iterating from root to leaf
- Node parent = null; // To store the future parent of new node
- while (iterator != null) {
- parent = iterator;
- if (data <= iterator.data) {
- iterator = iterator.left;
- }
- else {
- iterator = iterator.right;
- }
- }
- if (data <= parent.data) {
- parent.left = newNode;
- }
- else {
- parent.right = newNode;
- }
- }
-
- public Node search(int data) { // Returns the Node if element is found else will throw an Exception
- Node iterator = root;
- while (iterator != null) {
- if (iterator.data == data)
- return iterator;
- else if (data <= iterator.data)
- iterator = iterator.left;
- else
- iterator = iterator.right;
- }
- throw new NoSuchElementException("Element is not found in BST");
- }
-
- public boolean delete(int data) { // Finds the parent of the node to be deleted.
- if (root == null) {
- throw new NoSuchElementException("Cannot perform delete operation, BST is empty");
- }
- Node iterator = root;
- Node parent = null;
- while (iterator != null) {
- if (data == iterator.data) {
- return deleteNode(data, parent);
- } else {
- parent = iterator;
- if (data <= iterator.data)
- iterator = iterator.left;
- else
- iterator = iterator.right;
- }
- }
- throw new NoSuchElementException("Delete Unsuccessful! Element was not found in BST");
- }
-
- private boolean deleteNode(int data, Node parent) {
- Node child = null;
- boolean position = false; // Indicates position of child wrt to parent, true is left child, false is right child
- if (data <= parent.data) {
- child = parent.left;
- position = true;
- }
- else
- child = parent.right;
-
- if (child.left == child.right) { // Condition for leaf node
- child = null;
- if (position)
- parent.left = null;
- else
- parent.right = null;
- return true;
- } else if (child.right == null) { // Condition for non-leaf with no right sub-tree
- if (position)
- parent.left = child.left;
- else
- parent.right = child.left;
- child.left = null;
- child = null;
- return true;
- } else if (child.left == null) { // Condition for non-leaf with no left sub-tree
- if (position)
- parent.left = child.right;
- else
- parent.right = child.right;
- child.right = null;
- child = null;
- return true;
- }
- else { // Conditon when Node has both subtree avaliable
- Node iterator = child.right;
- Node parentOfIterator = null;
- while(iterator.left != null) { // Finding the leftmost child of right sub-tree
- parentOfIterator = iterator;
- iterator = iterator.left;
- }
- child.data = iterator.data;
- parentOfIterator.left = null;
- iterator = null;
- return true;
- }
- }
-
- public void printInOrder() { // Function to call inorder printing using root
- if (root == null)
- throw new NoSuchElementException("Cannot print! BST is empty");
- print(root);
- System.out.println("");
- }
-
- private void print(Node iterator) {
- if (iterator != null) {
- print(iterator.left);
- System.out.print(iterator.data + " ");
- print(iterator.right);
- }
- }
-}
-
-public class BinarySearchTree {
- public static void main(String[] args) {
- // Created an empty tree
- BST tree = new BST();
- // Adding a few test entries
- tree.insert(10);
- tree.insert(9);
- tree.insert(3);
- tree.insert(12);
- tree.insert(14);
- tree.insert(7);
- tree.insert(6);
- tree.insert(11);
- tree.insert(1);
- tree.insert(2);
- // Test printing
- tree.printInOrder();
- // Deleting a valid node
- tree.delete(9);
- // Print again
- tree.printInOrder();
- // Searching an invalid node, same can be tested for delete as both use same logic
- // but with a slight different approach to find the node
- try {
- tree.search(4);
- System.out.println("Node was found successfully.");
- } catch (NoSuchElementException e) {
- System.out.println("Invalid Search");
- }
- try {
- tree.delete(9);
- } catch (NoSuchElementException e) {
- System.out.println("Cannot delete, Node not present.");
- }
- }
-}
diff --git a/misc/algos-master/binary_search_tree/binary_search_tree.go b/misc/algos-master/binary_search_tree/binary_search_tree.go
deleted file mode 100644
index 6f2789d..0000000
--- a/misc/algos-master/binary_search_tree/binary_search_tree.go
+++ /dev/null
@@ -1,203 +0,0 @@
-package main
-
-import "fmt"
-
-type node struct {
- Key int
- Value int
- Left *node
- Right *node
-}
-
-// Insert inserts a key-value pair into the node
-// If the node's key is equal to the given key
-// the node's value will be overwritten, and no
-// new node will be added to the tree
-func (n *node) Insert(key, value int) {
- switch {
- case key == n.Key:
- // if same key, overwrite value
- n.Value = value
- case key < n.Key:
- // if key is lower
- if n.Left == nil {
- // create new left node if no left node exists
- n.Left = &node{Key: key, Value: value}
- } else {
- // otherwise, call insert on left node
- n.Left.Insert(key, value)
- }
- default:
- // if key is higher
- if n.Right == nil {
- // create new right node if no right node exists
- n.Right = &node{Key: key, Value: value}
- } else {
- // otherwise, call insert on right node
- n.Right.Insert(key, value)
- }
- }
-}
-
-// Max returns the max node and its parent
-func (n *node) Max(parent *node) (*node, *node) {
- if n.Right == nil {
- // if node right node is null, this node must be max node.
- return n, parent
- }
- // call Max on right node
- return n.Right.Max(n)
-}
-
-// Replace replaces parent's child with node.
-func (n *node) Replace(parent, replacement *node) {
- if n == parent.Left {
- // if this node is parents left node, replace parent left node with replacement
- parent.Left = replacement
- } else {
- // otherwise replae parents right node
- parent.Right = replacement
- }
-}
-
-// Delete will find the given key and delete the corresponding node
-func (n *node) Delete(key int, node *node) {
- switch {
- case key < n.Key:
- // if key is lower call delete on left node
- if n.Left != nil {
- n.Left.Delete(key, n)
- }
- case key > n.Key:
- // if key is higher call delete on right node
- if n.Right != nil {
- n.Right.Delete(key, n)
- }
- default:
- // if keys are equal
- if n.Left == nil && n.Right == nil {
- // if node has no children, replace node with nil
- n.Replace(node, nil)
- } else if n.Left == nil {
- // if key has no left node, replace node with right node
- n.Replace(node, n.Right)
- } else if n.Right == nil {
- // if key has no right node, replace node with left node
- n.Replace(node, n.Left)
- } else {
- replacement, parent := n.Left.Max(n)
- n.Key = replacement.Key
- n.Value = replacement.Value
- replacement.Delete(replacement.Key, parent)
- }
- }
-}
-
-// BST (Binary Search Tree) struct just contains the root node
-// so client code doesnt have to work with the nodes
-type BST struct {
- root *node
-}
-
-// Insert adds an element to the BST
-// Insertion is O(log n)
-func (bst *BST) Insert(key, value int) {
- if bst.root == nil {
- // if root is nil, i.e. the tree is empty,
- // just assign new node to root
- bst.root = &node{
- Key: key,
- Value: value,
- }
- } else {
- // otherwise call insert on root node
- bst.root.Insert(key, value)
- }
-}
-
-// Search traverses the tree trying to find a node
-// with given key. If successfull, the value of the node
-// will be returned with a true value. Otherwise 0 and false
-// Search is O(log n)
-func (bst *BST) Search(key int) (int, bool) {
- // start at root and traverse tree
- for node := bst.root; node != nil; {
- if key == node.Key {
- // if keys are equal: success
- return node.Value, true
- }
- if key < node.Key {
- // if key is lower, continue loop with left node
- node = node.Left
- } else {
- // if key is higher, continue loop with right node
- node = node.Right
- }
- }
- return 0, false
-}
-
-// Delete removes a node in the tree with the corresponding key
-func (bst *BST) Delete(key int) {
- if bst.root != nil {
- // create fake parent node
- parent := &node{Right: bst.root}
- // call delete on root node
- bst.root.Delete(key, parent)
- }
-}
-
-// Traverse traverses the tree in order (https://en.wikipedia.org/wiki/Tree_traversal#In-order)
-// and calls the supplied function for each node
-func (bst *BST) Traverse(f func(key, value int)) {
- // call helper function on root
- traverse(bst.root, f)
-}
-
-// helper for traverse
-func traverse(node *node, f func(key, value int)) {
- if node == nil {
- // stop if given node is nil
- return
- }
- // traverse down left subtree
- traverse(node.Left, f)
- // call function on node
- f(node.Key, node.Value)
- // traversen down right subtree
- traverse(node.Right, f)
-}
-
-func main() {
- // create empty bst
- var bst BST
- // add some key value pairs
- bst.Insert(8, 9)
- bst.Insert(4, 2)
- bst.Insert(12, 19)
- bst.Insert(2, 8)
- bst.Insert(1, 200)
- bst.Insert(10, 16)
-
- // Print in order. Should print from lowest key to highest
- bst.Traverse(func(key, value int) {
- fmt.Printf("Key: %d, Value: %d\n", key, value)
- })
-
- // Searching for a key. Should return value and whether key was found or not
- searchKey := 12
- value, ok := bst.Search(searchKey)
- if ok {
- fmt.Printf("Key %d was found! It's value is %d\n", searchKey, value)
- }
-
- // Delete a key
- bst.Delete(searchKey)
- // Search for same key again
- _, ok = bst.Search(searchKey)
- if ok {
- fmt.Println("This shouldn't happen, since key should have been deleted")
- } else {
- fmt.Printf("Key %d was not found :)\n", searchKey)
- }
-}
diff --git a/misc/algos-master/breadth_first_search/BreadthFirstSearch.java b/misc/algos-master/breadth_first_search/BreadthFirstSearch.java
deleted file mode 100644
index 5ab9846..0000000
--- a/misc/algos-master/breadth_first_search/BreadthFirstSearch.java
+++ /dev/null
@@ -1,87 +0,0 @@
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Set;
-
-// Generic type BreadthFirstSearch implementation using the queue concept
-// Time Complexity: O(V+E) where V is number of vertices in the graph and E is number of edges
-public class BreadthFirstSearch {
- // HashMap of lists for Adjacency List Representation
- public HashMap> adj = new HashMap>();
-
- //Function to add an edge
- public void addEdges (T source, T destination) {
- if (adj.containsKey(source)) {
- // update the adj-list
- ArrayList list = adj.get(source);
- list.add(destination);
- adj.put(source, list);
- } else {
- // init the adj-list
- ArrayList list = new ArrayList<>();
- list.add(destination);
- adj.put(source, list);
- }
- }
-
- // BreadthFirstSearch search function with return path in a list
- public ArrayList breadthFirstSearch (T source, T destination) {
- ArrayList bfsPath = new ArrayList<>();
- // init the set for node visited
- Set visited = new HashSet<>();
- // init list of queue
- ArrayList queue = new ArrayList<>();
- queue.add(source);
- bfsPath.add(source);
- // mark as visited
- visited.add(source);
- int flag = 0;
- while (! queue.isEmpty()) {
- source = queue.get(0);
- queue.remove(0);
- ArrayList temp = new ArrayList<>();
- if (adj.containsKey(source) && adj.get(source).size() > 0) {
- temp.addAll(adj.get(source));
- }
- for (int i = 0; i < temp.size(); i++) {
- if (! visited.contains(temp.get(i))) {
- bfsPath.add(temp.get(i));
- if (temp.get(i).equals(destination)) {
- flag = 1;
- break;
- }
- queue.add(temp.get(i));
- // mark as visited
- visited.add(temp.get(i));
- }
- }
- // break the while loop
- if (flag == 1) {
- break;
- }
- }
- // target node not found
- if (flag == 0) {
- return null;
- }
- // return the list
- return bfsPath;
- }
-
- public static void main (String[] args) {
- BreadthFirstSearch obj = new BreadthFirstSearch<>();
- obj.addEdges("A", "B");
- obj.addEdges("A", "D");
- obj.addEdges("B", "C");
- obj.addEdges("C", "D");
- ArrayList path = new ArrayList<>();
- // find the path form source and destination
- path = obj.breadthFirstSearch("A", "D");
- // print the path
- if (path != null) {
- System.out.println(path);
- } else {
- System.out.println("Path not found");
- }
- }
-}
diff --git a/misc/algos-master/coin_change_problem/CoinChangeProblem.java b/misc/algos-master/coin_change_problem/CoinChangeProblem.java
deleted file mode 100644
index 1c0e6cf..0000000
--- a/misc/algos-master/coin_change_problem/CoinChangeProblem.java
+++ /dev/null
@@ -1,39 +0,0 @@
-import java.util.Arrays;
-
-public class CoinChangeProblem {
-
- /**
- * Implementation of famous dynamic programming problem
- * that aims to find out the maximum number of ways in
- * which a value can be achieved using some fixed valued
- * coins.
- *
- * In the implementation, the time complexity is O(mn)
- * and extra space required is O(n).
- *
- * @param coins
- * @param n
- * @return
- */
- public static int coinChangeProblem(int[] coins, int value) {
- int[] possibilities = new int[value + 1];
- Arrays.fill(possibilities, 0);
- possibilities[0] = 1;
- // Build the possibilities table in bottom-up manner
- // For all coins,
- // Update array if the current coin is capable of
- // incrementing the possibility
- for (int i = 0; i < coins.length; i++) {
- for (int j = coins[i]; j <= value; j++) {
- possibilities[j] += possibilities[j - coins[i]];
- }
- }
- return possibilities[value];
- }
-
- public static void main(String[] args) {
- int[] coins = {2, 5, 3, 6};
- int value = 10;
- System.out.println(coinChangeProblem(coins, value));
- }
-}
diff --git a/misc/algos-master/coin_change_problem/coinChangeProblem.js b/misc/algos-master/coin_change_problem/coinChangeProblem.js
deleted file mode 100644
index 43bc25e..0000000
--- a/misc/algos-master/coin_change_problem/coinChangeProblem.js
+++ /dev/null
@@ -1,27 +0,0 @@
-function coinChangeProblem (coins, amount) {
- /*
- * Find out maximum number of ways in which a amount can
- * be obtained using fixed value coins.
- * Time Complexity : O((type of coins)*amount)
- * :param coins: Iterable of elements containing value of coins.
- * :param amount: It is value which is to be obtained with coins.
- * :return: returns maximum number of ways amount can be arranged in.
- */
- let possibilities = new Array(amount + 1);
- possibilities.fill(0);
- possibilities[0] = 1;
- for (let i = 0; i < coins.length; i++) {
- for (let j = coins[i]; j <= amount; j++) {
- possibilities[j] += possibilities[j - coins[i]];
- }
- }
- return possibilities[amount];
-}
-
-function main () {
- let coins = [1, 2, 3];
- let amount = 10;
- console.log(coinChangeProblem(coins, amount));
-}
-
-main();
diff --git a/misc/algos-master/coin_change_problem/coin_change_problem.go b/misc/algos-master/coin_change_problem/coin_change_problem.go
deleted file mode 100644
index f3fd807..0000000
--- a/misc/algos-master/coin_change_problem/coin_change_problem.go
+++ /dev/null
@@ -1,23 +0,0 @@
-package main
-
-import "fmt"
-
-// CoinChangeProblem find out maximum number of ways in which a amount can
-// be obtained using fixed value coins.
-// Time Complexity : O((number of type of coins)*amount)
-func CoinChangeProblem(coins []int, amount int) int {
- possibilities := make([]int, amount+1)
- possibilities[0] = 1
- for i := 0; i < len(coins); i++ {
- for j := coins[i]; j <= amount; j++ {
- possibilities[j] += possibilities[j-coins[i]]
- }
- }
- return possibilities[amount]
-}
-
-func main() {
- coins := []int{1, 2, 3}
- amount := 10
- fmt.Println(CoinChangeProblem(coins, amount))
-}
diff --git a/misc/algos-master/counting_sort/CountingSort.cs b/misc/algos-master/counting_sort/CountingSort.cs
deleted file mode 100644
index beda7c4..0000000
--- a/misc/algos-master/counting_sort/CountingSort.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-using System;
-
-public class CountingSort
-{
-
- /**
- * Sorts the array using counting sort
- * Time Complexity: O(n + k) where n is the number of elements in the array and k is the range of input
- * Space Complexity: O(n + k)
- */
- public static int[] DoCountingSort(int[] arr)
- {
- // finding the maximum value in the array
- int maxValue = Int32.MinValue;
- foreach (int num in arr)
- maxValue = Math.Max(maxValue, num);
-
- // counting the frequency of each element in the array
- int[] frequency = new int[maxValue + 1];
- foreach (int num in arr)
- frequency[num]++;
-
- // modifying each element in the frequency array to the total of all the elements before it
- for (int i = 1; i < frequency.Length; i++)
- frequency[i] += frequency[i - 1];
-
- // constructing the sorted array based on the freqency of each element in ascending order
- int[] sortedArr = new int[arr.Length];
- for (int i = 0; i < arr.Length; i++) {
- sortedArr[frequency[arr[i]] - 1] = arr[i];
- frequency[arr[i]]--;
- }
- return sortedArr;
- }
-
- public static void Main()
- {
- int[] arr = new int[] {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
- int[] sortedArr = DoCountingSort(arr);
- foreach (int num in sortedArr)
- Console.WriteLine(num);
- }
-}
diff --git a/misc/algos-master/counting_sort/CountingSort.java b/misc/algos-master/counting_sort/CountingSort.java
deleted file mode 100644
index 5b9cdf3..0000000
--- a/misc/algos-master/counting_sort/CountingSort.java
+++ /dev/null
@@ -1,35 +0,0 @@
-import java.util.Random;
-
-class CountingSort { //Time complexity = O(n)
- private static void countOccurences(int[] a, int[] c) { //Basically counting occurences of particular number and store in its index
- for (int i = 0; i < a.length; i++) //Counting occurence of each number
- c[a[i]]++;
- for(int i = 1; i < c.length; i++) //counting total number of numbers less then or equal to that number
- c[i] = c[i-1] + c[i];
- }
-
- public static int[] countingSort(int[] a, int k) { // For Sorting
- int[] b = new int[a.length]; //b Array stores sorted array
- int[] c = new int[k+1]; //array c count occurences
- countOccurences(a, c);
- for (int i = a.length-1; i >= 0; i--) { //storing number in ascending order in b
- b[c[a[i]]-1] = a[i]; //Stores number to it respective position
- c[a[i]]--; //Decrease c
- }
- return b; //Return sorted array
- }
-
- public static void main(String[] args) {
- int[] A = new int[10000];
- int k = 0;
- Random rand = new Random();
- for (int i = 0; i < A.length; i++) {
- A[i] = rand.nextInt(100);
- if (k < A[i]) //Every number must be between 0 to k
- k = A[i]; //K is max number
- }
- A = countingSort(A, k);
- for (int i = 0; i < A.length; i++)
- System.out.print(A[i] + " ");
- }
-}
diff --git a/misc/algos-master/counting_sort/countingSort.js b/misc/algos-master/counting_sort/countingSort.js
deleted file mode 100644
index 786915a..0000000
--- a/misc/algos-master/counting_sort/countingSort.js
+++ /dev/null
@@ -1,38 +0,0 @@
-/* Following algorithm sorts the input array in ascending order
-* Time complexity is O(n+k)
-* Auxiliary space is O(n+k)
-* n is number of elements and k is the range of input
-* max is the maximum element in array
-*/
-
-function countingSort (arr, max) {
- /*
- :param arr: Array to be sorted
- :param max: Maximum value in array
- :return: Sorted array
- */
- let n = arr.length;
- let count = new Array(max + 1);
- let temp = new Array(n);
- count.fill(0);
- for (let i = 0; i < n; i++) {
- count[arr[i]]++;
- }
- for (let i = 1; i <= max; i++) {
- count[i] += count[i - 1];
- }
- for (let i = 0; i < n; ++i) {
- temp[count[arr[i]] - 1] = arr[i];
- count[arr[i]]--;
- }
- return temp;
-}
-
-function main () {
- let max = 10;
- let arr = [3, 7, 10, 3, 1, 9, 4, 9];
- arr = countingSort(arr, max);
- console.log(arr);
-}
-
-main();
diff --git a/misc/algos-master/counting_sort/counting_sort.go b/misc/algos-master/counting_sort/counting_sort.go
deleted file mode 100644
index 045550a..0000000
--- a/misc/algos-master/counting_sort/counting_sort.go
+++ /dev/null
@@ -1,36 +0,0 @@
-package main
-
-import "fmt"
-
-// CountingSort sorts the input array in ascending order
-// Time complexity is O(z) where z = max(len(data), max(data))
-func CountingSort(data []int) {
- size := len(data)
- temp := make([]int, size)
- max := 0
- for _, elem := range data {
- if elem > max {
- max = elem
- }
- }
- count := make([]int, max+1)
- for _, item := range data {
- count[item]++
- }
- for i := 1; i <= max; i++ {
- count[i] += count[i-1]
- }
- for i := 0; i < size; i++ {
- temp[count[data[i]]-1] = data[i]
- count[data[i]]--
- }
- for i := 0; i < size; i++ {
- data[i] = temp[i]
- }
-}
-
-func main() {
- data := []int{1, 202, 2, 675, 901, 116, 312, 1, 2}
- CountingSort(data)
- fmt.Println(data)
-}
diff --git a/misc/algos-master/depth_first_traversal/DepthFirstTraversal.java b/misc/algos-master/depth_first_traversal/DepthFirstTraversal.java
deleted file mode 100644
index c3bc062..0000000
--- a/misc/algos-master/depth_first_traversal/DepthFirstTraversal.java
+++ /dev/null
@@ -1,57 +0,0 @@
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.Set;
-import java.util.ArrayList;
-
-
-public class DepthFirstTraversal {
-
- // ArrayList for Adjacency List Representation
- public static ArrayList> adj;
-
- // Function to add an edge into the DepthFirstTraversal
- private static void addEdge(int v, int w) {
- adj.get(v).add(w);
- }
-
- // A function used by DFS
- private static void depthFirstTraversal(int v, Set visited) {
- // Mark the current node as visited
- visited.add(v);
- System.out.println(v);
- Iterator i = adj.get(v).listIterator();
- while (i.hasNext()) {
- int n = i.next();
- if (!visited.contains(n)) {
- depthFirstTraversal(n, visited);
- }
- }
- }
-
- public static void dfs(int v) {
- // false by default in java)
- Set visited = new HashSet();
- // Call the recursive helper function to print DFS traversal
- depthFirstTraversal(v, visited);
- }
-
- public static void initEdges(int n) {
- adj = new ArrayList>();
- for (int i = 0; i < n; ++i) {
- adj.add(new LinkedList());
- }
- }
-
- public static void main(String[] args) {
- initEdges(4);
- addEdge(0, 1);
- addEdge(0, 2);
- addEdge(1, 2);
- addEdge(2, 0);
- addEdge(2, 3);
- addEdge(3, 0);
- System.out.println("Depth First Traversal starting from vertex 2");
- dfs(2);
- }
-}
diff --git a/misc/algos-master/dijkstra/Dijkstra.java b/misc/algos-master/dijkstra/Dijkstra.java
deleted file mode 100644
index ea71dbe..0000000
--- a/misc/algos-master/dijkstra/Dijkstra.java
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * Problem Statement: Implementation of Dijkstra Algorithm.
- * Time Complexity: O(|V|^2)
- * Space Complexity: O(|V|) for priority Queue.
- * Matrix representation is used here. Linked List representation would reduce time complexity to O(Elog(V)),
- * if implemented using binary heaps.
- */
-
-import java.util.Comparator;
-import java.util.HashSet;
-import java.util.PriorityQueue;
-import java.util.Set;
-
-public class Dijkstra {
-
- public int[][] graph;
- public Node[] nodes;
-
- public static class Node {
- public Node parent;
- public int cost;
- public int id;
-
- public Node(Node parent, int cost, int id) {
- this.parent = parent;
- this.cost = cost;
- this.id = id;
- }
- }
-
- public Dijkstra() {
- graph = new int[][]{{0, 4, 0, 0, 0, 0, 0, 8, 0},
- {4, 0, 8, 0, 0, 0, 0, 11, 0},
- {0, 8, 0, 7, 0, 4, 0, 0, 2},
- {0, 0, 7, 0, 9, 14, 0, 0, 0},
- {0, 0, 0, 9, 0, 10, 0, 0, 0},
- {0, 0, 4, 14, 10, 0, 2, 0, 0},
- {0, 0, 0, 0, 0, 2, 0, 1, 6},
- {8, 11, 0, 0, 0, 0, 1, 0, 7},
- {0, 0, 2, 0, 0, 0, 6, 7, 0}
- };
- nodes = new Node[graph.length];
- }
-
- public static void main(String[] args) {
-
- Dijkstra dijkstra = new Dijkstra();
- for(int i = 0; i < dijkstra.nodes.length; i++)
- dijkstra.nodes[i] = new Node(null, Integer.MAX_VALUE, i);
- int source = 0;
- int destination = 4;
- dijkstra.shortestPath(source, destination);
- System.out.println("Shortest Distance from " + source + " to " + destination + " is " + dijkstra.nodes[destination].cost);
- Node temp = dijkstra.nodes[destination];
- System.out.println("Path is ");
- while(temp.parent != null) {
- System.out.print(temp.id + " <--- ");
- temp = temp.parent;
- }
- System.out.println(temp.id);
- }
-
- public void shortestPath(int source, int destination) {
- Set visited = new HashSet<>();
- PriorityQueue pQueue = new PriorityQueue<>(new Comparator() {
- @Override
- public int compare(Node o1, Node o2) {
- return o1.cost - o2.cost;
- }
- });
- nodes[source].cost = 0;
- pQueue.add(nodes[source]);
- while(!pQueue.isEmpty()) {
- Node currVertex = pQueue.poll();
- for(int i = 0; i < graph.length; i++) {
- if(graph[currVertex.id][i]!=0 && !visited.contains(nodes[i]) ) {
- if(!pQueue.contains(nodes[i])) {
- nodes[i].cost = currVertex.cost + graph[currVertex.id][i];
- nodes[i].parent = currVertex;
- pQueue.add(nodes[i]);
- }
- else {
- nodes[i].cost = Math.min(nodes[i].cost, currVertex.cost + graph[currVertex.id][i]);
- if(nodes[i].cost == currVertex.cost + graph[currVertex.id][i])
- nodes[i].parent = currVertex;
- }
- }
- }
- visited.add(currVertex);
- }
- }
-}
diff --git a/misc/algos-master/euclidean_gcd/EuclideanGCD.cs b/misc/algos-master/euclidean_gcd/EuclideanGCD.cs
deleted file mode 100644
index 2014bfd..0000000
--- a/misc/algos-master/euclidean_gcd/EuclideanGCD.cs
+++ /dev/null
@@ -1,35 +0,0 @@
-using System;
-
-public class EuclideanGCD
-{
- public static long euclidean_gcd(long a, long b)
- {
- if(a == 0)
- {
- return (b);
- }
- else
- {
- return euclidean_gcd(b % a, a);
- }
- }
-
- public static long euclidean_gcd_iterative(long a, long b)
- {
- while (b != 0)
- {
- long temp = b;
- b = a % b;
- a = temp;
- }
- return a;
- }
-
- public static void Main()
- {
- int a = 9000, b = 145685;
- Console.WriteLine("GCD of " + a + " and " + b + " by recursive is : " + euclidean_gcd(a, b));
- Console.WriteLine("GCD of " + a + " and " + b + " by iterative is : " + euclidean_gcd_iterative(a, b));
- Console.WriteLine("");
- }
-}
diff --git a/misc/algos-master/euclidean_gcd/EuclideanGCD.java b/misc/algos-master/euclidean_gcd/EuclideanGCD.java
deleted file mode 100644
index cc2f455..0000000
--- a/misc/algos-master/euclidean_gcd/EuclideanGCD.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * first --> First number
- * second --> Second number
- * There are two implementations:
- * Recursive(euclideanGCDRecursive) and Non-Recursive(euclideanGCD)
- */
-
-public class EuclideanGCD {
- static int euclideanGCD(int first, int second) {
- while(second != 0) { // Iterate till second becomes zero
- int temp = second; // Temporary variable to hold value of second
- second = first % second;
- first = temp;
- }
- return first; // When second becomes 0, first becomes gcd of both
- }
-
- static int euclideanGCDRecursive(int first, int second) {
- return (second == 0) ? first : euclideanGCDRecursive(second, (first % second));
- // First becomes GCD when second becomes zero
- }
-
- public static void main(String[] args) {
- int first = 25;
- int second = 5;
- int answerIterative = EuclideanGCD.euclideanGCD(first, second);
- int answerRecursive = EuclideanGCD.euclideanGCDRecursive(first, second);
- System.out.printf("GCD of %d and %d is : %d by recursive algo.\n", first,
- second, answerRecursive);
- System.out.printf("GCD of %d and %d is : %d by iterative algo.\n", first,
- second, answerIterative);
- }
-}
diff --git a/misc/algos-master/euclidean_gcd/euclideanGCD.js b/misc/algos-master/euclidean_gcd/euclideanGCD.js
deleted file mode 100644
index c28c1fa..0000000
--- a/misc/algos-master/euclidean_gcd/euclideanGCD.js
+++ /dev/null
@@ -1,37 +0,0 @@
-function euclideanGCDRecursive (first, second) {
- /*
- Calculates GCD of two numbers using Euclidean Recursive Algorithm
- :param first: First number
- :param second: Second number
- :return: GCD of the numbers
- */
- if (second === 0) {
- return first;
- } else {
- return euclideanGCDRecursive(second, (first % second));
- }
-}
-
-function euclideanGCDIterative (first, second) {
- /*
- Calculates GCD of two numbers using Euclidean Iterative Algorithm
- :param first: First number
- :param second: Second number
- :return: GCD of the numbers
- */
- while (second !== 0) {
- let temp = second;
- second = first % second;
- first = temp;
- }
- return first;
-}
-
-function main () {
- let first = 20;
- let second = 30;
- console.log('Recursive GCD for %d and %d is %d', first, second, euclideanGCDRecursive(first, second));
- console.log('Iterative GCD for %d and %d is %d', first, second, euclideanGCDIterative(first, second));
-}
-
-main();
diff --git a/misc/algos-master/euclidean_gcd/euclidean_gcd.go b/misc/algos-master/euclidean_gcd/euclidean_gcd.go
deleted file mode 100644
index 4654f9f..0000000
--- a/misc/algos-master/euclidean_gcd/euclidean_gcd.go
+++ /dev/null
@@ -1,35 +0,0 @@
-package main
-
-import "fmt"
-
-// EuclideanGCD finds GCD of given numbers by iterative method
-// first : first number
-// second : second number
-// Time complexity :O(log min(first,second))
-func EuclideanGCD(first int, second int) int {
- for second != 0 {
- tmp := second
- second = first % second
- first = tmp
- }
- return first
-}
-
-// EuclideanGCDRecursive finds GCD of given numbers by recursion
-// first : first number
-// second : second number
-// Time complexity : O(log min(first,second))
-func EuclideanGCDRecursive(first int, second int) int {
- if second != 0 {
- return EuclideanGCDRecursive(second, (first % second))
- }
- return first
-}
-
-func main() {
- first := 90
- second := 65
- fmt.Println("GCD of numbers is :")
- fmt.Println(EuclideanGCD(first, second))
- fmt.Println(EuclideanGCDRecursive(first, second))
-}
diff --git a/misc/algos-master/radix_sort/RadixSort.java b/misc/algos-master/radix_sort/RadixSort.java
deleted file mode 100644
index 73da19b..0000000
--- a/misc/algos-master/radix_sort/RadixSort.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/**
- * This Java program implements the Radix sort algorithm
- * It's a non-comparative based sorting algorithm, hence its worse case time
- * complexity is O(kn), and space is O(k + n) where k is the bucket size
- */
-
-public class RadixSort {
-
- private static void radixSort(int[] array) {
-
- int m = array[0];
- int ex = 1;
- int n = array.length;
- int[] b = new int[10]; // initial bucket
-
- // loop through the array
- // find the max element
- for(int i = 1; i < n; i++) {
- if(array[i] > m)
- m = array[i];
- }
-
- while(m / ex > 0) {
-
- int[] bucket = new int[10];
-
- for(int i = 0; i < n; i++)
- bucket[(array[i] / ex) % 10]++;
- for(int i = 1; i < 10; i++)
- bucket[i] += bucket[i - 1];
- for(int i = n - 1; i >= 0; i--)
- b[--bucket[(array[i] / ex) % 10]] = array[i];
-
- for(int i = 0; i < n; i++)
- array[i] = b[i];
- ex *= 10;
- }
- }
-
- public static void main(String args[]) {
- int test[] = new int[]{170, 45, 75, 90, 802, 24, 2, 6};
- radixSort(test);
-
- for(int i: test) {
- System.out.print(i + " ");
- }
- }
-}
diff --git a/misc/algos-master/rod_cutting_problem/RodCutting.java b/misc/algos-master/rod_cutting_problem/RodCutting.java
deleted file mode 100644
index b1d4794..0000000
--- a/misc/algos-master/rod_cutting_problem/RodCutting.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
-Problem Statement: Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n.
-Determine the maximum value obtainable by cutting up the rod and selling the pieces.
-
-Time Complexity: O(n^2)
-Space Complexity: O(n)
-*/
-
-public class RodCutting {
-
- public static int cutRod(int[] price) {
- int n = price.length;
- int[] best_price = new int[n+1];
- best_price[0] = 0;
- for (int i = 1; i <= n; i++) {
- int tmax = Integer.MIN_VALUE;
- for (int j = 0; j < i; j++)
- tmax = Math.max(tmax, price[j] + best_price[i-j-1]);
- best_price[i] = tmax;
- }
- return best_price[n];
- }
-
- public static void main(String[] args) {
- int[] price = new int[] {10, 52, 84, 93, 101, 17, 117, 20};
- System.out.println("Maximum Obtainable Value is " + cutRod(price));
- }
-}
diff --git a/misc/algos-master/rod_cutting_problem/rodCuttingProblem.js b/misc/algos-master/rod_cutting_problem/rodCuttingProblem.js
deleted file mode 100644
index 8037538..0000000
--- a/misc/algos-master/rod_cutting_problem/rodCuttingProblem.js
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
-* Problem Statement: Given a rod of length n and an array of prices that contains prices of all pieces of size smaller than n.
-* Determine the maximum value obtainable by cutting up the rod and selling the pieces.
-*/
-
-function rodCuttingProblem (price) {
- /*
- Computes maximum money that can be earned by cutting a rod of length n (Bottom-Up Approach).
- Time Complexity : O(n ^ 2)
- Space Complexity : O(n)
- :param price: Array in which price[i] denotes price of rod of length i.
- :return: returns maximum value obtainable by cutting up the rod and selling the pieces.
- */
- let n = price.length;
- let bestPrice = new Array(n + 1);
- bestPrice.fill(0);
- for (let i = 1; i < bestPrice.length; i++) {
- bestPrice[i] = price[i - 1];
- }
- for (let i = 1; i <= n; i++) {
- let tmax = Number.MIN_SAFE_INTEGER;
- for (let j = 0; j < i; j++) {
- tmax = Math.max(tmax, bestPrice[i - j - 1] + price[j]);
- }
- bestPrice[i] = tmax;
- }
- return bestPrice[n];
-}
-
-function main () {
- let price = [10, 52, 84, 93, 101, 17, 117, 20];
- console.log('Maximum obtainable value is : ' + rodCuttingProblem(price));
-}
-
-main();
diff --git a/misc/algos-master/rod_cutting_problem/rod_cutting.go b/misc/algos-master/rod_cutting_problem/rod_cutting.go
deleted file mode 100644
index f4ee891..0000000
--- a/misc/algos-master/rod_cutting_problem/rod_cutting.go
+++ /dev/null
@@ -1,26 +0,0 @@
-package main
-
-import "fmt"
-
-// RodCutting computes maximum money that can be earned by cutting a rod of length len(price)
-// Time Complexity : O((length^2)
-// Space Complexity : O(length)
-func RodCutting(price []int) int {
- length := len(price)
- optPrice := make([]int, length+1, length+1)
- for i := 1; i <= length; i++ {
- maxim := -1
- for j := 0; j < i; j++ {
- if maxim < price[j]+optPrice[i-j-1] {
- maxim = price[j] + optPrice[i-j-1]
- }
- }
- optPrice[i] = maxim
- }
- return optPrice[length]
-}
-
-func main() {
- price := []int{1, 5, 8, 9, 10, 17, 17, 20, 24, 30}
- fmt.Println(RodCutting(price))
-}
diff --git a/misc/algos-master/shell_sort/ShellSort.cs b/misc/algos-master/shell_sort/ShellSort.cs
deleted file mode 100644
index 114eafa..0000000
--- a/misc/algos-master/shell_sort/ShellSort.cs
+++ /dev/null
@@ -1,46 +0,0 @@
-using System;
-
-public class ShellSort
-{
- public static void Main()
- {
- int[] data = new int[] {1000, 45, -45, 121, 47, 45, 65, 121, -1, 103, 45, 34};
- Console.WriteLine("Data to be sorted:");
- Print(data);
- Sort(data);
- Console.WriteLine("Sorted data:");
- Print(data);
- }
-
- public static void Sort(int[] data)
- {
- for (int i = data.Length / 2; i > 0; i /= 2)
- {
- for (int j = i; j < data.Length; ++j)
- {
- for (int k = j - i; k >= 0; k -= i)
- {
- if (data[k+i] >= data[k])
- {
- break;
- }
- else
- {
- int temp = data[k];
- data[k] = data[k+i];
- data[k+i] = temp;
- }
- }
- }
- }
- }
-
- public static void Print(int[] data)
- {
- foreach(int elem in data)
- {
- Console.Write(elem + " ");
- }
- Console.WriteLine("");
- }
-}
diff --git a/misc/algos-master/shell_sort/ShellSort.java b/misc/algos-master/shell_sort/ShellSort.java
deleted file mode 100644
index dd60796..0000000
--- a/misc/algos-master/shell_sort/ShellSort.java
+++ /dev/null
@@ -1,41 +0,0 @@
-public class ShellSort {
- /**
- * sorting function
- * Worst case time complexity = O(n^2)
- * Best case complexity = O(nlog(n))
- * n is input size
- */
- public static int[] shellSort(int[] data) {
- for (int i = data.length / 2; i > 0; i /= 2) {
- for (int j = i; j < data.length; ++j) {
- for (int k = j - i; k >= 0; k -= i) {
- if (data[k + i] >= data[k]) {
- break;
- } else {
- //swap the value
- int temp = data[k];
- data[k] = data[k + i];
- data[k + i] = temp;
- }
- }
- }
- }
- return data;
- }
-
- // print function
- public static void print(int[] data) {
- for (Integer item : data) {
- System.out.println(item);
- }
- }
-
- public static void main(String[] args) {
- int[] data = {1000, 45, -45, 121, 47, 45, 65, 121, -1, 103, 45, 34};
- System.out.println("Data to be sorted:");
- print(data);
- System.out.println("Sorted data:");
- data = shellSort(data);
- print(data);
- }
-}
diff --git a/misc/algos-master/shell_sort/shellSort.js b/misc/algos-master/shell_sort/shellSort.js
deleted file mode 100644
index 99282fc..0000000
--- a/misc/algos-master/shell_sort/shellSort.js
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Worst case time complexity = O(n^2)
- * Best case complexity = O(nlog(n))
- * @param {Array} data
- * returns sorted data
- */
-function shellSort (data) {
- let temp;
- for (let i = Math.floor(data.length / 2); i > 0; i = Math.floor(i / 2)) {
- for (let j = i; j < data.length; j++) {
- for (let k = j - i; k >= 0; k -= i) {
- if (data[k + i] >= data[k]) {
- break;
- } else {
- temp = data[k];
- data[k] = data[k + i];
- data[k + i] = temp;
- }
- }
- }
- }
- return data;
-}
-
-function main () {
- let data = [1000, 45, -45, 121, 47, 45, 65, 121, -1, 103, 45, 34];
- console.log(shellSort(data));
-}
-
-main();
diff --git a/misc/algos-master/shell_sort/shell_sort.go b/misc/algos-master/shell_sort/shell_sort.go
deleted file mode 100644
index 7e4712e..0000000
--- a/misc/algos-master/shell_sort/shell_sort.go
+++ /dev/null
@@ -1,28 +0,0 @@
-package main
-
-import "fmt"
-
-// ShellSort function returns sorted data
-// Worst case time complexity = O(n^2)
-// Best case complexity = O(nlog(n))
-func ShellSort(data []int) []int {
- for i := len(data) / 2; i > 0; i /= 2 {
- for j := i; j < len(data); j++ {
- for k := j - i; k >= 0; k -= i {
- if data[k+i] >= data[k] {
- break
- } else {
- data[k], data[k+i] = data[k+i], data[k]
- }
- }
- }
- }
- return data
-}
-
-func main() {
- data := []int{1000, 45, -45, 121, 47, 45, 65, 121, -1, 103, 45, 34}
- fmt.Println("Data to be sorted: ", data)
- data = ShellSort(data)
- fmt.Println("Sorted data:", data)
-}
diff --git a/misc/algos-master/sieve_of_eratosthenes/SieveOfEratosthenes.java b/misc/algos-master/sieve_of_eratosthenes/SieveOfEratosthenes.java
deleted file mode 100644
index 9f270c7..0000000
--- a/misc/algos-master/sieve_of_eratosthenes/SieveOfEratosthenes.java
+++ /dev/null
@@ -1,83 +0,0 @@
-import java.util.Arrays;
-
-/**
- * This class represents a Sieve of Eratosthenes. It exposes an isPrime(int) method.
- *
- * When creating a Sieve, you need to specify the max number that you might query.
- *
- * Time complexity for creating the Sieve is O(n * n) but for querying is O(1). Space complexity is O(n)
- *
- * @see Sieve of Eratosthenes
- */
-public class SieveOfEratosthenes {
-
- private boolean[] sieve;
-
- /**
- * Creates a sieve that can be queried for numbers up to maxNumber.
- *
- * @param maxNumber
- */
- public SieveOfEratosthenes(final int maxNumber) {
- initSieve(maxNumber);
- crossMultiplesOfKnownPrimes();
- }
-
- private void initSieve(int maxNumber) {
- this.sieve = new boolean[maxNumber + 1];
- Arrays.fill(sieve, true);
- cross(0);
- cross(1);
- }
-
- /**
- * Iterates the sieve and when it finds a prime in it, it'll cross its multiples, since by definition those numbers are not prime.
- */
- private void crossMultiplesOfKnownPrimes() {
- for (int n = 2; n * n < sieve.length; ++n) {
- if (isPrime(n)) {
- crossMultiplesOf(n);
- }
- }
- }
-
- /**
- * Given prime, crosses all multiples of prime in the sieve
- *
- * @param prime
- */
- private void crossMultiplesOf(final int prime) {
- for (int n = prime * prime; n < sieve.length; n += prime) {
- cross(n);
- }
- }
-
- /**
- * Marks n as a non-prime in the sieve.
- *
- * @param n
- */
- private void cross(final int n) {
- sieve[n] = false;
- }
-
- /**
- * Returns true if n is a prime number, false otherwise.
- *
- * @param n
- * @return
- */
- public boolean isPrime(final int n) {
- return sieve[n];
- }
-
- public static void main(String[] args) {
- int max = 100;
- SieveOfEratosthenes sieve = new SieveOfEratosthenes(max);
- for (int n = 0; n < 100; ++n) {
- if (sieve.isPrime(n)) {
- System.out.println(n);
- }
- }
- }
-}
diff --git a/misc/algos-master/sieve_of_eratosthenes/sieveOfEratosthenes.js b/misc/algos-master/sieve_of_eratosthenes/sieveOfEratosthenes.js
deleted file mode 100644
index 130754c..0000000
--- a/misc/algos-master/sieve_of_eratosthenes/sieveOfEratosthenes.js
+++ /dev/null
@@ -1,31 +0,0 @@
-function sieveOfEratosthenes (n) {
- /*
- * Calculates prime numbers till a number n
- * :param n: Number upto which to calculate primes
- * :return: A boolean list contaning only primes
- */
- let primes = new Array(n + 1);
- primes.fill(true); // set all as true initially
- primes[0] = primes[1] = false; // Handling case for 0 and 1
- let sqrtn = Math.ceil(Math.sqrt(n));
- for (let i = 2; i <= sqrtn; i++) {
- if (primes[i]) {
- for (let j = 2 * i; j <= n; j += i) {
- primes[j] = false;
- }
- }
- }
- return primes;
-}
-
-function main () {
- let n = 319; // number till where we wish to find primes
- let primes = sieveOfEratosthenes(n);
- for (let i = 2; i <= n; i++) {
- if (primes[i]) {
- console.log(i);
- }
- }
-}
-
-main();
diff --git a/misc/algos-master/sieve_of_eratosthenes/sieve_of_eratosthenes.go b/misc/algos-master/sieve_of_eratosthenes/sieve_of_eratosthenes.go
deleted file mode 100644
index 88c2323..0000000
--- a/misc/algos-master/sieve_of_eratosthenes/sieve_of_eratosthenes.go
+++ /dev/null
@@ -1,34 +0,0 @@
-package main
-
-import (
- "fmt"
- "math"
-)
-
-// SieveOfEratosthenes returns bool array primes
-func SieveOfEratosthenes(n int) []bool {
- primes := make([]bool, n+1)
- sqrtOfN := int(math.Floor(math.Sqrt(float64(n))) + 1)
- for j := range primes {
- primes[j] = true
- }
- for i := 2; i <= sqrtOfN; i++ {
- if primes[i] {
- for j := 2 * i; j < n+1; j += i {
- primes[j] = false
- }
- }
- }
- return primes
-}
-
-func main() {
- // Change the value of n to get all primes <= n
- n := 29
- primes := SieveOfEratosthenes(n)
- for i := 2; i <= n; i++ {
- if primes[i] {
- fmt.Println(i)
- }
- }
-}
diff --git a/misc/algos-master/sleep_sort/SleepSort.java b/misc/algos-master/sleep_sort/SleepSort.java
deleted file mode 100644
index 703a8b1..0000000
--- a/misc/algos-master/sleep_sort/SleepSort.java
+++ /dev/null
@@ -1,57 +0,0 @@
-import java.util.Vector;
-
-/**
-* A Java implementation of sleep sort.
-* Time Complexity : O(max(input))
-* (Will work for integers and not real numbers)
-*/
-public class SleepSort {
- private static final int DELAY_CONST = 25;
-
- public static void main(String[] args) {
- int[] data = new int[] { 9, 2, 3, 4, 0 };
- sleepSort(data);
- for (int element : data) {
- System.out.println(element);
- }
- }
-
- private static void sleepSort(int[] data) {
- if (data.length == 0 || data.length == 0)
- return;
- SorterThread[] sorterThreads = new SorterThread[data.length];
- Vector sortedList = new Vector<>();
- for (int i = 0; i < sorterThreads.length; i++) {
- sorterThreads[i] = new SorterThread(data[i], sortedList);
- sorterThreads[i].start();
- }
- while (sortedList.size() != data.length) {
- try {
- Thread.sleep(DELAY_CONST * DELAY_CONST);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- for (int i = 0; i < data.length; i++) {
- data[i] = sortedList.get(i);
- }
- }
-
- private static class SorterThread extends Thread {
- private int sleepTimer;
- private Vector target;
-
- public SorterThread(int sleepTimer, Vector target) {
- this.sleepTimer = sleepTimer * DELAY_CONST;
- this.target = target;
- }
-
- public void run() {
- try {
- Thread.sleep(sleepTimer);
- } catch (Exception e) {
- }
- target.add(sleepTimer / DELAY_CONST);
- }
- }
-}
diff --git a/misc/algos-master/sleep_sort/sleep_sort.go b/misc/algos-master/sleep_sort/sleep_sort.go
deleted file mode 100644
index 5eba6b0..0000000
--- a/misc/algos-master/sleep_sort/sleep_sort.go
+++ /dev/null
@@ -1,31 +0,0 @@
-package main
-
-import (
- "fmt"
- "time"
-)
-
-// SleepSort sorts an array using SleepSort algorithm
-func SleepSort(numbers []int) []int {
- channel := make(chan int, len(numbers))
-
- for _, n := range numbers {
- go func(n int) {
- time.Sleep(time.Duration(n) * time.Second)
- channel <- n
-
- }(n)
- }
-
- // Get the result
- sorted := make([]int, len(numbers))
- for i := 0; i < len(numbers); i++ {
- sorted[i] = <-channel
- }
- return sorted
-}
-
-func main() {
- sorted := SleepSort([]int{2, 3, 0, 4, 1})
- fmt.Println(sorted)
-}
diff --git a/misc/algos-master/stack/Stack.cs b/misc/algos-master/stack/Stack.cs
deleted file mode 100644
index d241a63..0000000
--- a/misc/algos-master/stack/Stack.cs
+++ /dev/null
@@ -1,126 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-
-class MainClass
-{
- public static void Main()
- {
- Stack test = new Stack();
-
- Console.WriteLine("Pushing to the stack.");
- int max_size = 10;
- for (int i = 1; i <= max_size; i++)
- {
- string ele = String.Format("{0} duck", max_size + 1 - i);
- Console.WriteLine("Pushing {0} to the stack", ele);
- test.Push(ele);
- }
-
- Console.WriteLine("Currently in the stack: %n {0}", test.ToString());
-
- Console.WriteLine("Rotating");
- test.Rotate(4, true);
- Console.WriteLine(test.ToString());
-
- test.Rotate(5, false);
- Console.WriteLine(test.ToString());
-
- Console.WriteLine("Popping off the stack.");
- for (int i = 1; i <= max_size; i++)
- {
- string ele = test.Pop();
- Console.WriteLine("The stack had '{0}' in it", ele);
- }
- Console.WriteLine("Stack is empty!");
- }
-}
-
-class Stack
-{
- private LinkedList stack;
-
- // Constructs an empty stack
- public Stack()
- {
- stack = new LinkedList();
- }
-
- // Adds element at the top of the stack
- public void Push(T data)
- {
- stack.AddLast(data);
- }
-
- // Removes the element at the top of the stack
- public T Pop()
- {
- T t = stack.Last();
- stack.RemoveLast();
- return t;
- }
-
- public Boolean isEmpty()
- {
- return !stack.Any();
- }
-
- /*
- * Gets the top n elements and rotates them
- *
- * If left == false then it will move the last element to behind the nth element (from the top)
- *
- * If left == true it will move the nth element(from the top) to the top
- */
- public void Rotate(int n, bool left)
- {
- Stack tmp = new Stack();
- T ele;
- if (left)
- {
- for (int i = 0; i < n; i++)
- {
- tmp.Push(this.Pop());
- }
- ele = tmp.Pop();
- }
- else
- {
- ele = this.Pop();
- for (int i = 0; i < n - 1; i++)
- {
- tmp.Push(this.Pop());
- }
- tmp.Push(ele);
- }
- while(!tmp.isEmpty())
- {
- this.Push(tmp.Pop());
- }
- if(left)
- {
- this.Push(ele);
- }
- }
-
- public override string ToString()
- {
- Stack tmp = new Stack();
- string s = "Stack: ";
- while (!this.isEmpty())
- {
- T ele = this.Pop();
- s += String.Format("{0} | ", ele.ToString());
- tmp.Push(ele);
- }
- while (!tmp.isEmpty())
- {
- this.Push(tmp.Pop());
- }
- return s;
- }
-}
-
diff --git a/misc/algos-master/stack/Stack.java b/misc/algos-master/stack/Stack.java
deleted file mode 100644
index 0e0c7c9..0000000
--- a/misc/algos-master/stack/Stack.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Following implementation of Stack uses LinkedList
- * The last element of LinkedList is considered as the Top of Stack
- * T defines the type of Stack we wish to create
- */
-
-import java.util.LinkedList;
-import java.util.NoSuchElementException;
-
-public class Stack {
- private LinkedList stack;
-
- public Stack() { // Constructor to create empty Stack
- stack = new LinkedList<>();
- }
-
- public void push(T data) { // Add element to Top of Stack
- stack.addLast(data);
- }
-
- public T pop() throws NoSuchElementException { // Remove element from top of Stack
- return stack.removeLast();
- }
-
- public static void main(String[] args) {
- Stack obj = new Stack<>();
- System.out.println("Putting element in the stack.");
- for (int i = 1; i <= 10; i++) {
- obj.push(i);
- System.out.println("Pushed "+i);
- }
- System.out.println("\nPoping elements out of stack.");
- while(true) { // Remove the elements till stack is empty,
- try {
- Integer curr_element = obj.pop();
- System.out.println("Popped " + curr_element);
- }
- catch(NoSuchElementException nsee) {
- System.out.println("Stack is empty now.");
- break;
- }
- }
- }
-}
diff --git a/misc/algos-master/stack/stack.go b/misc/algos-master/stack/stack.go
deleted file mode 100644
index 56f0e1c..0000000
--- a/misc/algos-master/stack/stack.go
+++ /dev/null
@@ -1,39 +0,0 @@
-package main
-
-import (
- "errors"
- "fmt"
-)
-
-// Stack implements stack DS
-type Stack struct {
- list []int
-}
-
-// Push pushes to stack
-func (s *Stack) Push(data int) error {
- s.list = append(s.list, data)
- return nil
-}
-
-// Pop pops from stack
-func (s *Stack) Pop() (int, error) {
- if len(s.list) == 0 {
- return -1, errors.New("pop from empty stack")
- }
- last := s.list[len(s.list)-1]
- s.list = s.list[:len(s.list)-1]
- return last, nil
-}
-
-func main() {
- var s Stack
- s.Push(2)
- s.Push(3)
- s.Push(5)
- last, err := s.Pop()
- for err == nil {
- fmt.Println(last)
- last, err = s.Pop()
- }
-}
diff --git a/misc/algos-master/stack/stack.js b/misc/algos-master/stack/stack.js
deleted file mode 100644
index 98bad5f..0000000
--- a/misc/algos-master/stack/stack.js
+++ /dev/null
@@ -1,37 +0,0 @@
-class Stack {
- constructor (size = 0) {
- this._array = [];
- this._size = size;
- }
-
- push (argument) {
- if (this._size > 0 && this._array.length === this._size) {
- throw new Error('Unable to push to full stack');
- }
- this._array.push(argument);
- }
-
- pop () {
- if (this._array.length === 0) {
- throw new Error('Unable to pop from empty stack');
- }
- return this._array.pop();
- }
-}
-
-function main () {
- let st = new Stack();
- st.push('Hello World!');
- st.push(1223);
- st.push('last one');
- console.log(st.pop());
- console.log(st.pop());
- console.log(st.pop());
- try {
- console.log(st.pop());
- } catch (error) {
- console.log('Error: ' + error.message);
- }
-}
-
-main();
diff --git a/misc/algos-master/trie/Trie.cs b/misc/algos-master/trie/Trie.cs
deleted file mode 100644
index c1b1d90..0000000
--- a/misc/algos-master/trie/Trie.cs
+++ /dev/null
@@ -1,90 +0,0 @@
-using System;
-using System.Collections.Generic;
-
-class TrieNode
-{
- public char c;
- public Dictionary children;
- public bool isWord;
-
- public TrieNode()
- {
- children = new Dictionary();
- }
-
- public TrieNode(char c)
- {
- this.c = c;
- children = new Dictionary();
- }
-}
-
-public class Trie
-{
- private TrieNode root;
-
- public Trie()
- {
- root = new TrieNode();
- }
-
- ///
- /// Inserts a word into the Trie
- /// Time Complexity: O(len(word))
- ///
- /// The word to insert
- public void Insert(String word)
- {
- TrieNode curr = root;
-
- foreach (char c in word)
- {
- if (!curr.children.ContainsKey(c))
- curr.children[c] = new TrieNode(c);
-
- curr = curr.children[c];
- }
-
- curr.isWord = true;
- }
-
- ///
- /// Searches the trie for a word
- /// Time Complexity: O(len(word))
- ///
- /// The word to search for
- /// True if the word was found, false otherwise
- public bool Search(String word)
- {
- TrieNode curr = root;
-
- foreach (char c in word)
- {
- if (!curr.children.ContainsKey(c))
- return false;
-
- curr = curr.children[c];
- }
-
- return curr.isWord;
- }
-
- public static void Main()
- {
- Trie dictionary = new Trie();
- // Input keys words
- dictionary.Insert("the");
- dictionary.Insert("a");
- dictionary.Insert("there");
- dictionary.Insert("answer");
- dictionary.Insert("any");
- dictionary.Insert("by");
- dictionary.Insert("bye");
- dictionary.Insert("their");
- // Search for different keys words
- Console.WriteLine(dictionary.Search("the"));
- Console.WriteLine(dictionary.Search("these"));
- Console.WriteLine(dictionary.Search("thaw"));
- Console.WriteLine(dictionary.Search("their"));
- }
-}
diff --git a/misc/algos-master/trie/trie.go b/misc/algos-master/trie/trie.go
deleted file mode 100644
index d872a65..0000000
--- a/misc/algos-master/trie/trie.go
+++ /dev/null
@@ -1,107 +0,0 @@
-package main
-
-import (
- "fmt"
-)
-
-// AlphabetSize is the size of the alphabet used.
-// All nodes will have an array of pointers to other nodes,
-// and this array will have the size of the alphabet.
-// Setting to a smaller size (in allowed alphabet) will
-// lower the space needed for the trie
-const AlphabetSize int = 256
-
-// inner node of trie
-type node struct {
- value string
- next [AlphabetSize]*node
-}
-
-// Helper methods:
-
-// get traverses the trie byte by byte. returns a pointer
-// to the final node (nil if key does not exist in trie)
-func get(currentNode *node, key []byte, keyIndex int) *node {
- if currentNode == nil {
- return nil
- }
- if keyIndex == len(key) {
- // we've looked at each byte of the key
- // and must be at final node. return it
- return currentNode
- }
- // we still got bytes left in the key.
- // pick the next byte from the key
- c := key[keyIndex]
- // and get the next node at position c
- // also increment keyIndex.
- return get(currentNode.next[c], key, keyIndex+1)
-}
-
-// put returns a pointer to a node (representing a subtrie)
-func put(currentNode *node, key []byte, value string, keyIndex int) *node {
- if currentNode == nil {
- // if given node is nil, create a new node
- currentNode = &node{}
- }
- if keyIndex == len(key) {
- // if we're at the end of the key bytes, set
- // the current node's value to the given value
- // and return it.
- currentNode.value = value
- return currentNode
- }
- // we still got bytes left in the key.
- // pick the next byte from the key
- c := key[keyIndex]
- // Set the next node at position c
- currentNode.next[c] = put(currentNode.next[c], key, value, keyIndex+1)
- return currentNode
-}
-
-// Trie is a wrapper around the the node struct
-type Trie struct {
- root *node
-}
-
-// Get returns the value and whether the key
-// exists in the trie or not. If the key does
-// not exists, the returned string will be the
-// empty string
-func (t *Trie) Get(key string) (string, bool) {
- node := get(t.root, []byte(key), 0)
- if node == nil {
- return "", false
- }
- return node.value, true
-}
-
-// Put inserts a key/value pair into the trie
-func (t *Trie) Put(key, value string) {
- t.root = put(t.root, []byte(key), value, 0)
-}
-
-func main() {
- keyValuePairs := map[string]string{
- "hello": "world",
- "hola": "mundo",
- "hej": "verden",
- "sveika": "pasaule",
- "alofa": "lalolagi",
- }
-
- var trie Trie
-
- for key, value := range keyValuePairs {
- trie.Put(key, value)
- }
-
- for _, key := range []string{"hello", "goodbye", "alofa", "tofa"} {
- value, ok := trie.Get(key)
- if ok {
- fmt.Printf("Key '%s' was in the trie with value '%s'\n", key, value)
- } else {
- fmt.Printf("Key '%s' was not in the trie\n", key)
- }
- }
-}