diff --git a/.editorconfig b/.editorconfig deleted file mode 100644 index 2f59d86..0000000 --- a/.editorconfig +++ /dev/null @@ -1,13 +0,0 @@ -root = true - -[*] -indent_style = space -indent_size = 4 -end_of_line = lf -charset = utf-8 -trim_trailing_whitespace = true -insert_final_newline = true - -[*.yml] -indent_style = space -indent_size = 2 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/.gitignore b/.gitignore deleted file mode 100644 index 6253c15..0000000 --- a/.gitignore +++ /dev/null @@ -1,7 +0,0 @@ -DS_Store -*.o - -/scripts/node_modules -/scripts/yarn.lock -/scripts/package-lock.json -.vscode/ \ No newline at end of file diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index e28aa71..0000000 --- a/.travis.yml +++ /dev/null @@ -1,14 +0,0 @@ -language: node_js -node_js: - - '9' - -before_script: - - npm version - - cd scripts/ - - npm install - -script: - - npm run validate - -notifications: - email: false diff --git a/BinaryTrees-traversals/BinaryTree.java b/BinaryTrees-traversals/BinaryTree.java new file mode 100644 index 0000000..d69b9f1 --- /dev/null +++ b/BinaryTrees-traversals/BinaryTree.java @@ -0,0 +1,58 @@ +/** + * Binary Tree Traversals implementation in Java + * + * @author: {Sudheer Reddy T} + * @github: {tadipatrisudheerreddy} + */ + + +public class BinaryTree { + + public static TreeNode mirrorTree(TreeNode node){ + if(node == null) + return node; + + TreeNode left = mirrorTree(node.left); + TreeNode right = mirrorTree(node.right); + node.left = right; + node.right = left; + + return node; + } + + public static void main(String[] args){ + + TreeNode root = new TreeNode(8); + TreeNode.insert(root, new TreeNode(31)); + TreeNode.insert(root, new TreeNode(45)); + TreeNode.insert(root, new TreeNode(16)); + TreeNode.insert(root, new TreeNode(24)); + TreeNode.insert(root, new TreeNode(19)); + TreeNode.insert(root, new TreeNode(29)); + TreeNode.insert(root, new TreeNode(7)); + + StringBuffer inorderbuf=new StringBuffer(); + StringBuffer preorderbuf=new StringBuffer(); + StringBuffer postorderbuf=new StringBuffer(); + + + TreeTraversal.getInorder(root,inorderbuf); + TreeTraversal.getPreorder(root, preorderbuf); + TreeTraversal.getPostorder(root, postorderbuf); + + System.out.println("Before mirroring,In order tree is: "+inorderbuf); + + BinaryTree.mirrorTree(root); + + StringBuffer inorderbufAfter = new StringBuffer(); + TreeTraversal.getInorder(root, inorderbufAfter); + System.out.println("After mirroring,In order tree is: "+inorderbufAfter); + + System.out.println("Post order traversal:" + postorderbuf); + System.out.println("Pre order traversal:"+ preorderbuf); + + System.out.println("Nodes with no siblings:"); + TreeWithNoSiblings.printOnlyLeaves(root); + + } +} diff --git a/BinaryTrees-traversals/LowestCommonAncestor.java b/BinaryTrees-traversals/LowestCommonAncestor.java new file mode 100644 index 0000000..eb74e5b --- /dev/null +++ b/BinaryTrees-traversals/LowestCommonAncestor.java @@ -0,0 +1,50 @@ +/** + * To find Lowest Common Ancestor for a binary tree implementation in Java + * + * @author: {Sudheer Reddy T} + * @github: {tadipatrisudheerreddy} + */ + +public class LowestCommonAncestor { + + TreeNode root; + + public TreeNode LCA(int p,int q){ + return findLCA(root,p,q); + } + + private TreeNode findLCA(TreeNode root, int p, int q) { + if(root == null) + return null; + if(root.value == p || root.value == q) + return root; + + TreeNode left = findLCA(root.left,p,q); + TreeNode right = findLCA(root.right,p,q); + + if(left!=null && right!=null) + return root; + + return left!=null? left : right; + } + + + + public static void main(String[] args){ + + LowestCommonAncestor lca = new LowestCommonAncestor(); + + TreeNode root = new TreeNode(1); + root.left = new TreeNode(2); + root.right = new TreeNode(3); + root.left.left = new TreeNode(4); + root.left.right = new TreeNode(5); + root.right.left = new TreeNode(6); + root.right.right = new TreeNode(7); + + + System.out.println("Lowest Common Ancestor of (4,5): "+ lca.findLCA(root, 4, 5).value); + System.out.println("Lowest Common Ancestor of (4,6): "+ lca.findLCA(root, 4, 6).value); + System.out.println("Lowest Common Ancestor of (3,4): "+ lca.findLCA(root, 3, 4).value); + } +} diff --git a/BinaryTrees-traversals/SubTree.java b/BinaryTrees-traversals/SubTree.java new file mode 100644 index 0000000..ed8d10d --- /dev/null +++ b/BinaryTrees-traversals/SubTree.java @@ -0,0 +1,64 @@ +/** + * Binary Tree Identical implementation in Java + * + * @author: {Sudheer Reddy T} + * @github: {tadipatrisudheerreddy} + */ +public class SubTree { + + TreeNode root1, root2; + + public boolean isIdentical(TreeNode root1,TreeNode root2){ + + //Since every null tree is also subset of main tree + if(root1==null&&root2==null) + return true; + //Need to check the null condition only once,since we are using recursion at second time it should not be null + if(root1==null&&root2==null) + return false; + + return (root1.value==root2.value)&& (isIdentical(root1.left,root2.left)) + &&((isIdentical(root1.right,root2.right)) ); + } + + public boolean isSubTree(TreeNode p, TreeNode q){ + + //Since every null tree is also subset of main tree + if(q==null) + return true; + + if(p==null) + return false; + + if(isIdentical(p,q)) + return true; + + return isSubTree(p.left,q)||isSubTree(p.right,q); + } + + + public static void main(String[] args) { + + SubTree tree = new SubTree(); + + TreeNode root1 = new TreeNode(26); + root1.right = new TreeNode(3); + root1.right.right = new TreeNode(3); + root1.left = new TreeNode(10); + root1.left.left = new TreeNode(4); + root1.left.left.right = new TreeNode(30); + root1.left.right = new TreeNode(6); + + TreeNode root2 = new TreeNode(10); + root2.right = new TreeNode(6); + root2.left = new TreeNode(4); + root2.left.right = new TreeNode(30); + + if(tree.isSubTree(tree.root1,tree.root2)) + System.out.println("Tree2 is subtree of Tree1"); + else + System.out.println("Tree2 is not a subtree of Tree1"); + + } + +} diff --git a/BinaryTrees-traversals/TreeNode.java b/BinaryTrees-traversals/TreeNode.java new file mode 100644 index 0000000..11ad3a0 --- /dev/null +++ b/BinaryTrees-traversals/TreeNode.java @@ -0,0 +1,40 @@ +/** + * Binary Tree Node implementation in Java + * + * @author: {Sudheer Reddy T} + * @github: {tadipatrisudheerreddy} + */ + +public class TreeNode { + + int value; + TreeNode left; + TreeNode right; + + public TreeNode(int i) { + value = i; + left = right = null; + } + + public static boolean insert(TreeNode root,TreeNode n){ + if(n!=null){ + if(n.value >= root.value){ + if(root.right==null){ + root.right=n; + return true; + } + else + return insert(root.right,n); + } + else if(root.left==null){ + root.left=n; + return true; + } + else + return insert(root.left,n); + } + return false; + + } + +} diff --git a/BinaryTrees-traversals/TreeTraversal.java b/BinaryTrees-traversals/TreeTraversal.java new file mode 100644 index 0000000..9443295 --- /dev/null +++ b/BinaryTrees-traversals/TreeTraversal.java @@ -0,0 +1,33 @@ +/** + * Binary Tree Traversals implementation in Java + * + * @author: {Sudheer Reddy T} + * @github: {tadipatrisudheerreddy} + */ + +public class TreeTraversal { + + public static void getInorder(TreeNode node,StringBuffer buf){ + if(node == null) + return; + getInorder(node.left,buf); + buf.append(" "+node.value); + getInorder(node.right,buf); + } + + public static void getPreorder(TreeNode node,StringBuffer buf){ + if(node==null) + return; + buf.append(" "+node.value); + getPreorder(node.left,buf); + getPreorder(node.right,buf); + } + + public static void getPostorder(TreeNode node,StringBuffer buf){ + if(node==null) + return; + getPostorder(node.left,buf); + getPostorder(node.right,buf); + buf.append(" "+node.value); + } +} diff --git a/BinaryTrees-traversals/TreeWithNoSiblings.java b/BinaryTrees-traversals/TreeWithNoSiblings.java new file mode 100644 index 0000000..d0dffb1 --- /dev/null +++ b/BinaryTrees-traversals/TreeWithNoSiblings.java @@ -0,0 +1,38 @@ +/** + * To find the Tree with no siblings - implementation in Java + * + * @author: {Sudheer Reddy T} + * @github: {tadipatrisudheerreddy} + */ + +public class TreeWithNoSiblings { + public static void printOnlyLeaves(TreeNode node){ + if(node!=null){ + + printOnlyLeaves(node.left); + + if ((node.left==null) && (node.right!=null)) + System.out.println("Node with no sibling in right side is: " + node.right.value); + + if((node.left!=null) && (node.right==null)) + System.out.println("Node with no sibling in left side is: " + node.left.value); + + printOnlyLeaves(node.right); + } + } + + public static void main(String[] args){ + + TreeNode root = new TreeNode(50); + TreeNode.insert(root, new TreeNode(30)); + TreeNode.insert(root, new TreeNode(60)); + TreeNode.insert(root, new TreeNode(22)); + TreeNode.insert(root, new TreeNode(38)); + TreeNode.insert(root, new TreeNode(55)); + TreeNode.insert(root, new TreeNode(34)); + + + TreeWithNoSiblings.printOnlyLeaves(root); + } + +} diff --git a/Hashing/Isograms.java b/Hashing/Isograms.java new file mode 100644 index 0000000..373b7ac --- /dev/null +++ b/Hashing/Isograms.java @@ -0,0 +1,40 @@ +import java.lang.*; +import java.io.*; +class Isogram + { + public static boolean Check(String s){ + HashSeth=new HashSet<>(); + for(int i=0;i= 0; + } + + public int leftChild(int parentindex){ + return items[getLeftChildIndex(parentindex)]; + } + + public int rightChild(int parentindex){ + return items[getRightChildIndex(parentindex)]; + } + + public int parent(int index) + { + return items[getParentIndex(index)]; + } + + public void swap(int indexone,int indextwo){ + int temp = items[indexone]; + items[indexone] = items[indextwo]; + items[indextwo] = temp; + } + + public void add(int item) + { + items[size] = item; + size++; + heapifyUp(); + } + public void isEmpty(String name) + { + if(size == 0) + { + System.out.println(name+"cant poll"); + } + } + + public int poll() + { + isEmpty("its empty"); + + int item = items[0]; + items[0] = items[size-1]; + size--; + + heapifyDown(); + return item; + } + + public void print() + { + for(int i=0;i leftChild(index)) + { + smallerChildIndex = getRightChildIndex(index); + } + + if(items[index] > items[smallerChildIndex]) + { + break; + } + else{ + swap(index,smallerChildIndex); + } + index = smallerChildIndex; + } + } + + + public void heapifyUp() + { + int index = size - 1; + while(hasParent(index) && parent(index) < items[index]){ + swap(getParentIndex(index),index); + index = getParentIndex(index); + } + } + + public static void main(String []args) + { + Scanner ob = new Scanner(System.in); + int n = ob.nextInt(); + Heap myHeap = new MaxHeap(); + for(int i=0;i= 0 && arr[j] > key) { + arr[j + 1] = arr[j]; + j = j - 1; + } + arr[j + 1] = key; + } + } + + /* A utility function to print array of size n */ + static void printArray(int arr[]) { + int n = arr.length; + for (int i = 0; i < n; ++i) + System.out.print(arr[i] + " "); + + System.out.println(); + } + + // Driver method + public static void main(String args[]) { + int arr[] = { 12, 11, 13, 5, 6 }; + + InsertionSort ob = new InsertionSort(); + ob.sort(arr); + + printArray(arr); + } +} diff --git a/sorting/MergeSort.java b/algorithms/sorting/MergeSort.java similarity index 100% rename from sorting/MergeSort.java rename to algorithms/sorting/MergeSort.java diff --git a/algorithms/sorting/QuickSort.java b/algorithms/sorting/QuickSort.java new file mode 100644 index 0000000..542d8b4 --- /dev/null +++ b/algorithms/sorting/QuickSort.java @@ -0,0 +1,98 @@ +/** + * Java implementation of quick sort + * + * @author Tibeyev Timur (timurtibeyev@gmail.com) + */ + +public class QuickSort { + + /** + * Method responsible for sorting array. + * + * @param arr array of elements + * @param left start of the segment to sort + * @param right end of the segment to sort + */ + private void sort(int[] arr, int left, int right) { + if (left >= right) { + return; + } + + int i = left; + int j = right; + + int mid = (i + j) / 2; + // Pivot element + int v = arr[mid]; + + while (i < j) { + // Find element from the left side, which is equal or greater than pivot element + while (arr[i] < v) { + i++; + } + + // Find element from the right side, which is equal or less than pivot element + while (v < arr[j]) { + j--; + } + + // If such elements exist, perform swapping + if (i <= j) { + swap(arr, i, j); + i++; + j--; + } + } + + // Recursively sort left subarray + sort(arr, left, j); + // Recursively sort right subarray + sort(arr, i, right); + } + + /** + * Swaps two elements. + * + * @param arr array of elements + * @param i first index + * @param j second index + */ + private void swap(int[] arr, int i, int j) { + int buf = arr[i]; + arr[i] = arr[j]; + arr[j] = buf; + } + + /** + * Entry point, invokes sorting methods and prints resulting array. + * + * @param arr array to sort + */ + public void run(int[] arr) { + sort(arr, 0, arr.length - 1); + printArray(arr); + } + + /** + * Utility method to print array. + * + * @param arr array to print + */ + private void printArray(int[] arr) { + for (int i : arr) { + System.out.print(i + " "); + } + System.out.println(); + } + + /** + * {@code Main} method. Initializes {@link QuickSort} object and passes simple + * array to sort. + * + * @param args cmd arguments + */ + public static void main(String args[]) { + int arr[] = { 100, 19, 23, 1, 4, 23, 66 }; + new QuickSort().run(arr); + } +} \ No newline at end of file diff --git a/algorithms/sorting/SelectionSort.java b/algorithms/sorting/SelectionSort.java new file mode 100644 index 0000000..4b03964 --- /dev/null +++ b/algorithms/sorting/SelectionSort.java @@ -0,0 +1,29 @@ +/** + * Java implementation of merge sort + * + * @author Dimitris Glynatsis + * @email dim.glynatsis@gmail.com + */ + +public class SelectionSort { + static void selection(int[] a, int left, int right) { + for (int i = left; i < right; i++) { + int min = i; + for (int j = i + 1; j <= right; j++) + if (a[j] < a[min]) + min = j; + int temp = a[i]; + a[i] = a[min]; + a[min] = temp; + } + } + + public static void main(String[] args) { + int[] a = { 5, 4, 6, 1, 3, 8 }; + + SelectionSort s = new SelectionSort(); + s.selection(a, 0, a.length - 1); + for (int i = 0; i < a.length; i++) + System.out.println(a[i]); + } +} \ No newline at end of file diff --git a/algorithms/sorting/ShellSort.java b/algorithms/sorting/ShellSort.java new file mode 100644 index 0000000..ae61e18 --- /dev/null +++ b/algorithms/sorting/ShellSort.java @@ -0,0 +1,36 @@ +/** + * Java implementation of merge sort + * + * @author Dimitris Glynatsis + * @email dim.glynatsis@gmail.com + */ + +public class ShellSort { + + static void shell(int[] a) { + int l = 0, r = a.length - 1, h; + for (h = 0; h <= (r - 1) / 9; h = 3 * h + 1) + ; + for (; h > 0; h /= 3) + for (int i = l + h; i <= r; i++) { + int j = i, v = a[i]; + while (j >= l + h && v < a[j - h]) { + a[j] = a[j - h]; + j -= h; + } + a[j] = v; + } + } + + public static void main(String[] args) { + int[] a = { 5, 6, 4, 9, 13, 3, 7 }; + + ShellSort s = new ShellSort(); + + s.shell(a); + + for (int i = 0; i < a.length; i++) + System.out.println(a[i]); + } + +} \ No newline at end of file diff --git a/bit-manipulation/BooleanBitSet.java b/bit-manipulation/BooleanBitSet.java new file mode 100644 index 0000000..5736822 --- /dev/null +++ b/bit-manipulation/BooleanBitSet.java @@ -0,0 +1,56 @@ + +/** + * BooleanBitSet that encodes bits in longs, thus saving memory compared to a + * boolean[] array. + */ +public class BooleanBitSet { + + final long[] storage; + + public BooleanBitSet(int size) { + storage = new long[(int)Math.ceil(size / 64.0)]; + } + + public void set(int adress, boolean value){ + + // translate adress to holding long + int pos = (int)Math.floor(adress/ 64.0); + long holder = storage[pos]; + int offset = adress % 64; + + if(value){ + holder |= 1 << offset; + } else { + holder &= ~(1 << offset); + } + storage[pos] = holder; + } + + public boolean get(int adress){ + + long holder = storage[(int)Math.floor(adress/ 64.0)]; + int offset = adress % 64; + + return ((holder >> offset) & 1) == 1; + } + + public static void main(String...strings){ + + BooleanBitSet b = new BooleanBitSet(20); + b.set(0, true); + b.set(1, true); + b.set(3, true); + b.set(5, true); + + System.out.println(b.get(0)); + System.out.println(b.get(1)); + System.out.println(b.get(2)); + System.out.println(b.get(3)); + System.out.println(b.get(4)); + System.out.println(b.get(5)); + System.out.println(b.get(6)); + } + + + +} \ No newline at end of file diff --git a/data-structures/BinaryTree.java b/data-structures/BinaryTree.java new file mode 100644 index 0000000..436c047 --- /dev/null +++ b/data-structures/BinaryTree.java @@ -0,0 +1,67 @@ +/* Class containing left and right child of current + node and key value*/ +class Node +{ + int key; + Node left, right; + + public Node(int item) + { + key = item; + left = right = null; + } +} + +// A Java program to make Binary Tree +class BinaryTree +{ + // Root of Binary Tree + Node root; + + // Constructors + BinaryTree(int key) + { + root = new Node(key); + } + + BinaryTree() + { + root = null; + } + + public static void main(String[] args) + { + BinaryTree tree = new BinaryTree(); + + /*create root*/ + tree.root = new Node(1); + + /* following is the tree after above statement + + 1 + / \ + null null */ + + tree.root.left = new Node(2); + tree.root.right = new Node(3); + + /* 2 and 3 become left and right children of 1 + 1 + / \ + 2 3 + / \ / \ + null null null null */ + + + tree.root.left.left = new Node(4); + /* 4 becomes left child of 2 + 1 + / \ + 2 3 + / \ / \ + 4 null null null + / \ + null null + */ + } +} diff --git a/data-structures/LinearSearch.java b/data-structures/LinearSearch.java new file mode 100644 index 0000000..1753500 --- /dev/null +++ b/data-structures/LinearSearch.java @@ -0,0 +1,45 @@ +/* + Program to find a particular key in the array (Linear-search) +*/ + +import java.util.Scanner; + +class LinearSearch{ + public static void main(String args[]){ + Scanner sc = new Scanner(System.in); + System.out.println("How many elements the array have?"); + System.out.print("Answer : "); + try{ + int[] arr = new int[sc.nextInt()]; + System.out.println("Enter elements one by one"); + for(int i = 0 ; i < arr.length; i++){ + System.out.print("Enter arr["+i+"] : "); + arr[i] = sc.nextInt(); + } + System.out.print("Enter the key you want to find : "); + int index = searchForKey(arr, sc.nextInt()); + if(index == -1){ + System.out.println("Sorry! Key is not in the array"); + }else{ + System.out.println("Key found on index -> "+index); + } + }catch(Exception e){ + System.out.println(e); + } + } + + public static int searchForKey(int[] arr, int key){ + /* + This function looks for the key in the array and returns index when key found and -1 if key is not in the array. + */ + for(int i=0; i < arr.length; i++){ + // Searching elements one by one + if(arr[i] == key){ + //returns index if found + return i; + } + } + //if failed to find key return -1 + return -1; + } +} \ No newline at end of file diff --git a/data-structures/TreeMap_Implementation.java b/data-structures/TreeMap_Implementation.java new file mode 100644 index 0000000..5d1c54d --- /dev/null +++ b/data-structures/TreeMap_Implementation.java @@ -0,0 +1,62 @@ +import java.util.Comparator; +import java.util.SortedMap; +import java.util.TreeMap; + +class TreeMap_Implementation { + + + //A TreeMap is a map implementation where they are always sorted based on the natural ordering of the keys, + // or based on a custom Comparator that you can provide at the time of creation of the TreeMap. + + // + public static void main(String[] args) { + // Creating a TreeMap + SortedMap names = new TreeMap<>(); + + + // Adding new key-value pairs to a TreeMap + names.put("Aanchal", "girl"); + names.put("Rahul", "boy"); + names.put("Arjun", "boy"); + names.put("Karen", "girl"); + names.put("Salman", "boy"); + + // Printing the TreeMap (Output will be sorted based on keys) + System.out.println(names); + + System.out.println(((TreeMap) names).firstEntry()); + + System.out.print(((TreeMap) names).lastEntry()); + + + SortedMap names_2 = new TreeMap<>(new Comparator() { + @Override + public int compare(String s1, String s2) { + return s2.compareTo(s1); + } + }); + + // Adding new key-value pairs to a TreeMap + names_2.put("Aanchal", "girl"); + names_2.put("Rahul", "boy"); + names_2.put("Arjun", "boy"); + names_2.put("Karen", "girl"); + names_2.put("Salman", "boy"); + + // Printing the TreeMap (The keys will be sorted based on the supplied comparator in descending order.) + System.out.println(names_2); + + System.out.println(((TreeMap) names_2).firstEntry()); + + System.out.print(((TreeMap) names_2).lastEntry()); + } + + } + + + /* Output: + {Aanchal=girl, Arjun=boy, Karen=girl, Rahul=boy, Salman=boy} + Aanchal=girl + Salman=boy{Salman=boy, Rahul=boy, Karen=girl, Arjun=boy, Aanchal=girl} + Salman=boy + Aanchal=girl*/ diff --git a/dynamic-programming/MatrixChainMultiplication.java b/dynamic-programming/MatrixChainMultiplication.java new file mode 100644 index 0000000..6d43ecc --- /dev/null +++ b/dynamic-programming/MatrixChainMultiplication.java @@ -0,0 +1,45 @@ +// Dynamic Programming Python implementation of Matrix +// Chain Multiplication. +public class MatrixChainMultiplication { +// Matrix Ai has dimension p[i-1] x p[i] for i = 1..n + static int MatrixChainOrder(int p[], int n) { + /* For simplicity of the program, one extra row and one + extra column are allocated in m[][]. 0th row and 0th + column of m[][] are not used */ + int m[][] = new int[n][n]; + + int i, j, k, L, q; + + /* m[i,j] = Minimum number of scalar multiplications needed + to compute the matrix A[i]A[i+1]...A[j] = A[i..j] where + dimension of A[i] is p[i-1] x p[i] */ + + // cost is zero when multiplying one matrix. + for (i = 1; i < n; i++) + m[i][i] = 0; + + // L is chain length. + for (L=2; L distances[sourcenode] + + adjacencymatrix[sourcenode][destinationnode]) + distances[destinationnode] = distances[sourcenode] + + adjacencymatrix[sourcenode][destinationnode]; + } + } + } + } + + for (int sourcenode = 1; sourcenode <= numberofvertices; sourcenode++) + { + for (int destinationnode = 1; destinationnode <= numberofvertices; destinationnode++) + { + if (adjacencymatrix[sourcenode][destinationnode] != MAX_VALUE) + { + if (distances[destinationnode] > distances[sourcenode] + + adjacencymatrix[sourcenode][destinationnode]) + System.out.println("The Graph contains negative egde cycle"); + } + } + } + + for (int vertex = 1; vertex <= numberofvertices; vertex++) + { + System.out.println("distance of source " + source + " to " + + vertex + " is " + distances[vertex]); + } + } + + public static void main(String... arg) + { + int numberofvertices = 0; + int source; + Scanner scanner = new Scanner(System.in); + + System.out.println("Enter the number of vertices"); + numberofvertices = scanner.nextInt(); + + int adjacencymatrix[][] = new int[numberofvertices + 1][numberofvertices + 1]; + System.out.println("Enter the adjacency matrix"); + for (int sourcenode = 1; sourcenode <= numberofvertices; sourcenode++) + { + for (int destinationnode = 1; destinationnode <= numberofvertices; destinationnode++) + { + adjacencymatrix[sourcenode][destinationnode] = scanner.nextInt(); + if (sourcenode == destinationnode) + { + adjacencymatrix[sourcenode][destinationnode] = 0; + continue; + } + if (adjacencymatrix[sourcenode][destinationnode] == 0) + { + adjacencymatrix[sourcenode][destinationnode] = MAX_VALUE; + } + } + } + + System.out.println("Enter the source vertex"); + source = scanner.nextInt(); + + BellmanFord bellmanford = new BellmanFord(numberofvertices); + bellmanford.BellmanFordEvaluation(source, adjacencymatrix); + scanner.close(); + } +} diff --git a/graph-algorithms/DFS.java b/graph-algorithms/DFS.java new file mode 100644 index 0000000..ceefd1f --- /dev/null +++ b/graph-algorithms/DFS.java @@ -0,0 +1,74 @@ +import java.util.InputMismatchException; +import java.util.Scanner; +import java.util.Stack; + +public class DFS +{ + private Stack stack; + + public DFS() + { + stack = new Stack(); + } + + public void dfs(int adjacency_matrix[][], int source) + { + int number_of_nodes = adjacency_matrix[source].length - 1; + + int visited[] = new int[number_of_nodes + 1]; + int element = source; + int i = source; + System.out.print(element + "\t"); + visited[source] = 1; + stack.push(source); + + while (!stack.isEmpty()) + { + element = stack.peek(); + i = element; + while (i <= number_of_nodes) + { + if (adjacency_matrix[element][i] == 1 && visited[i] == 0) + { + stack.push(i); + visited[i] = 1; + element = i; + i = 1; + System.out.print(element + "\t"); + continue; + } + i++; + } + stack.pop(); + } + } + + public static void main(String...arg) + { + int number_of_nodes, source; + Scanner scanner = null; + try + { + System.out.println("Enter the number of nodes in the graph"); + scanner = new Scanner(System.in); + number_of_nodes = scanner.nextInt(); + + int adjacency_matrix[][] = new int[number_of_nodes + 1][number_of_nodes + 1]; + System.out.println("Enter the adjacency matrix"); + for (int i = 1; i <= number_of_nodes; i++) + for (int j = 1; j <= number_of_nodes; j++) + adjacency_matrix[i][j] = scanner.nextInt(); + + System.out.println("Enter the source for the graph"); + source = scanner.nextInt(); + + System.out.println("The DFS Traversal for the graph is given by "); + DFS dfs = new DFS(); + dfs.dfs(adjacency_matrix, source); + }catch(InputMismatchException inputMismatch) + { + System.out.println("Wrong Input format"); + } + scanner.close(); + } +} diff --git a/graph-algorithms/Dijkstra.java b/graph-algorithms/Dijkstra.java new file mode 100644 index 0000000..682fb39 --- /dev/null +++ b/graph-algorithms/Dijkstra.java @@ -0,0 +1,141 @@ +import java.util.HashSet; +import java.util.InputMismatchException; +import java.util.LinkedList; +import java.util.Queue; +import java.util.Scanner; +import java.util.Set; + +public class DijkstraQueue +{ + private int distances[]; + private Queue queue; + private Set settled; + private int number_of_nodes; + private int adjacencyMatrix[][]; + + public DijkstraQueue(int number_of_nodes) + { + this.number_of_nodes = number_of_nodes; + distances = new int[number_of_nodes + 1]; + settled = new HashSet(); + queue = new LinkedList(); + adjacencyMatrix = new int[number_of_nodes + 1][number_of_nodes + 1]; + } + + public void dijkstra_algorithm(int adjacency_matrix[][], int source) + { + int evaluationNode; + for (int i = 1; i <= number_of_nodes; i++) + for (int j = 1; j <= number_of_nodes; j++) + adjacencyMatrix[i][j] = adjacency_matrix[i][j]; + + for (int i = 1; i <= number_of_nodes; i++) + { + distances[i] = Integer.MAX_VALUE; + } + + queue.add(source); + distances[source] = 0; + + while (!queue.isEmpty()) + { + evaluationNode = getNodeWithMinimumDistanceFromQueue(); + settled.add(evaluationNode); + evaluateNeighbours(evaluationNode); + } + } + + private int getNodeWithMinimumDistanceFromQueue() + { + int min ; + int node = 0; + Iterator iterator = queue.iterator(); + node = iterator.next(); + min = distances[node]; + + for (int i = 1; i <= distances.length; i++) + { + if (queue.contains(i)) + { + if (distances[i] <= min) + { + min = distances[i]; + node = i; + } + } + } + queue.remove(node); + return node; + } + + private void evaluateNeighbours(int evaluationNode) + { + int edgeDistance = -1; + int newDistance = -1; + + for (int destinationNode = 1; destinationNode <= number_of_nodes; destinationNode++) + { + if (!settled.contains(destinationNode)) + { + if (adjacencyMatrix[evaluationNode][destinationNode] != Integer.MAX_VALUE) + { + edgeDistance = adjacencyMatrix[evaluationNode][destinationNode]; + newDistance = distances[evaluationNode] + edgeDistance; + if (newDistance < distances[destinationNode]) + { + distances[destinationNode] = newDistance; + } + queue.add(destinationNode); + } + } + } + } + + public static void main(String... arg) + { + int adjacency_matrix[][]; + int number_of_vertices; + int source = 0; + Scanner scan = new Scanner(System.in); + + try + { + System.out.println("Enter the number of vertices"); + number_of_vertices = scan.nextInt(); + adjacency_matrix = new int[number_of_vertices + 1][number_of_vertices + 1]; + + System.out.println("Enter the Weighted Matrix for the graph"); + for (int i = 1; i <= number_of_vertices; i++) + { + for (int j = 1; j <= number_of_vertices; j++) + { + adjacency_matrix[i][j] = scan.nextInt(); + if (i == j) + { + adjacency_matrix[i][j] = 0; + continue; + } + if (adjacency_matrix[i][j] == 0) + { + adjacency_matrix[i][j] = Integer.MAX_VALUE; + } + } + } + + System.out.println("Enter the source "); + source = scan.nextInt(); + DijkstraQueue dijkstrasQueue = new DijkstraQueue(number_of_vertices); + dijkstrasQueue.dijkstra_algorithm(adjacency_matrix, source); + + System.out.println("The Shorted Path to all nodes are "); + for (int i = 1; i <= dijkstrasQueue.distances.length - 1; i++) + { + System.out.println(source + " to " + i + " is " + dijkstrasQueue.distances[i]); + } + } catch (InputMismatchException inputMismatch) + { + System.out.println("Wrong Input Format"); + } + scan.close(); + } +} diff --git a/graph/AStarPathfinding.java b/graph/AStarPathfinding.java new file mode 100644 index 0000000..6960123 --- /dev/null +++ b/graph/AStarPathfinding.java @@ -0,0 +1,219 @@ +import java.util.*; + +/** + * A* Pathfinding algorithm + * + * It searches for shortest path between two graph nodes using + * heuristic estimation of a distance to lower the amount of + * nodes to be visited. + * + * It works well in cases of finding a path between geographical + * objects (like cities or intersections) using connections + * between them (roads). + * + * It minimizes a function: f(x) = g(x) + h(x) where: + * g(x) is computed distance from start to x node + * h(x) is heuristic distance from x node to the target + * f(x) is the total cost of getting from start to goal through x + * + * In this example the heurestic distance is an euclidean distance + * (every node has a cartesian coordinates assigned) + * + * Wiki page about the algorithm: + * https://en.wikipedia.org/wiki/A*_search_algorithm + * + * === + * + * The algorithm is implemented in @see Graph.findShortestPathUsingAStar() + * The rest of the code helps keeping implementation clear. + * + * === + * + * @author Piotr Macha + */ + +final class Graph { + private final Map nodes = new HashMap<>(); + + List findShortestPathUsingAStar(String startName, String goalName) { + Node start = nodes.get(startName); + Node goal = nodes.get(goalName); + + // Nodes already visited + Set closedSet = new HashSet<>(); + + // Nodes already known but not visited, we put start node as first element + Set openSet = new HashSet<>(); + openSet.add(start); + + // Map to rebuild path when we found a route + Map cameFrom = new HashMap<>(); + + // g(x), g-score contains cost to get from start to given node + // We initialize it as 0 for start node and infinite for others + Map gScore = new HashMap<>(); + for (Node node : nodes.values()) { + gScore.put(node, node == start ? Distance.real(0) : Distance.infinite()); + } + + // f(x), f-score is total cost of getting from start to goal thought a specific node + // We initialize it as heuristic distance estimate for start and infinity for others + Map fScore = new HashMap<>(); + for (Node node : nodes.values()) { + fScore.put(node, node == start ? node.euqlideanDistanceTo(goal) : Distance.infinite()); + } + + while (!openSet.isEmpty()) { + // Find a node in open set with the lowest f-score + Node current = openSet.stream().min(Comparator.comparing(fScore::get)).get(); + + if (current == goal) { + // We found the path and now we can reconstruct it using cameFrom map + List path = new ArrayList<>(); + path.add(current); + while (cameFrom.keySet().contains(current)) { + current = cameFrom.get(current); + path.add(current); + } + Collections.reverse(path); + return path; + } + + // Mark node as visited by swapping its set + openSet.remove(current); + closedSet.add(current); + + for (Map.Entry neighborEntry : current.edges.entrySet()) { + Node neighbor = neighborEntry.getKey(); + Distance distance = neighborEntry.getValue(); + + if (closedSet.contains(neighbor)) { + // Ignore neighbor if it was already evaluated + continue; + } + + // Might be a new g-score for current + Distance gScoreMaybe = gScore.get(current).add(distance); + + if (!openSet.contains(neighbor)) { + // We'll evaluate the newly discovered node later + openSet.add(neighbor); + } else if (gScoreMaybe.compareTo(gScore.get(neighbor)) >= 0) { + // Path is worse than already discovered + continue; + } + + // We'll use it later to reconstruct the path + cameFrom.put(neighbor, current); + + // We set f(x) as g(x) + h(x) (heuristic distance) + gScore.put(neighbor, gScoreMaybe); + fScore.put(neighbor, gScoreMaybe.add(neighbor.euqlideanDistanceTo(goal))); + } + } + + throw new RuntimeException("A* reached end without finding a route (unexpected case)"); + } + + Graph add(Node node) { + this.nodes.put(node.name, node); + return this; + } + + Graph edge(String from, String to, double distance) { + Node a = nodes.get(from); + Node b = nodes.get(to); + a.edges.put(b, Distance.real(distance)); + b.edges.put(a, Distance.real(distance)); + return this; + } + + final static class Distance implements Comparable { + private final boolean infinite; + private final double distance; + + private Distance(boolean infinite, double distance) { + this.infinite = infinite; + this.distance = distance; + } + + Distance add(Distance o) { + return new Distance(this.infinite && o.infinite, this.distance + o.distance); + } + + static Distance infinite() { + return new Distance(true, 0); + } + + static Distance real(double distance) { + return new Distance(false, distance); + } + + @Override + public int compareTo(Distance o) { + if (o.infinite && this.infinite || (!o.infinite && !this.infinite && o.distance == this.distance)) { + return 0; + } + + if (o.infinite || (!this.infinite && this.distance < o.distance)) { + return -1; + } + + return 1; + } + } + + final static class Node { + private final String name; + private final double positionX; + private final double positionY; + private final Map edges; + + Node(String name, double positionX, double positionY) { + this.name = name; + this.positionX = positionX; + this.positionY = positionY; + this.edges = new HashMap<>(); + } + + String getName() { + return name; + } + + Distance euqlideanDistanceTo(Node o) { + return Distance.real(Math.sqrt(Math.pow(positionX - o.positionX, 2) + Math.pow(positionY - o.positionY, 2))); + } + } +} + +public class AStarPathfinding { + public static void main(String args[]) { + (new Graph()) + .add(new Graph.Node("A", 1, 4)) + .add(new Graph.Node("B", 1, 3)) + .add(new Graph.Node("C", 2, 3)) + .add(new Graph.Node("D", 3, 4)) + .add(new Graph.Node("E", 1, 2)) + .add(new Graph.Node("F", 3, 2)) + .add(new Graph.Node("G", 2, 1)) + .add(new Graph.Node("H", 1, 0)) + .add(new Graph.Node("I", 0, 2)) + .add(new Graph.Node("J", 0, 0)) + .edge("A", "B", 1.1) + .edge("A", "C", 1.47) + .edge("A", "D", 2.2) + .edge("C", "E", 1.43) + .edge("D", "F", 2.8) + .edge("E", "I", 1.01) + .edge("I", "J", 1.1) + .edge("J", "H", 1.12) + .edge("E", "G", 3.44) + .edge("F", "G", 1.44) + .edge("H", "G", 1.42) + .findShortestPathUsingAStar("A", "H") + .stream() + .map(Graph.Node::getName) + .forEach(name -> System.out.println("Route step: " + name)); + ; + } +} diff --git a/graph/BFS.java b/graph/BFS.java new file mode 100644 index 0000000..e6215c9 --- /dev/null +++ b/graph/BFS.java @@ -0,0 +1,97 @@ + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.Queue; + +/** + * + * @author miqdad + */ + +class Node{ + int value; + int index; // represent index of node + boolean isVisited; + ArrayList neighbor; + + public Node(int index, int value){ + this.index = index; + this.value = value; + this.neighbor = new ArrayList(); + this.isVisited = false; + } + + public void addNeighbor(Node node){ + this.neighbor.add(node); + } +} + +class Graph{ + int totalNode; + Node[] nodes; + + public Graph(int totalNode){ + this.totalNode = totalNode; + nodes = new Node[totalNode]; + for(int i=0; i initQueue = new LinkedList(); + initQueue.add(root); + BFS(initQueue); + } + + public void BFS(Queue queue){ + if(queue.isEmpty()){ // check if there is no neighbor + return; + } + Queue nextQueue = new LinkedList(); + while(!queue.isEmpty()){ + Node node = queue.poll(); // take neighbor + if(!nodes[node.index].isVisited){ // check neighbor node is visited or not by his index + nodes[node.index].isVisited = true; // set visited to true on graph global variable + System.out.print(node.value + " "); // print the node + for(Node n : node.neighbor){ + if(!nodes[n.index].isVisited){ + nextQueue.add(n); // insert every neighbor to nextqueue + } + } + } + } + + BFS(nextQueue); // recursive visiting node + } +} + +public class BFS { + public static void main(String[] args){ + Graph graph = new Graph(10); // 10 nodes in this graph + for(Node n : graph.nodes){ + System.out.printf("Node index %d has value %d\n", n.index, n.value); + } + + graph.addEdge(0, 1); + graph.addEdge(0, 2); + graph.addEdge(0, 3); + graph.addEdge(1, 4); + graph.addEdge(1, 5); + graph.addEdge(2, 6); + graph.addEdge(2, 7); + graph.addEdge(3, 8); + graph.addEdge(3, 9); + graph.addEdge(1, 7); + + graph.initBFS(); + } +} diff --git a/graph/DFS.java b/graph/DFS.java new file mode 100644 index 0000000..4faa384 --- /dev/null +++ b/graph/DFS.java @@ -0,0 +1,89 @@ + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.Queue; + +/** + * + * @author miqdad + */ +class Node { + + int value; + int index; // represent index of node + boolean isVisited; + ArrayList neighbor; + + public Node(int index, int value) { + this.index = index; + this.value = value; + this.neighbor = new ArrayList(); + this.isVisited = false; + } + + public void addNeighbor(Node node) { + this.neighbor.add(node); + } +} + +class Graph { + + int totalNode; + Node[] nodes; + + public Graph(int totalNode) { + this.totalNode = totalNode; + nodes = new Node[totalNode]; + for (int i = 0; i < totalNode; i++) { + int value = (int) (Math.random() * 100); // gives random value to node + nodes[i] = new Node(i, value); + } + } + + public void addEdge(int s, int d) { // index node +// add neighbor each other + nodes[s].addNeighbor(nodes[d]); + nodes[d].addNeighbor(nodes[s]); + } + + public void initDFS() { + Node root = nodes[0]; + DFS(root); + } + + public void DFS(Node node) { + if (!nodes[node.index].isVisited) { + System.out.print(node.value + " "); + node.isVisited = true; + } + for (Node n : node.neighbor) { + if(!n.isVisited){ + DFS(n); + } + } + + } +} + +public class DFS { + public static void main(String[] args){ + Graph graph = new Graph(10); // 10 nodes in this graph + for(Node n : graph.nodes){ + System.out.printf("Node index %d has value %d\n", n.index, n.value); + } + + graph.addEdge(0, 1); + graph.addEdge(0, 2); + graph.addEdge(0, 3); + graph.addEdge(1, 4); + graph.addEdge(1, 5); + graph.addEdge(2, 6); + graph.addEdge(2, 7); + graph.addEdge(3, 8); + graph.addEdge(3, 9); + graph.addEdge(1, 7); + + graph.initDFS(); + System.out.println(""); + } +} diff --git a/greedy-algorithms/HuffmanCoding.java b/greedy-algorithms/HuffmanCoding.java new file mode 100644 index 0000000..e2fa247 --- /dev/null +++ b/greedy-algorithms/HuffmanCoding.java @@ -0,0 +1,125 @@ +import java.util.PriorityQueue; +import java.util.Scanner; +import java.util.Comparator; + +// Implementation of Hoffman Coding algoritms. +class HuffmanNode { + + int data; + char c; + HuffmanNode left; + HuffmanNode right; +} + +// comparator class helps to compare the node +// on the basis of one of its attribute. +// Here we will be compared +// on the basis of data values of the nodes. +class MyComparator implements Comparator { + public int compare(HuffmanNode x, HuffmanNode y) + { + + return x.data - y.data; + } +} + +public class Huffman { + + // recursive function to print the + // huffman-code through the tree traversal. + // Here s is the huffman - code generated. + public static void printCode(HuffmanNode root, String s) + { + + // base case; if the left and right are null + // then its a leaf node and we print + // the code s generated by traversing the tree. + if (root.left == null && root.right == null && Character.isLetter(root.c)) { + // c is the character in the node + System.out.println(root.c + ":" + s); + return; + } + + // if we go to left then add "0" to the code. + // if we go to the right add"1" to the code. + + // recursive calls for left and + // right sub-tree of the generated tree. + printCode(root.left, s + "0"); + printCode(root.right, s + "1"); + } + + // main function + public static void main(String[] args) + { + + Scanner s = new Scanner(System.in); + // number of characters. + int n = 6; + char[] charArray = { 'a', 'b', 'c', 'd', 'e', 'f' }; + int[] charfreq = { 5, 9, 12, 13, 16, 45 }; + + // creating a priority queue q. + // makes a min-priority queue(min-heap). + PriorityQueue q + = new PriorityQueue(n, new MyComparator()); + + for (int i = 0; i < n; i++) { + + // creating a huffman node object + // and adding it to the priority-queue. + HuffmanNode hn = new HuffmanNode(); + + hn.c = charArray[i]; + hn.data = charfreq[i]; + + hn.left = null; + hn.right = null; + + // add functions adds + // the huffman node to the queue. + q.add(hn); + } + + // create a root node + HuffmanNode root = null; + + // Here we will extract the two minimum value + // from the heap each time until + // its size reduces to 1, extract until + // all the nodes are extracted. + while (q.size() > 1) { + + // first min extract. + HuffmanNode x = q.peek(); + q.poll(); + + // second min extarct. + HuffmanNode y = q.peek(); + q.poll(); + + // new node f which is equal + HuffmanNode f = new HuffmanNode(); + + // to the sum of the frequency of the two nodes + // assigning values to the f node. + f.data = x.data + y.data; + f.c = '-'; + + // first extracted node as left child. + f.left = x; + + // second extracted node as the right child. + f.right = y; + + // marking the f node as the root node. + root = f; + + // add this node to the priority-queue. + q.add(f); + } + + // print the codes by traversing the tree + printCode(root, ""); + } +} diff --git a/license b/license index 6f8bf2d..559a12b 100644 --- a/license +++ b/license @@ -1,7 +1,7 @@ MIT License Copyright (c) 2018 All Algorithms and its contributors (allalgorithms.com) -Copyright (c) 2018 Abraham Hernandez (abranhe.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 diff --git a/math/Nth_fibonacci_using_goldenratio.java b/math/Nth_fibonacci_using_goldenratio.java new file mode 100644 index 0000000..1f29c54 --- /dev/null +++ b/math/Nth_fibonacci_using_goldenratio.java @@ -0,0 +1,39 @@ +// Java program to find n-th Fibonacci number +// Adapted from code by Anant Agarwal. +class Nth_fibonacci_using_goldenratio +{ + // Approximate value of golden ratio + static double PHI = 1.6180339; + + // Fibonacci numbers upto n = 5 + static int f[] = { 0, 1, 1, 2, 3, 5 }; + + // Function to find nth + // Fibonacci number + static int fib (int n) + { + // Fibonacci numbers for n < 6 + if (n < 6) + return f[n]; + + // Else start counting from + // 5th term + int t = 5; + int fn = 5; + + while (t < n) { + fn = (int)Math.round(fn * PHI); + t++; + } + + return fn; + } + + public static void main (String[] args) + { + int fibNo; + fibNo = fib(9); //RETURNS 34 + fibNo = fib(8); //RETURNS 21 + fibNo = fib(7); //RETURNS 13 + } +} diff --git a/math/NumberOfDivisorDigits.java b/math/NumberOfDivisorDigits.java new file mode 100644 index 0000000..e69fc1a --- /dev/null +++ b/math/NumberOfDivisorDigits.java @@ -0,0 +1,18 @@ +public class NumberOfDivisorDigits { + + public static int getNumberOfDivisorDigits(final int number) { + int mutatedNumber = number; + int numberOfEvenlyDivides = 0; + + while(mutatedNumber > 0) { + final int digit = mutatedNumber % 10; + mutatedNumber = mutatedNumber / 10; + + if (digit != 0 && number % digit == 0) { + numberOfEvenlyDivides += 1; + } + } + + return numberOfEvenlyDivides; + } +} \ No newline at end of file diff --git a/math/RecursiveFactorial.java b/math/RecursiveFactorial.java new file mode 100644 index 0000000..1b01a54 --- /dev/null +++ b/math/RecursiveFactorial.java @@ -0,0 +1,20 @@ +package testes; +/** + * Java implementation of recursive factorial + * @author @joao-vieira + */ + +public class RecursiveFactorial { + + public int recursiveFactorial(int n) { + if(n <= 1) return 1; + return n * recursiveFactorial(n-1); + } + + public static void main(String[] args) { + // Test + int number = 3; + System.out.println(number + "! = " + new RecursiveFactorial().recursiveFactorial(number)); + } + +} diff --git a/readme.md b/readme.md index 6c00484..dd64172 100644 --- a/readme.md +++ b/readme.md @@ -1,132 +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 +


-

All ▲lgorithms implemented in Java

- - + + + - - -
-
-allalgorithms.com +
- +## See -## Contents +- [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) -You can find the All ▲lgorithms categories at [algorithms.com/categories](https://algorithms.com/categories) - - [Artificial intelligence](#artificial-intelligence) - - [Backtracking](#backtracking) - - [Bit manipulation](#bit-manipulation) - - [Cellular automaton](#cellular-automaton) - - [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) - - [Online challenges](#online-challenges) - - [Randomized algorithms](#randomized-algorithms) - - [Serches](#serches) - - [Selections](#selections) - - [Sorting](#sorting) - - [Strings](#strings) - - [No category](#no-category) +## What is an algorithm? -## Backtracking +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. - - [Crossword Puzzle](backtracking/CrosswordPuzzle.java) +An algorithm should have three important characteristics to be considered valid: -## Ciphers +- **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. - - [Ceasercipher](ciphers/Ceasercipher.java) +## Categories -## Data structures +> Structure of The All ▲lgoritms project - - [Double Linked List Of Integer](data-structures/DoubleLinkedListOfInteger.java) - - [Linked List](data-structures/LinkedList.java) - - [Segment Tree](data-structures/SegmentTree.java) - - [Stack](data-structures/Stack.java) - - [Use Stack](data-structures/UseStack.java) +- [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) -## Dynamic programming +## [Artificial Intelligence](artificial-intelligence) - - [Edist](dynamic-programming/Edist.java) - - [Fibonacci](dynamic-programming/Fibonacci.java) - - [Kadane](dynamic-programming/Kadane.java) - - [Knapsack](dynamic-programming/Knapsack.java) - - [Longest Common Subsequence](dynamic-programming/LongestCommonSubsequence.java) - - [Min Coin Change](dynamic-programming/MinCoinChange.java) - - [Min Edits To Convert Str1 To Str2](dynamic-programming/MinEditsToConvertStr1ToStr2.java) +- [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) -## Graph +## [Backtracking](backtracking) - - [Binary Tree](graph/BinaryTree.java) +- [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) -## Graphs +## [Bit Manipulation](bit-manipulation) - - [Bfs](graphs/Bfs.java) - - [Topological Sort](graphs/TopologicalSort.java) +- [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) -## Math +## [Cellular Automaton](cellular-automaton) - - [Matrix Multiply](math/MatrixMultiply.java) +- [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) -## Searches +## [Computational Geometry](computational-geometry) - - [Binary Search](searches/BinarySearch.java) - - [Interpolation Search](searches/InterpolationSearch.java) - - [Linear Search](searches/LinearSearch.java) +- [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/) -## Sorting +## [Cryptography](cryptography) - - [Bubble Sort](sorting/BubbleSort.java) - - [Counting Sort](sorting/CountingSort.java) - - [Insertion Sort](sorting/InsertionSort.java) - - [Merge Sort](sorting/MergeSort.java) - - [Quick Sort](sorting/QuickSort.java) - - [Selection Sort](sorting/SelectionSort.java) - - [Shell Sort](sorting/ShellSort.java) +- [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) -## License +- [Bag](data-structures/bag/) +- [Hashes](data-structures/hashes/) +- [Linked List](data-structures/linked-list/) +- [List](data-structures/list/) +- [Queue](data-structures/queue/) +- [Stack](data-structures/stack/) +- [Tree](data-structures/tree/) + +## [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) -This work is released under [MIT License][MIT] +## [Greedy Algorithms](greedy-algorithms) -[![MIT IMG][MIT-logo]][MIT] +- [Activity Selection](greedy-algorithms) +- [Dijkstra Shortest Path](greedy-algorithms) +- [Egyptian Fraction](greedy-algorithms) -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. +## [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.

-
- -[MIT]: https://github.com/abranhe/algorithms/blob/master/license -[MIT-logo]: https://cdn.abranhe.com/projects/algorithms/mit-license.png +
\ No newline at end of file diff --git a/scripts/formatter.js b/scripts/formatter.js deleted file mode 100644 index 6929fba..0000000 --- a/scripts/formatter.js +++ /dev/null @@ -1,151 +0,0 @@ -/** - * The All Algorithms C++ Formatter - * - * Author: Carlos Abraham Hernandez - * https://abranhe.com (abraham@abranhe.com) - */ -'use strict'; - -const fs = require('fs'); -const path = require('path'); -const glob = require('glob'); -const chalk = require('chalk'); - -const getFiles = (src, callback) => glob(src + '/**', callback); - -getFiles('../', (err, res) => { - if (err) { - console.log('Error', err); - } - - res.map((file) => { - if (path.extname(file) !== '.java') { - return; - } - }); -}); - -const categories = [ - 'artificial-intelligence', - 'backtracking', - 'bit-manipulation', - 'cellular-automaton', - 'computational-geometry', - 'cryptography', - 'data-structures', - 'divide-and-conquer', - 'dynamic-programming', - 'gaming-theory', - 'graphs', - 'greedy-algorithms', - 'math', - 'networking', - 'numerical-analysis', - 'online-challenges', - 'randomized-algorithms', - 'serches', - 'selections', - 'sorting', - 'strings', - 'no-category', -]; - -const readme = [ - ` - -
-
-
-
-
- -
-
-
-
-
-
- -
-
-

All ▲lgorithms implemented in Java

- - - - - - -
-
-allalgorithms.com -
- - - -## Contents - -You can find the All ▲lgorithms categories at [algorithms.com/categories](https://algorithms.com/categories) -`, -]; - -categories.forEach((category) => { - readme.push(` - [${category.charAt(0).toUpperCase() + category.slice(1).replace(/\-/g, ' ')}](#${category})`); -}); - -getFiles('../', (err, res) => { - let printedCategories = []; - - if (err) { - console.log('Error', err); - } - - res.map((file) => { - if (path.extname(file) !== '.java') { - return; - } - - let algorithmName = path.basename(file).replace('.java', '').replace(/([a-z0-9])([A-Z])/g, '$1 $2'); - let currentCategory = path.parse(file).dir.split(path.sep)[1]; - - if (!printedCategories.includes(currentCategory)) { - printedCategories.push(currentCategory); - readme.push( - `\n## ${currentCategory.charAt(0).toUpperCase() + currentCategory.slice(1).replace(/\-/g, ' ')}\n`, - ); - } - - readme.push( - ` - [${algorithmName.charAt(0).toUpperCase() + algorithmName.slice(1).replace(/\_/g, ' ')}](${file.replace( - '../', - '', - )})`, - ); - }); - - readme.push(` - - -## License - -This work is released under [MIT License][MIT] - -[![MIT IMG][MIT-logo]][MIT] - -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]: https://github.com/abranhe/algorithms/blob/master/license -[MIT-logo]: https://cdn.abranhe.com/projects/algorithms/mit-license.png -`); - - fs.writeFile(`../readme.md`, readme.join('\n'), (err) => { - if (err) throw err; - console.log(chalk.green('The file was succesfully saved!')); - }); -}); diff --git a/scripts/package.json b/scripts/package.json deleted file mode 100644 index bef28da..0000000 --- a/scripts/package.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "name": "scripts", - "version": "1.0.0", - "description": "Maintaining clean the All ▲lgorithms Project", - "main": "formatter.js", - "scripts": { - "validate": "node validate.js", - "format": "node formatter.js" - }, - "license": "MIT", - "private": true, - "dependencies": { - "camelcase": "^5.3.1", - "chalk": "^2.4.2", - "glob": "^7.1.3" - } -} diff --git a/scripts/validate.js b/scripts/validate.js deleted file mode 100644 index cf71f8e..0000000 --- a/scripts/validate.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * validate.js - * - * The All ▲lgorithms validator CLI - * - * Author: Carlos Abraham Hernandez - * https://abranhe.com (abraham@abranhe.com) - */ -'use strict'; - -const glob = require('glob'); -const path = require('path'); -const camelCase = require('camelcase'); -const chalk = require('chalk'); - -const getFiles = (src, callback) => glob(src + '/**', callback); - -getFiles('../', (err, res) => { - if (err) { - console.log('Error', err); - } - - let invalid = false; - - res.map((file) => { - // Accept only valid Java Files - if (path.extname(file) !== '.java') { - return; - } - - if (path.basename(file, '.java') !== camelCase(path.basename(file, '.java'), { pascalCase: true })) { - console.log(`${chalk.red(path.basename(file))} does not follow the correct style.`); - invalid = true; - } else { - console.log(`${chalk.green(path.basename(file))} is ok.`); - } - }); - - if (invalid) { - throw new TypeError(`Expected the All ▲lgorithms structure.`); - } -}); diff --git a/searches/BinarySearchRecursive.java b/searches/BinarySearchRecursive.java new file mode 100644 index 0000000..9faf7b3 --- /dev/null +++ b/searches/BinarySearchRecursive.java @@ -0,0 +1,28 @@ +public class BinarySearchRecursive { + + public static int binarySearch(int[] arr, int toSearch, int start, int end) { + if (end < start) { + return -1; + } + int mid = (start + end) / 2; + if (arr[mid] > toSearch) { + return binarySearch(arr, toSearch, start, mid - 1); + } else if (arr[mid] < toSearch) { + return binarySearch(arr, toSearch, mid + 1, end); + } + return mid; + } + + public static void main(String[] args) { + int[] arr = {1, 5, 6, 7, 8, 11}; + int toSearch = 8; + + int index = binarySearch(arr, toSearch, 0, arr.length); + + if (index == -1) { + System.out.println(toSearch + " not found"); + } else { + System.out.println(toSearch + " found at index " + index); + } + } +} \ No newline at end of file diff --git a/searches/exponential_search.java b/searches/exponential_search.java new file mode 100644 index 0000000..f7571be --- /dev/null +++ b/searches/exponential_search.java @@ -0,0 +1,37 @@ +import java.util.Arrays; + +class Exponential +{ + // Returns position of first occurrence of + // x in array + static int Exponential(int arr[], + int n, int x) + { + // If x is present at firt location itself + if (arr[0] == x) + return 0; + + // Find range for binary search by + // repeated doubling + int i = 1; + while (i < n && arr[i] <= x) + i = i*2; + + // Call binary search for the found range. + return Arrays.binarySearch(arr, i/2, + Math.min(i, n), x); + } + + // Driver code + public static void main(String args[]) + { + int arr[] = {2, 3, 4, 10, 40}; + int x = 10; + int result = Exponential(arr, arr.length, x); + + System.out.println((result < 0) ? + "Element is not present in array" : + "Element is present at index " + + result); + } +} diff --git a/searches/minMaxSearch.java b/searches/minMaxSearch.java new file mode 100644 index 0000000..4892b90 --- /dev/null +++ b/searches/minMaxSearch.java @@ -0,0 +1,53 @@ +public class MinMaxSearch { + + public MinMaxSearch(){ + + } + + + public int[] searchMinMax(int[] in) { + int n = in.length; + int j = 0; + int min; + int max; + int count = 0; + if (n % 2 == 1) { + j = j - 1; + min = in[0]; + max = in[0]; + count = count + 1; + } else if (in[0] < in[1]) { + min = in[0]; + max = in[1]; + count = count + 2; + } else { + min = in[1]; + max = in[0]; + count = count + 2; + } + for (int i = 1; i <= ((n - 1) / 2); i++) { + if (in[j + 2 * i] <= in[j + 2 * i + 1]) { + if (in[j + 2 * i] < min) { + min = in[j + 2 * i]; + } + if (in[j + 2 * i + 1] > max) { + max = in[j + 2 * i + 1]; + } + count = count + 3; + } else { + if (in[j + 2 * i + 1] < min) { + min = in[j + 2 * i + 1]; + } + if (in[j + 2 * i] > max) { + max = in[j + 2 * i]; + } + count = count + 3; + } + } + + int[] MinMaxC = { min, max, count }; + return MinMaxC; + + } + +} diff --git a/sorting/Cyclesort.java b/sorting/Cyclesort.java new file mode 100644 index 0000000..aa2ab87 --- /dev/null +++ b/sorting/Cyclesort.java @@ -0,0 +1,82 @@ +// Java program to impleament cycle sort + +import java.util.*; +import java.lang.*; + +class Cyclesort +{ +// Function sort the array using Cycle sort + public static void cycleSort (int arr[], int n) + { + // count number of memory writes + int writes = 0; + + // traverse array elements and put it to on + // the right place + for (int cycle_start=0; cycle_start<=n-2; cycle_start++) + { + // initialize item as starting point + int item = arr[cycle_start]; + + // Find position where we put the item. We basically + // count all smaller elements on right side of item. + int pos = cycle_start; + for (int i = cycle_start+1; i= 0; i--) + heapify(arr, n, i); + + // Step 2: Extract elements one by one from heap + for (int i=n-1; i>=0; i--) + { + // Step 2.1: Move current root to end + int temp = arr[0]; + arr[0] = arr[i]; + arr[i] = temp; + + // Step 2.2: Call max heapify on the reduced heap + heapify(arr, i, 0); + } + } + /* Method to heapify a subtree rooted with node i which is + + an index in arr[]. + Heap Size = n + */ + void heapify(int arr[], int n, int i) + { + int largest = i; // Initialize largest as root + int l = 2*i + 1; // left = 2*i + 1 + int r = 2*i + 2; // right = 2*i + 2 + + // If left child is larger than root + if (l < n && arr[l] > arr[largest]) + largest = l; + + // If right child is larger than largest so far + if (r < n && arr[r] > arr[largest]) + largest = r; + + // If largest is not root + if (largest != i) + { + int swap = arr[i]; + arr[i] = arr[largest]; + arr[largest] = swap; + + // Recursively heapify the affected sub-tree + heapify(arr, n, largest); + } + } + + /* A utility function to print array of size n */ + static void printArray(int arr[]) + { + int n = arr.length; + for (int i=0; i>{ + public T[] heapSort(T[] M) { + int n = M.length - 1; + for (int i = n / 2; i >= 0; i--) { + heapify(i, n, M); + } + for (int i = n; i > 0; i--) { + T h1 = M[0]; + T h2 = M[i]; + M[i] = h1; + M[0] = h2; + heapify(0, i - 1, M); + } + return M; + } + + public T[] heapify(int i, int r, T[] M) { + T a = M[i]; + int j = 2 * i; + while (j <= r) { + if (j < r && M[j + 1].compareTo(M[j]) < 0) { + j++; + } + if (a.compareTo(M[j]) > 0) { + M[i] = M[j]; + i = j; + j = 2 * i; + + } else { + j = r + 1; + } + } + M[i] = a; + return M; + } + + public void sort(T[] M) { + heapSort(M); + } +} diff --git a/sorting/InsertionSort.java b/sorting/InsertionSort.java index 95a357b..b9d6631 100644 --- a/sorting/InsertionSort.java +++ b/sorting/InsertionSort.java @@ -1,46 +1,27 @@ /** - * Java implementation of insertion sort - * - * @author Andres Langberg - */ +* Generic Insertion Sort +* @author Jan Tabacki +*/ -// Java program for implementation of Insertion Sort -public class InsertionSort { - /* Function to sort array using insertion sort */ - void sort(int arr[]) { - int n = arr.length; - for (int i = 1; i < n; ++i) { - int key = arr[i]; - int j = i - 1; - - /* - * Move elements of arr[0..i-1], that are greater than key, to one position - * ahead of their current position - */ - while (j >= 0 && arr[j] > key) { - arr[j + 1] = arr[j]; - j = j - 1; +public class InsertionSort> { + + /** + * Sort + * @param T[] array of not sorted elements + * @return T[] array of sorted element + */ + public T[] Sort(T[] values) { + if (values.length > 0) { + T value = values[0]; + for (int i = 1; i < values.length; ++i) { + value = values[i]; + int j; + for (j = i - 1; j >= 0 && values[j].compareTo(value) > 0; --j) { + values[j + 1] = values[j]; + } + values[j + 1] = value; } - arr[j + 1] = key; } - } - - /* A utility function to print array of size n */ - static void printArray(int arr[]) { - int n = arr.length; - for (int i = 0; i < n; ++i) - System.out.print(arr[i] + " "); - - System.out.println(); - } - - // Driver method - public static void main(String args[]) { - int arr[] = { 12, 11, 13, 5, 6 }; - - InsertionSort ob = new InsertionSort(); - ob.sort(arr); - - printArray(arr); + return values; } } diff --git a/sorting/MergeSortNonRecursive.java b/sorting/MergeSortNonRecursive.java new file mode 100644 index 0000000..b9aa73b --- /dev/null +++ b/sorting/MergeSortNonRecursive.java @@ -0,0 +1,56 @@ +public class NonRecursiveMergeSort> { + + public T[] MergeSort(T[] M) { + + int length = M.length; + int size = 1; + int p; + while (size < length) { + p = -1; + while (p + size < length) { + int left = p + 1; + int right = left + size - 1; + if (right + size <= length) { + p = right + size; + } else { + p = length; + } + merge(M, left, right, p); + } + size = size * 2; + } + + return M; + + } + + + public T[] merge(T[] M, int left, int right, int p) { + int i = left; + int j = right + 1; + int k = left; + T[] M2 = M.clone(); + for (int n = 0; n < M.length; n++) { + M2[n] = null; + } + while (i <= right && j <= p) { + if (M[i].compareTo(M[j]) <= 0) { + M2[k] = M[i]; + i = i + 1; + } else { + M2[k] = M[j]; + j = j + 1; + } + k = k + 1; + } + for (int h = i; h <= right; h++) { + M[k + (h - i)] = M[h]; + } + for (int h = left; h <= (k - 1); h++) { + M[h] = M2[h]; + } + return M; + + } + +} diff --git a/sorting/MinMaxSearch.java b/sorting/MinMaxSearch.java new file mode 100644 index 0000000..4892b90 --- /dev/null +++ b/sorting/MinMaxSearch.java @@ -0,0 +1,53 @@ +public class MinMaxSearch { + + public MinMaxSearch(){ + + } + + + public int[] searchMinMax(int[] in) { + int n = in.length; + int j = 0; + int min; + int max; + int count = 0; + if (n % 2 == 1) { + j = j - 1; + min = in[0]; + max = in[0]; + count = count + 1; + } else if (in[0] < in[1]) { + min = in[0]; + max = in[1]; + count = count + 2; + } else { + min = in[1]; + max = in[0]; + count = count + 2; + } + for (int i = 1; i <= ((n - 1) / 2); i++) { + if (in[j + 2 * i] <= in[j + 2 * i + 1]) { + if (in[j + 2 * i] < min) { + min = in[j + 2 * i]; + } + if (in[j + 2 * i + 1] > max) { + max = in[j + 2 * i + 1]; + } + count = count + 3; + } else { + if (in[j + 2 * i + 1] < min) { + min = in[j + 2 * i + 1]; + } + if (in[j + 2 * i] > max) { + max = in[j + 2 * i]; + } + count = count + 3; + } + } + + int[] MinMaxC = { min, max, count }; + return MinMaxC; + + } + +} diff --git a/sorting/QuickSort.java b/sorting/QuickSort.java index 542d8b4..6574b38 100644 --- a/sorting/QuickSort.java +++ b/sorting/QuickSort.java @@ -1,98 +1,78 @@ -/** - * Java implementation of quick sort - * - * @author Tibeyev Timur (timurtibeyev@gmail.com) - */ - -public class QuickSort { - - /** - * Method responsible for sorting array. - * - * @param arr array of elements - * @param left start of the segment to sort - * @param right end of the segment to sort - */ - private void sort(int[] arr, int left, int right) { - if (left >= right) { - return; - } - - int i = left; - int j = right; - - int mid = (i + j) / 2; - // Pivot element - int v = arr[mid]; - - while (i < j) { - // Find element from the left side, which is equal or greater than pivot element - while (arr[i] < v) { - i++; - } - - // Find element from the right side, which is equal or less than pivot element - while (v < arr[j]) { - j--; - } - - // If such elements exist, perform swapping - if (i <= j) { - swap(arr, i, j); - i++; - j--; - } - } - - // Recursively sort left subarray - sort(arr, left, j); - // Recursively sort right subarray - sort(arr, i, right); - } - - /** - * Swaps two elements. - * - * @param arr array of elements - * @param i first index - * @param j second index - */ - private void swap(int[] arr, int i, int j) { - int buf = arr[i]; - arr[i] = arr[j]; - arr[j] = buf; - } - - /** - * Entry point, invokes sorting methods and prints resulting array. - * - * @param arr array to sort - */ - public void run(int[] arr) { - sort(arr, 0, arr.length - 1); - printArray(arr); - } - - /** - * Utility method to print array. - * - * @param arr array to print - */ - private void printArray(int[] arr) { - for (int i : arr) { - System.out.print(i + " "); - } - System.out.println(); - } - - /** - * {@code Main} method. Initializes {@link QuickSort} object and passes simple - * array to sort. - * - * @param args cmd arguments - */ - public static void main(String args[]) { - int arr[] = { 100, 19, 23, 1, 4, 23, 66 }; - new QuickSort().run(arr); - } -} \ No newline at end of file +// Java program for implementation of QuickSort +class QuickSort +{ + /* This function takes last element as pivot, + places the pivot element at its correct + position in sorted array, and places all + smaller (smaller than pivot) to left of + pivot and all greater elements to right + of pivot */ + int partition(int arr[], int low, int high) + { + int pivot = arr[high]; + int i = (low-1); // index of smaller element + for (int j=low; j Array to be sorted, + low --> Starting index, + high --> Ending index */ + void sort(int arr[], int low, int high) + { + if (low < high) + { + /* pi is partitioning index, arr[pi] is + now at right place */ + int pi = partition(arr, low, high); + + // Recursively sort elements before + // partition and after partition + sort(arr, low, pi-1); + sort(arr, pi+1, high); + } + } + + /* A utility function to print array of size n */ + static void printArray(int arr[]) + { + int n = arr.length; + for (int i=0; iarray[j])//if i'th element of array is greater than j'th element swap the elements + { + int temp=array[i]; + array[i]=array[j]; + array[j]=temp; + } + } + } + + System.out.println("Array after sorting"); + for(int i=0;i 0; h /= 3) - for (int i = l + h; i <= r; i++) { - int j = i, v = a[i]; - while (j >= l + h && v < a[j - h]) { - a[j] = a[j - h]; - j -= h; - } - a[j] = v; - } - } - - public static void main(String[] args) { - int[] a = { 5, 6, 4, 9, 13, 3, 7 }; - - ShellSort s = new ShellSort(); - - s.shell(a); - - for (int i = 0; i < a.length; i++) - System.out.println(a[i]); - } - -} \ No newline at end of file +class ShellSort +{ + /* An utility function to print array of size n*/ + static void printArray(int arr[]) + { + int n = arr.length; + for (int i=0; i 0; gap /= 2) + { + // Do a gapped insertion sort for this gap size. + // The first gap elements a[0..gap-1] are already + // in gapped order keep adding one more element + // until the entire array is gap sorted + for (int i = gap; i < n; i += 1) + { + // add a[i] to the elements that have been gap + // sorted save a[i] in temp and make a hole at + // position i + int temp = arr[i]; + + // shift earlier gap-sorted elements up until + // the correct location for a[i] is found + int j; + for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) + arr[j] = arr[j - gap]; + + // put temp (the original a[i]) in its correct + // location + arr[j] = temp; + } + } + return 0; + } + + // Driver method + public static void main(String args[]) + { + int arr[] = {12, 34, 54, 2, 3}; + System.out.println("Array before sorting"); + printArray(arr); + + ShellSort ob = new ShellSort(); + ob.sort(arr); + + System.out.println("Array after sorting"); + printArray(arr); + } +} \ No newline at end of file diff --git a/sorting/heapSort.java b/sorting/heapSort.java new file mode 100644 index 0000000..65bbe2f --- /dev/null +++ b/sorting/heapSort.java @@ -0,0 +1,39 @@ +public class HeapSort{ + + public T[] heapSort(T[] M) { + int n = M.length - 1; + for (int i = n / 2; i >= 0; i--) { + heapify(i, n, M); + } + for (int i = n; i > 0; i--) { + T h1 = M[0]; + T h2 = M[i]; + M[i] = h1; + M[0] = h2; + heapify(0, i - 1, M); + } + return M; + } + + public T[] heapify(int i, int r, T[] M) { + T a = M[i]; + int j = 2 * i; + while (j <= r) { + if (j < r && M[j + 1].compareTo(M[j]) > 0) { + j++; + } + if (a.compareTo(M[j]) < 0) { + M[i] = M[j]; + i = j; + j = 2 * i; + + } else { + j = r + 1; + } + } + M[i] = a; + return M; + } + + +} \ No newline at end of file diff --git a/src/.gitkeep b/src/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/strings/LevenshteinDistance.java b/strings/LevenshteinDistance.java new file mode 100644 index 0000000..433efc8 --- /dev/null +++ b/strings/LevenshteinDistance.java @@ -0,0 +1,31 @@ +// Source: https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Java +public class LevenshteinDistance { + private static int minimum(int a, int b, int c) { + return Math.min(Math.min(a, b), c); + } + + + public static int computeLevenshteinDistance(CharSequence lhs, CharSequence rhs) { + int[][] distance = new int[lhs.length() + 1][rhs.length() + 1]; + + for (int i = 0; i <= lhs.length(); i++) + distance[i][0] = i; + for (int j = 1; j <= rhs.length(); j++) + distance[0][j] = j; + + for (int i = 1; i <= lhs.length(); i++) + for (int j = 1; j <= rhs.length(); j++) + distance[i][j] = minimum( + distance[i - 1][j] + 1, + distance[i][j - 1] + 1, + distance[i - 1][j - 1] + ((lhs.charAt(i - 1) == rhs.charAt(j - 1)) ? 0 : 1)); + + return distance[lhs.length()][rhs.length()]; + } + // Driver method to test above + public static void main(String args[]){ + System.out.println("Distance from 'stull' to 'still' is :"+ LevenshteinDistance.computeLevenshteinDistance("stull", "still")); + System.out.println("Distance from 'stull' to 'steal' is :"+ LevenshteinDistance.computeLevenshteinDistance("stull", "steal")); + System.out.println("Distance from 'skill' to 'steal' is :"+ LevenshteinDistance.computeLevenshteinDistance("skill", "steal")); + } +} \ No newline at end of file