From 1e52ba37c31c7af29e2c36e6b93193f052ca9da6 Mon Sep 17 00:00:00 2001 From: Miki Pokryvailo Date: Thu, 28 Sep 2017 14:11:35 -0400 Subject: [PATCH 01/36] Added level order traversal, and more nodes in main method --- data_structures/Trees/TreeTraversal.java | 38 +++++++++++++++++++----- 1 file changed, 31 insertions(+), 7 deletions(-) diff --git a/data_structures/Trees/TreeTraversal.java b/data_structures/Trees/TreeTraversal.java index c4ff92d0..8e73134e 100644 --- a/data_structures/Trees/TreeTraversal.java +++ b/data_structures/Trees/TreeTraversal.java @@ -1,3 +1,5 @@ +import java.util.LinkedList; + /** * * @author Varun Upadhyay (https://github.com/varunu28) @@ -9,19 +11,27 @@ public class TreeTraversal { public static void main(String[] args) { Node tree = new Node(5); tree.insert(3); + tree.insert(2); tree.insert(7); + tree.insert(4); + tree.insert(6); + tree.insert(8); - // Prints 3 5 7 - tree.printInOrder(); - System.out.println(); - - // Prints 5 3 7 + System.out.println("Pre order traversal:"); tree.printPreOrder(); System.out.println(); - // Prints 3 7 5 + System.out.println("In order traversal:"); + tree.printInOrder(); + System.out.println(); + + System.out.println("Post order traversal:"); tree.printPostOrder(); System.out.println(); + + System.out.println("Level order traversal:"); + tree.printLevelOrder(); + System.out.println(); } } @@ -88,5 +98,19 @@ class Node { } System.out.print(data + " "); } -} + public void printLevelOrder() { + LinkedList queue = new LinkedList<>(); + queue.add(this); + while (queue.size() > 0) { + Node head = queue.remove(); + System.out.print(head.data + " "); + if (head.left != null) { + queue.add(head.left); + } + if (head.right != null) { + queue.add(head.right); + } + } + } +} From 22c48e09253e43e499e94324e3baf0d8fddf0c58 Mon Sep 17 00:00:00 2001 From: Michael Rolland Date: Fri, 29 Sep 2017 14:31:26 -0400 Subject: [PATCH 02/36] Create AnyBaseToAnyBase Class for converting a number between any two bases, by going through decimal. --- Conversions/AnyBaseToAnyBase | 87 ++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 Conversions/AnyBaseToAnyBase diff --git a/Conversions/AnyBaseToAnyBase b/Conversions/AnyBaseToAnyBase new file mode 100644 index 00000000..9f3f3704 --- /dev/null +++ b/Conversions/AnyBaseToAnyBase @@ -0,0 +1,87 @@ +import java.util.InputMismatchException; +import java.util.Scanner; + +/** + * Class for converting from any base to any other base, though it's unclear how digits greater than + * 36 would be represented in bases >36. + * + * @author Michael Rolland + * @version 2017.09.29 + * + */ +public class AnyBaseToAnyBase { + + // Driver + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + System.out.print("Enter number: "); + String n = in.nextLine(); + int b1=0,b2=0; + while (true) { + try { + System.out.print("Enter beginning base: "); + b1 = in.nextInt(); + System.out.print("Enter end base: "); + b2 = in.nextInt(); + break; + } catch (InputMismatchException e) { + System.out.println("Invalid input."); + in.next(); + } + } + System.out.println(base2base(n, b1, b2)); + } + + /** + * Method to convert any integer from base b1 to base b2. Works by converting from b1 to decimal, + * then decimal to b2. + * @param n The integer to be converted. + * @param b1 Beginning base. + * @param b2 End base. + * @return n in base b2. + */ + public static String base2base(String n, int b1, int b2) { + // Declare variables: decimal value of n, + // character of base b1, character of base b2, + // and the string that will be returned. + int decimalValue = 0, charB2; + char charB1; + String output=""; + // Go through every character of n + for (int i=0; i9 and store it in charB2 + if (charB1 >= 'A' && charB1 <= 'Z') + charB2 = 10 + (charB1 - 'A'); + // Else, store the integer value in charB2 + else + charB2 = charB1 - '0'; + // Convert the digit to decimal and add it to the + // decimalValue of n + decimalValue = decimalValue * b1 + charB2; + } + + // Converting the decimal value to base b2: + // A number is converted from decimal to another base + // by continuously dividing by the base and recording + // the remainder until the quotient is zero. The number in the + // new base is the remainders, with the last remainder + // being the left-most digit. + + // While the quotient is NOT zero: + while (decimalValue != 0) { + // If the remainder is a digit < 10, simply add it to + // the left side of the new number. + if (decimalValue % b2 < 10) + output = Integer.toString(decimalValue % b2) + output; + // If the remainder is >= 10, add a character with the + // corresponding value to the new number. (A = 10, B = 11, C = 12, ...) + else + output = (char)((decimalValue % b2)+55) + output; + // Divide by the new base again + decimalValue /= b2; + } + return output; + } +} From e7f35ab8dffb7c2efeda42d45a779634c1a6fdb2 Mon Sep 17 00:00:00 2001 From: Manmeet Singh Date: Mon, 2 Oct 2017 00:42:20 +0530 Subject: [PATCH 03/36] Postfix Notation using Stack Note- Give input in the form like "1 21 + 45 13 + *" #96 --- Misc/StackPostfixNotation | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Misc/StackPostfixNotation diff --git a/Misc/StackPostfixNotation b/Misc/StackPostfixNotation new file mode 100644 index 00000000..c04b0ac6 --- /dev/null +++ b/Misc/StackPostfixNotation @@ -0,0 +1,38 @@ +import java.util.*; + +public class Postfix { + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + String post = scanner.nextLine(); // Takes input with spaces in between eg. "1 21 +" + System.out.println(postfixEvaluate(post)); + } + + // Evaluates the given postfix expression string and returns the result. + public static int postfixEvaluate(String exp) { + Stack s = new Stack (); + Scanner tokens = new Scanner(exp); + + while (tokens.hasNext()) { + if (tokens.hasNextInt()) { + s.push(tokens.nextInt()); // If int then push to stack + } else { // else pop top two values and perform the operation + int num2 = s.pop(); + int num1 = s.pop(); + String op = tokens.next(); + + if (op.equals("+")) { + s.push(num1 + num2); + } else if (op.equals("-")) { + s.push(num1 - num2); + } else if (op.equals("*")) { + s.push(num1 * num2); + } else { + s.push(num1 / num2); + } + + // "+", "-", "*", "/" + } + } + return s.pop(); + } +} From ae3342fb50eb5f4a2b973356e8685fb3ac57543a Mon Sep 17 00:00:00 2001 From: Manmeet Singh Date: Tue, 3 Oct 2017 16:51:42 +0530 Subject: [PATCH 04/36] Added Extension --- Misc/{StackPostfixNotation => StackPostfixNotation.java} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Misc/{StackPostfixNotation => StackPostfixNotation.java} (100%) diff --git a/Misc/StackPostfixNotation b/Misc/StackPostfixNotation.java similarity index 100% rename from Misc/StackPostfixNotation rename to Misc/StackPostfixNotation.java From 3f25ae85012d83bec726712c6f0fb2d22cea04f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20M=C3=BCller?= Date: Tue, 3 Oct 2017 18:26:07 +0200 Subject: [PATCH 05/36] turned some public methods private --- Dynamic Programming/Fibonacci.java | 6 +++--- Dynamic Programming/Levenshtein_distance.java | 4 ++-- Dynamic Programming/LongestIncreasingSubsequence.java | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Dynamic Programming/Fibonacci.java b/Dynamic Programming/Fibonacci.java index 17c11d8d..b2524b4d 100644 --- a/Dynamic Programming/Fibonacci.java +++ b/Dynamic Programming/Fibonacci.java @@ -11,7 +11,7 @@ import java.util.Map; public class Fibonacci { - public static Map map = new HashMap(); + private static Map map = new HashMap(); public static void main(String[] args) throws Exception { @@ -29,7 +29,7 @@ public class Fibonacci { * Outputs the nth fibonacci number **/ - public static int fibMemo(int n) { + private static int fibMemo(int n) { if (map.containsKey(n)) { return map.get(n); } @@ -54,7 +54,7 @@ public class Fibonacci { * Outputs the nth fibonacci number **/ - public static int fibBotUp(int n) { + private static int fibBotUp(int n) { Map fib = new HashMap(); diff --git a/Dynamic Programming/Levenshtein_distance.java b/Dynamic Programming/Levenshtein_distance.java index 5bff389f..49f39902 100644 --- a/Dynamic Programming/Levenshtein_distance.java +++ b/Dynamic Programming/Levenshtein_distance.java @@ -7,7 +7,7 @@ */ public class Levenshtein_distance{ - private int minimum(int a, int b, int c){ + private static int minimum(int a, int b, int c){ if(a < b && a < c){ return a; }else if(b < a && b < c){ @@ -16,7 +16,7 @@ public class Levenshtein_distance{ return c; } } - public int calculate_distance(String a, String b){ + private static int calculate_distance(String a, String b){ len_a = a.length() + 1; len_b = b.length() + 1; int [][] distance_mat = new int[len_a][len_b]; diff --git a/Dynamic Programming/LongestIncreasingSubsequence.java b/Dynamic Programming/LongestIncreasingSubsequence.java index 1616c246..eaa574a4 100644 --- a/Dynamic Programming/LongestIncreasingSubsequence.java +++ b/Dynamic Programming/LongestIncreasingSubsequence.java @@ -31,7 +31,7 @@ public class LongestIncreasingSubsequence { return r; } - public static int LIS(int[] array) { + private static int LIS(int[] array) { int N = array.length; if (N == 0) return 0; From 7bb187bca15e942c1f1ef899ca729bdb90da8a5b Mon Sep 17 00:00:00 2001 From: Michael Rolland Date: Tue, 3 Oct 2017 15:59:12 -0400 Subject: [PATCH 06/36] Make it actually a java file Oops --- Conversions/{AnyBaseToAnyBase => AnyBaseToAnyBase.java} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Conversions/{AnyBaseToAnyBase => AnyBaseToAnyBase.java} (100%) diff --git a/Conversions/AnyBaseToAnyBase b/Conversions/AnyBaseToAnyBase.java similarity index 100% rename from Conversions/AnyBaseToAnyBase rename to Conversions/AnyBaseToAnyBase.java From 6807e7e3ea27cbb09cc3fa0280302e3f0097d237 Mon Sep 17 00:00:00 2001 From: Ribhav Pahuja Date: Thu, 5 Oct 2017 00:50:54 +0530 Subject: [PATCH 07/36] Added Ternary Search --- Searches/TernarySearch.java | 74 +++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 Searches/TernarySearch.java diff --git a/Searches/TernarySearch.java b/Searches/TernarySearch.java new file mode 100644 index 00000000..6b2d2b14 --- /dev/null +++ b/Searches/TernarySearch.java @@ -0,0 +1,74 @@ +import java.util.Scanner; + +public class TernarySearch{ + + /** + * @param arr The **Sorted** array in which we will search the element. + * @param value The value that we want to search for. + * @return The index of the element if found. + * Else returns -1. + */ + public static int ternarySearch(int[] arr, int value){ + return ternarySearch(arr, value, 0, arr.length - 1); + } + + /** + * @param arr The **Sorted** array in which we will search the element. + * @param key The value that we want to search for. + * @param start The starting index from which we will start Searching. + * @param end The ending index till which we will Search. + * @return Returns the index of the Element if found. + * Else returns -1. + */ + public static int ternarySearch(int[] arr, int key, int start, int end) { + if (start > end){ + return -1; + } + /* First boundary: add 1/3 of length to start */ + int mid1 = start + (end - start) / 3; + /* Second boundary: add 2/3 of length to start */ + int mid2 = start + 2 * (end - start) / 3; + if (arr[mid1] == key) { + return mid1; + } + else if (arr[mid2] == key) { + return mid2; + } + + /* Search the first (1/3) rd part of the array.*/ + + else if (key < arr[mid1]) { + return ternarySearch(arr, key, start, mid1 - 1); + } + /* Search 3rd (1/3)rd part of the array */ + + else if (key > arr[mid2]) { + return ternarySearch(arr, key, mid2 + 1, end); + } + /* Search middle (1/3)rd part of the array */ + + else { + return ternarySearch(arr, key, mid1, mid2); + } + } + + public static void main(String[] args) { + Scanner s = new Scanner(System.in); + System.out.println("Enter number of elements in the array"); + int n = s.nextInt(); + int arr[] = new int[n]; + System.out.println("Enter the elements of the array"); + for (int i= 0; i < n; i++){ + arr[i] = s.nextInt(); + } + System.out.println("Enter element to search for : "); + int k = s.nextInt(); + int ans = ternarySearch(arr, k); + if (ans == -1) { + System.out.println(" The element is not present in the array."); + } + else { + System.out.println("The element is present at the position" + ans); + } + } +} \ No newline at end of file From 76042f4713e560765ebfc9cc9b43b3bf43ff7c04 Mon Sep 17 00:00:00 2001 From: Ribhav Pahuja Date: Thu, 5 Oct 2017 00:55:27 +0530 Subject: [PATCH 08/36] Added Ternary Search --- Searches/TernarySearch.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Searches/TernarySearch.java b/Searches/TernarySearch.java index 6b2d2b14..06b0be56 100644 --- a/Searches/TernarySearch.java +++ b/Searches/TernarySearch.java @@ -57,7 +57,7 @@ public class TernarySearch{ System.out.println("Enter number of elements in the array"); int n = s.nextInt(); int arr[] = new int[n]; - System.out.println("Enter the elements of the array"); + System.out.println("Enter the elements of the Sorted array"); for (int i= 0; i < n; i++){ arr[i] = s.nextInt(); } @@ -68,7 +68,7 @@ public class TernarySearch{ System.out.println(" The element is not present in the array."); } else { - System.out.println("The element is present at the position" + ans); + System.out.println("The element is present at the position " + (ans+1)); } } } \ No newline at end of file From a139d6b5bc4d06602c4a67aeed6b42639e25fbb6 Mon Sep 17 00:00:00 2001 From: Pankaj Kumar Gautam Date: Thu, 5 Oct 2017 13:16:13 +0530 Subject: [PATCH 09/36] updating file according to new algorithms added --- README.md | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 55 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 4b563445..4e3b62f5 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# The Algorithms - Java [![Build Status](https://travis-ci.org/TheAlgorithms/Python.svg)](https://travis-ci.org/TheAlgorithms/Python) +# The Algorithms - Java [![Build Status](https://travis-ci.org/TheAlgorithms/Java.svg)](https://travis-ci.org/TheAlgorithms/Java) ### All algorithms implemented in Java (for education) @@ -47,7 +47,17 @@ __Properties__ ###### View the algorithm in [action][merge-toptal] +### Quick +![alt text][quick-image] +From [Wikipedia][quick-wiki]: Quicksort (sometimes called partition-exchange sort) is an efficient sorting algorithm, serving as a systematic method for placing the elements of an array in order. + +__Properties__ +* Worst case performance O(n^2) +* Best case performance O(n log n) or O(n) with three-way partition +* Average case performance O(n^2) + +###### View the algorithm in [action][quick-toptal] ### Selection ![alt text][selection-image] @@ -61,6 +71,50 @@ __Properties__ ###### View the algorithm in [action][selection-toptal] +### Shell +![alt text][shell-image] + +From [Wikipedia][shell-wiki]: Shellsort is a generalization of insertion sort that allows the exchange of items that are far apart. The idea is to arrange the list of elements so that, starting anywhere, considering every nth element gives a sorted list. Such a list is said to be h-sorted. Equivalently, it can be thought of as h interleaved lists, each individually sorted. + +__Properties__ +* Worst case performance O(nlog2 2n) +* Best case performance O(n log n) +* Average case performance depends on gap sequence + +###### View the algorithm in [action][shell-toptal] + +### Time-Compexity Graphs + +Comparing the complexity of sorting algorithms (Bubble Sort, Insertion Sort, Selection Sort) + +[Complexity Graphs](https://github.com/prateekiiest/Python/blob/master/sorts/sortinggraphs.png) + +---------------------------------------------------------------------------------- + +## Search Algorithms + +### Linear +![alt text][linear-image] + +From [Wikipedia][linear-wiki]: linear search or sequential search is a method for finding a target value within a list. It sequentially checks each element of the list for the target value until a match is found or until all the elements have been searched. + Linear search runs in at worst linear time and makes at most n comparisons, where n is the length of the list. + +__Properties__ +* Worst case performance O(n) +* Best case performance O(1) +* Average case performance O(n) +* Worst case space complexity O(1) iterative + +### Binary +![alt text][binary-image] + +From [Wikipedia][binary-wiki]: Binary search, also known as half-interval search or logarithmic search, is a search algorithm that finds the position of a target value within a sorted array. It compares the target value to the middle element of the array; if they are unequal, the half in which the target cannot lie is eliminated and the search continues on the remaining half until it is successful. + +__Properties__ +* Worst case performance O(log n) +* Best case performance O(1) +* Average case performance O(log n) +* Worst case space complexity O(1) [bubble-toptal]: https://www.toptal.com/developers/sorting-algorithms/bubble-sort @@ -94,4 +148,3 @@ __Properties__ [binary-image]: https://upload.wikimedia.org/wikipedia/commons/f/f7/Binary_search_into_array.png -[caesar]: https://upload.wikimedia.org/wikipedia/commons/4/4a/Caesar_cipher_left_shift_of_3.svg From 50f8693ffab4d9e88495a3fddd21019d8f1b7c75 Mon Sep 17 00:00:00 2001 From: Pankaj Kumar Gautam Date: Thu, 5 Oct 2017 13:17:11 +0530 Subject: [PATCH 10/36] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4e3b62f5..9b925db5 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# The Algorithms - Java [![Build Status](https://travis-ci.org/TheAlgorithms/Java.svg)](https://travis-ci.org/TheAlgorithms/Java) +# The Algorithms - Java [![Build Status](https://travis-ci.org/TheAlgorithms/Python.svg)](https://travis-ci.org/TheAlgorithms/Python) ### All algorithms implemented in Java (for education) From 35bd2bb9df1788ac8521b3e46fbcc4e3593b2b30 Mon Sep 17 00:00:00 2001 From: Acha Jackson Date: Thu, 5 Oct 2017 13:23:11 +0100 Subject: [PATCH 11/36] #96.Added and Implemented Counting sort with Java --- Sorts/CountSort.java | 47 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Sorts/CountSort.java diff --git a/Sorts/CountSort.java b/Sorts/CountSort.java new file mode 100644 index 00000000..232df591 --- /dev/null +++ b/Sorts/CountSort.java @@ -0,0 +1,47 @@ +public class CountingSort +{ + public static void sort(char arr[]) + { + int n = arr.length; + + // The output character array that will have sorted arr + char output[] = new char[n]; + + // Create a count array to store count of inidividul + // characters and initialize count array as 0 + int count[] = new int[256]; + for (int i = 0; i < 256; ++i) + count[i] = 0; + + // store count of each character + for (int i=0; i Date: Thu, 5 Oct 2017 16:27:54 -0400 Subject: [PATCH 12/36] Added comments to level order traversal method, and samples in main method. --- data_structures/Trees/TreeTraversal.java | 59 +++++++++++++----------- 1 file changed, 33 insertions(+), 26 deletions(-) diff --git a/data_structures/Trees/TreeTraversal.java b/data_structures/Trees/TreeTraversal.java index 8e73134e..1db0c6e8 100644 --- a/data_structures/Trees/TreeTraversal.java +++ b/data_structures/Trees/TreeTraversal.java @@ -1,10 +1,10 @@ import java.util.LinkedList; /** - * - * @author Varun Upadhyay (https://github.com/varunu28) - * - */ +* +* @author Varun Upadhyay (https://github.com/varunu28) +* +*/ // Driver Program public class TreeTraversal { @@ -17,18 +17,19 @@ public class TreeTraversal { tree.insert(6); tree.insert(8); + // Prints 5 3 2 4 7 6 8 System.out.println("Pre order traversal:"); tree.printPreOrder(); System.out.println(); - + // Prints 2 3 4 5 6 7 8 System.out.println("In order traversal:"); tree.printInOrder(); System.out.println(); - + // Prints 2 4 3 6 8 7 5 System.out.println("Post order traversal:"); tree.printPostOrder(); System.out.println(); - + // Prints 5 3 7 2 4 6 8 System.out.println("Level order traversal:"); tree.printLevelOrder(); System.out.println(); @@ -36,12 +37,13 @@ public class TreeTraversal { } /** - * The Node class which initializes a Node of a tree - * Consists of all 3 traversal methods: printInOrder, printPostOrder & printPreOrder - * printInOrder: LEFT -> ROOT -> RIGHT - * printPreOrder: ROOT -> LEFT -> RIGHT - * printPostOrder: LEFT -> RIGHT -> ROOT - */ +* The Node class which initializes a Node of a tree +* Consists of all 3 traversal methods: printInOrder, printPostOrder & printPreOrder +* printInOrder: LEFT -> ROOT -> RIGHT +* printPreOrder: ROOT -> LEFT -> RIGHT +* printPostOrder: LEFT -> RIGHT -> ROOT +* printLevelOrder: Prints by level (starting at root), from left to right. +*/ class Node { Node left, right; int data; @@ -99,18 +101,23 @@ class Node { System.out.print(data + " "); } + /** + * O(n) time algorithm. + * Uses O(n) space to store nodes in a queue to aid in traversal. + */ public void printLevelOrder() { - LinkedList queue = new LinkedList<>(); - queue.add(this); - while (queue.size() > 0) { - Node head = queue.remove(); - System.out.print(head.data + " "); - if (head.left != null) { - queue.add(head.left); - } - if (head.right != null) { - queue.add(head.right); - } - } - } + LinkedList queue = new LinkedList<>(); + queue.add(this); + while (queue.size() > 0) { + Node head = queue.remove(); + System.out.print(head.data + " "); + // Add children of recently-printed node to queue, if they exist. + if (head.left != null) { + queue.add(head.left); + } + if (head.right != null) { + queue.add(head.right); + } + } + } } From 2128c7a15dc757c20af73dfd54f64da6febe789d Mon Sep 17 00:00:00 2001 From: "DESKTOP-0VAEMFL\\joaom" <1160907@isep.ipp.pt> Date: Thu, 5 Oct 2017 22:37:13 +0100 Subject: [PATCH 13/36] Columnar Transposition Cipher with example usage --- ciphers/ColumnarTranspositionCipher.java | 169 +++++++++++++++++++++++ 1 file changed, 169 insertions(+) create mode 100644 ciphers/ColumnarTranspositionCipher.java diff --git a/ciphers/ColumnarTranspositionCipher.java b/ciphers/ColumnarTranspositionCipher.java new file mode 100644 index 00000000..b1274371 --- /dev/null +++ b/ciphers/ColumnarTranspositionCipher.java @@ -0,0 +1,169 @@ +/** + * Columnar Transposition Cipher Encryption and Decryption. + * @author freitzzz + */ +public class ColumnarTranspositionCipher { + private static String keyword; + private static Object[][] table; + private static String abecedarium; + public static final String ABECEDARIUM="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,.;:-@"; + private static final String ENCRYPTION_FIELD="≈"; + private static final char ENCRYPTION_FIELD_CHAR='≈'; + /** + * Encrypts a certain String with the Columnar Transposition Cipher Rule + * @param word Word being encrypted + * @param keyword String with keyword being used + * @return a String with the word encrypted by the Columnar Transposition Cipher Rule + */ + public static String encrpyter(String word,String keyword){ + ColumnarTranspositionCipher.keyword=keyword; + abecedariumBuilder(500); + table=tableBuilder(word); + Object[][] sortedTable=sortTable(table); + String wordEncrypted=""; + for(int i=0;iword.length()/keyword.length()){ + return (word.length()/keyword.length())+1; + }else{ + return word.length()/keyword.length(); + } + } + private static Object[] findElements(){ + Object[] charValues=new Object[keyword.length()]; + for(int i=0;i(int)table[0][j]){ + Object[] column=getColumn(tableSorted,tableSorted.length,i); + switchColumns(tableSorted,j,i,column); + } + } + } + return tableSorted; + } + private static Object[] getColumn(Object[][] table,int rows,int column){ + Object[] columnArray=new Object[rows]; + for(int i=0;i>> "+wordBeingEncrypted); + System.out.println("Word encrypted ->>> "+ColumnarTranspositionCipher.encrpyter(wordBeingEncrypted,keywordForExample)); + System.out.println("Word decryped ->>> "+ColumnarTranspositionCipher.decrypter()); + System.out.println("\n### Encrypted Table ###"); + showTable(); + } +} From a9e8b6b1001832861c063b18ad1165b1bbe4be99 Mon Sep 17 00:00:00 2001 From: KyleScharnhorst Date: Sat, 7 Oct 2017 20:18:35 -0700 Subject: [PATCH 14/36] Add: level order traversal. Prints each level of the bst. I.e., Root -> its children -> its children's children -> and so on... --- data_structures/Trees/TreeTraversal.java | 30 +++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/data_structures/Trees/TreeTraversal.java b/data_structures/Trees/TreeTraversal.java index c4ff92d0..8dd0555a 100644 --- a/data_structures/Trees/TreeTraversal.java +++ b/data_structures/Trees/TreeTraversal.java @@ -3,6 +3,7 @@ * @author Varun Upadhyay (https://github.com/varunu28) * */ +import java.util.LinkedList; // Driver Program public class TreeTraversal { @@ -10,18 +11,25 @@ public class TreeTraversal { Node tree = new Node(5); tree.insert(3); tree.insert(7); + tree.insert(1); + tree.insert(9); - // Prints 3 5 7 + // Prints 1 3 5 7 9 tree.printInOrder(); System.out.println(); - // Prints 5 3 7 + // Prints 5 3 1 7 9 tree.printPreOrder(); System.out.println(); - // Prints 3 7 5 + // Prints 1 3 9 7 5 tree.printPostOrder(); System.out.println(); + + // Add a couple more nodes for print level test + // Print 5 3 7 1 9 + tree.printLevelOrder(); + System.out.println(); } } @@ -31,6 +39,7 @@ public class TreeTraversal { * printInOrder: LEFT -> ROOT -> RIGHT * printPreOrder: ROOT -> LEFT -> RIGHT * printPostOrder: LEFT -> RIGHT -> ROOT + * printLevelOrder: ROOT -> ROOT's CHILDREN -> ROOT's CHILDREN's CHILDREN -> etc */ class Node { Node left, right; @@ -88,5 +97,20 @@ class Node { } System.out.print(data + " "); } + + public void printLevelOrder() { + LinkedList queue = new LinkedList<>(); + queue.add(this); + while(!queue.isEmpty()) { + Node n = queue.poll(); + System.out.print(n.data + " "); + if (n.left != null) { + queue.add(n.left); + } + if (n.right != null) { + queue.add(n.right); + } + } + } } From a275701781369052bcb479eea4cf547b9b1ad89e Mon Sep 17 00:00:00 2001 From: Ayaan Faiz Date: Tue, 10 Oct 2017 19:00:34 +0530 Subject: [PATCH 15/36] To check if tree is valid BST tree or not --- data_structures/Trees/Valid BST or not.java | 62 +++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 data_structures/Trees/Valid BST or not.java diff --git a/data_structures/Trees/Valid BST or not.java b/data_structures/Trees/Valid BST or not.java new file mode 100644 index 00000000..0f71a46a --- /dev/null +++ b/data_structures/Trees/Valid BST or not.java @@ -0,0 +1,62 @@ +class Node +{ + int data; + Node left, right; + + public Node(int item) + { + data = item; + left = right = null; + } +} + +public class BinaryTree +{ + //Root of the Binary Tree + Node root; + + /* can give min and max value according to your code or + can write a function to find min and max value of tree. */ + + /* returns true if given search tree is binary + search tree (efficient version) */ + boolean isBST() { + return isBSTUtil(root, Integer.MIN_VALUE, + Integer.MAX_VALUE); + } + + /* Returns true if the given tree is a BST and its + values are >= min and <= max. */ + boolean isBSTUtil(Node node, int min, int max) + { + /* an empty tree is BST */ + if (node == null) + return true; + + /* false if this node violates the min/max constraints */ + if (node.data < min || node.data > max) + return false; + + /* otherwise check the subtrees recursively + tightening the min/max constraints */ + // Allow only distinct values + return (isBSTUtil(node.left, min, node.data-1) && + isBSTUtil(node.right, node.data+1, max)); + } + + /* Driver program to test above functions */ + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(4); + tree.root.left = new Node(2); + tree.root.right = new Node(5); + tree.root.left.left = new Node(1); + tree.root.left.right = new Node(3); + + if (tree.isBST()) + System.out.println("IS BST"); + else + System.out.println("Not a BST"); + } +} \ No newline at end of file From f6c322249f00ce1bd1709b346aa616f2f4f7abd6 Mon Sep 17 00:00:00 2001 From: Tobias Date: Tue, 10 Oct 2017 20:26:06 -0700 Subject: [PATCH 16/36] Add Linear Congruential Generator --- Misc/LinearCongruentialGenerator.java | 57 +++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Misc/LinearCongruentialGenerator.java diff --git a/Misc/LinearCongruentialGenerator.java b/Misc/LinearCongruentialGenerator.java new file mode 100644 index 00000000..b03c10da --- /dev/null +++ b/Misc/LinearCongruentialGenerator.java @@ -0,0 +1,57 @@ +/*** + * A pseudorandom number generator. + * + * @author Tobias Carryer + * Date: October 10, 2017 + */ +public class LinearCongruentialGenerator { + + private double a, c, m, previousValue; + + /*** + * These parameters are saved and used when nextNumber() is called. + * The current timestamp in milliseconds is used as the seed. + * + * @param multiplier + * @param increment + * @param modulo The maximum number that can be generated (exclusive). A common value is 2^32. + */ + public LinearCongruentialGenerator( double multiplier, double increment, double modulo ) { + this(System.currentTimeMillis(), multiplier, increment, modulo); + } + + /*** + * These parameters are saved and used when nextNumber() is called. + * + * @param seed + * @param multiplier + * @param increment + * @param modulo The maximum number that can be generated (exclusive). A common value is 2^32. + */ + public LinearCongruentialGenerator( double seed, double multiplier, double increment, double modulo ) { + this.previousValue = seed; + this.a = multiplier; + this.c = increment; + this.m = modulo; + } + + /** + * The smallest number that can be generated is zero. + * The largest number that can be generated is modulo-1. modulo is set in the constructor. + * @return a pseudorandom number. + */ + public double nextNumber() { + previousValue = (a * previousValue + c) % m; + return previousValue; + } + + public static void main( String[] args ) { + // Show the LCG in action. + // Decisive proof that the LCG works could be made by adding each number + // generated to a Set while checking for duplicates. + LinearCongruentialGenerator lcg = new LinearCongruentialGenerator(1664525, 1013904223, Math.pow(2.0, 32.0)); + for( int i = 0; i < 512; i++ ) { + System.out.println(lcg.nextNumber()); + } + } +} From 3244f5b698dda67209d497ec20b2d821025eb59f Mon Sep 17 00:00:00 2001 From: Ayaan Faiz Date: Wed, 11 Oct 2017 19:47:55 +0530 Subject: [PATCH 17/36] To check if tree is valid BST tree or not (#180) --- data_structures/Trees/Valid BST or not.java | 62 +++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 data_structures/Trees/Valid BST or not.java diff --git a/data_structures/Trees/Valid BST or not.java b/data_structures/Trees/Valid BST or not.java new file mode 100644 index 00000000..0f71a46a --- /dev/null +++ b/data_structures/Trees/Valid BST or not.java @@ -0,0 +1,62 @@ +class Node +{ + int data; + Node left, right; + + public Node(int item) + { + data = item; + left = right = null; + } +} + +public class BinaryTree +{ + //Root of the Binary Tree + Node root; + + /* can give min and max value according to your code or + can write a function to find min and max value of tree. */ + + /* returns true if given search tree is binary + search tree (efficient version) */ + boolean isBST() { + return isBSTUtil(root, Integer.MIN_VALUE, + Integer.MAX_VALUE); + } + + /* Returns true if the given tree is a BST and its + values are >= min and <= max. */ + boolean isBSTUtil(Node node, int min, int max) + { + /* an empty tree is BST */ + if (node == null) + return true; + + /* false if this node violates the min/max constraints */ + if (node.data < min || node.data > max) + return false; + + /* otherwise check the subtrees recursively + tightening the min/max constraints */ + // Allow only distinct values + return (isBSTUtil(node.left, min, node.data-1) && + isBSTUtil(node.right, node.data+1, max)); + } + + /* Driver program to test above functions */ + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(4); + tree.root.left = new Node(2); + tree.root.right = new Node(5); + tree.root.left.left = new Node(1); + tree.root.left.right = new Node(3); + + if (tree.isBST()) + System.out.println("IS BST"); + else + System.out.println("Not a BST"); + } +} \ No newline at end of file From de86c31dc78f3e3b2eb0ef76af6caa1db76f29d8 Mon Sep 17 00:00:00 2001 From: Michael Rolland Date: Wed, 11 Oct 2017 14:22:06 -0400 Subject: [PATCH 18/36] Add validForBase() and min/max base constants --- Conversions/AnyBaseToAnyBase.java | 57 +++++++++++++++++++++++++++---- 1 file changed, 50 insertions(+), 7 deletions(-) diff --git a/Conversions/AnyBaseToAnyBase.java b/Conversions/AnyBaseToAnyBase.java index 9f3f3704..33c77975 100644 --- a/Conversions/AnyBaseToAnyBase.java +++ b/Conversions/AnyBaseToAnyBase.java @@ -1,28 +1,48 @@ +import java.util.Arrays; +import java.util.HashSet; import java.util.InputMismatchException; import java.util.Scanner; /** - * Class for converting from any base to any other base, though it's unclear how digits greater than - * 36 would be represented in bases >36. + * Class for converting from "any" base to "any" other base, when "any" means from 2-36. + * Works by going from base 1 to decimal to base 2. Includes auxiliary method for + * determining whether a number is valid for a given base. * * @author Michael Rolland - * @version 2017.09.29 + * @version 2017.10.10 * */ public class AnyBaseToAnyBase { + // Smallest and largest base you want to accept as valid input + static final int MINIMUM_BASE = 2; + static final int MAXIMUM_BASE = 36; + // Driver public static void main(String[] args) { Scanner in = new Scanner(System.in); - System.out.print("Enter number: "); - String n = in.nextLine(); + String n; int b1=0,b2=0; while (true) { try { - System.out.print("Enter beginning base: "); + System.out.print("Enter number: "); + n = in.next(); + System.out.print("Enter beginning base (between "+MINIMUM_BASE+" and "+MAXIMUM_BASE+"): "); b1 = in.nextInt(); - System.out.print("Enter end base: "); + if (b1 > MAXIMUM_BASE || b1 < MINIMUM_BASE) { + System.out.println("Invalid base!"); + continue; + } + if (!validForBase(n, b1)) { + System.out.println("The number is invalid for this base!"); + continue; + } + System.out.print("Enter end base (between "+MINIMUM_BASE+" and "+MAXIMUM_BASE+"): "); b2 = in.nextInt(); + if (b2 > MAXIMUM_BASE || b2 < MINIMUM_BASE) { + System.out.println("Invalid base!"); + continue; + } break; } catch (InputMismatchException e) { System.out.println("Invalid input."); @@ -32,6 +52,29 @@ public class AnyBaseToAnyBase { System.out.println(base2base(n, b1, b2)); } + /** + * Checks if a number (as a String) is valid for a given base. + */ + public static boolean validForBase(String n, int base) { + char[] validDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', + 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', + 'W', 'X', 'Y', 'Z'}; + // digitsForBase contains all the valid digits for the base given + char[] digitsForBase = Arrays.copyOfRange(validDigits, 0, base); + + // Convert character array into set for convenience of contains() method + HashSet digitsList = new HashSet(); + for (int i=0; i Date: Thu, 12 Oct 2017 10:31:46 -0700 Subject: [PATCH 19/36] Create FindHeightOfTree.java --- data_structures/Trees/FindHeightOfTree.java | 100 ++++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 data_structures/Trees/FindHeightOfTree.java diff --git a/data_structures/Trees/FindHeightOfTree.java b/data_structures/Trees/FindHeightOfTree.java new file mode 100644 index 00000000..675b1e8b --- /dev/null +++ b/data_structures/Trees/FindHeightOfTree.java @@ -0,0 +1,100 @@ +/** + * + * @author Varun Upadhyay (https://github.com/varunu28) + * + */ +import java.util.LinkedList; + +public class FindHeightOfTree { + + // Driver Program + public static void main(String[] args) { + Node tree = new Node(5); + tree.insert(3); + tree.insert(7); + tree.insert(1); + tree.insert(-1); + tree.insert(29); + tree.insert(93); + tree.insert(6); + tree.insert(0); + tree.insert(-5); + tree.insert(-6); + tree.insert(-8); + tree.insert(-1); + + // A level order representation of the tree + tree.printLevelOrder(); + System.out.println(); + + System.out.println("Height of the tree is: " + tree.findHeight()); + } +} + +/** + * The Node class which initializes a Node of a tree + * printLevelOrder: ROOT -> ROOT's CHILDREN -> ROOT's CHILDREN's CHILDREN -> etc + * findHeight: Returns the height of the tree i.e. the number of links between root and farthest leaf + */ +class Node { + Node left, right; + int data; + + public Node(int data) { + this.data = data; + } + + public void insert (int value) { + if (value < data) { + if (left == null) { + left = new Node(value); + } + else { + left.insert(value); + } + } + else { + if (right == null) { + right = new Node(value); + } + else { + right.insert(value); + } + } + } + + public void printLevelOrder() { + LinkedList queue = new LinkedList<>(); + queue.add(this); + while(!queue.isEmpty()) { + Node n = queue.poll(); + System.out.print(n.data + " "); + if (n.left != null) { + queue.add(n.left); + } + if (n.right != null) { + queue.add(n.right); + } + } + } + + public int findHeight() { + return findHeight(this); + } + + private int findHeight(Node root) { + if (root.left == null && root.right == null) { + return 0; + } + else if (root.left != null && root.right != null) { + return 1 + Math.max(findHeight(root.left), findHeight(root.right)); + } + else if (root.left == null && root.right != null) { + return 1 + findHeight(root.right); + } + else { + return 1 + findHeight(root.left); + } + } +} + From ea62951117ca0b03fd37c0570ab79d3b2822d94d Mon Sep 17 00:00:00 2001 From: Rahul Jain Date: Fri, 13 Oct 2017 03:43:31 +0530 Subject: [PATCH 20/36] Add Longest Common Subsequence algorithm (DP) --- .../LongestCommonSubsequence.java | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 Dynamic Programming/LongestCommonSubsequence.java diff --git a/Dynamic Programming/LongestCommonSubsequence.java b/Dynamic Programming/LongestCommonSubsequence.java new file mode 100644 index 00000000..9e828056 --- /dev/null +++ b/Dynamic Programming/LongestCommonSubsequence.java @@ -0,0 +1,66 @@ +class LongestCommonSubsequence { + + public static String getLCS(String str1, String str2) { + + //At least one string is null + if(str1 == null || str2 == null) + return null; + + //At least one string is empty + if(str1.length() == 0 || str2.length() == 0) + return ""; + + String[] arr1 = str1.split(""); + String[] arr2 = str2.split(""); + + //lcsMatrix[i][j] = LCS of first i elements of arr1 and first j characters of arr2 + int[][] lcsMatrix = new int[arr1.length + 1][arr2.length + 1]; + + for(int i = 0; i < arr1.length + 1; i++) + lcsMatrix[i][0] = 0; + for(int j = 1; j < arr2.length + 1; j++) + lcsMatrix[0][j] = 0; + for(int i = 1; i < arr1.length + 1; i++) { + for(int j = 1; j < arr2.length + 1; j++) { + if(arr1[i-1].equals(arr2[j-1])) { + lcsMatrix[i][j] = lcsMatrix[i-1][j-1] + 1; + } else { + lcsMatrix[i][j] = lcsMatrix[i-1][j] > lcsMatrix[i][j-1] ? lcsMatrix[i-1][j] : lcsMatrix[i][j-1]; + } + } + } + return lcsString(str1, str2, lcsMatrix); + } + + public static String lcsString (String str1, String str2, int[][] lcsMatrix) { + StringBuilder lcs = new StringBuilder(); + int i = str1.length(), + j = str2.length(); + while(i > 0 && j > 0) { + if(str1.charAt(i-1) == str2.charAt(j-1)) { + lcs.append(str1.charAt(i-1)); + i--; + j--; + } else if(lcsMatrix[i-1][j] > lcsMatrix[i][j-1]) { + i--; + } else { + j--; + } + } + return lcs.reverse().toString(); + } + + public static void main(String[] args) { + String str1 = "DSGSHSRGSRHTRD"; + String str2 = "DATRGAGTSHS"; + String lcs = getLCS(str1, str2); + + //Print LCS + if(lcs != null) { + System.out.println("String 1: " + str1); + System.out.println("String 2: " + str2); + System.out.println("LCS: " + lcs); + System.out.println("LCS length: " + lcs.length()); + } + } +} \ No newline at end of file From 12af0489a773ec5781b190271ff19bb614e7f105 Mon Sep 17 00:00:00 2001 From: Ayaan Faiz Date: Fri, 13 Oct 2017 13:50:30 +0530 Subject: [PATCH 21/36] Top view --- .../Trees/Print Top View of Tree.java | 105 ++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 data_structures/Trees/Print Top View of Tree.java diff --git a/data_structures/Trees/Print Top View of Tree.java b/data_structures/Trees/Print Top View of Tree.java new file mode 100644 index 00000000..a429f8a6 --- /dev/null +++ b/data_structures/Trees/Print Top View of Tree.java @@ -0,0 +1,105 @@ +// Java program to print top view of Binary tree +import java.util.*; + +// Class for a tree node +class TreeNode +{ + // Members + int key; + TreeNode left, right; + + // Constructor + public TreeNode(int key) + { + this.key = key; + left = right = null; + } +} + +// A class to represent a queue item. The queue is used to do Level +// order traversal. Every Queue item contains node and horizontal +// distance of node from root +class QItem +{ + TreeNode node; + int hd; + public QItem(TreeNode n, int h) + { + node = n; + hd = h; + } +} + +// Class for a Binary Tree +class Tree +{ + TreeNode root; + + // Constructors + public Tree() { root = null; } + public Tree(TreeNode n) { root = n; } + + // This method prints nodes in top view of binary tree + public void printTopView() + { + // base case + if (root == null) { return; } + + // Creates an empty hashset + HashSet set = new HashSet<>(); + + // Create a queue and add root to it + Queue Q = new LinkedList(); + Q.add(new QItem(root, 0)); // Horizontal distance of root is 0 + + // Standard BFS or level order traversal loop + while (!Q.isEmpty()) + { + // Remove the front item and get its details + QItem qi = Q.remove(); + int hd = qi.hd; + TreeNode n = qi.node; + + // If this is the first node at its horizontal distance, + // then this node is in top view + if (!set.contains(hd)) + { + set.add(hd); + System.out.print(n.key + " "); + } + + // Enqueue left and right children of current node + if (n.left != null) + Q.add(new QItem(n.left, hd-1)); + if (n.right != null) + Q.add(new QItem(n.right, hd+1)); + } + } +} + +// Driver class to test above methods +public class Main +{ + public static void main(String[] args) + { + /* Create following Binary Tree + 1 + / \ + 2 3 + \ + 4 + \ + 5 + \ + 6*/ + TreeNode root = new TreeNode(1); + root.left = new TreeNode(2); + root.right = new TreeNode(3); + root.left.right = new TreeNode(4); + root.left.right.right = new TreeNode(5); + root.left.right.right.right = new TreeNode(6); + Tree t = new Tree(root); + System.out.println("Following are nodes in top view of Binary Tree"); + t.printTopView(); + } +} \ No newline at end of file From 98ef32740340134f078cda5168ac1fa478bf42d1 Mon Sep 17 00:00:00 2001 From: Ayaan Faiz Date: Fri, 13 Oct 2017 13:50:55 +0530 Subject: [PATCH 22/36] Level Order Traversal(2 methods) --- .../Level Order Traversal(using Queue).java | 62 +++++++++++++++ .../Trees/Level Order Traversal.java | 78 +++++++++++++++++++ 2 files changed, 140 insertions(+) create mode 100644 data_structures/Trees/Level Order Traversal(using Queue).java create mode 100644 data_structures/Trees/Level Order Traversal.java diff --git a/data_structures/Trees/Level Order Traversal(using Queue).java b/data_structures/Trees/Level Order Traversal(using Queue).java new file mode 100644 index 00000000..4f263c95 --- /dev/null +++ b/data_structures/Trees/Level Order Traversal(using Queue).java @@ -0,0 +1,62 @@ +import java.util.Queue; +import java.util.LinkedList; + +/* Class to represent Tree node */ +class Node { + int data; + Node left, right; + + public Node(int item) { + data = item; + left = null; + right = null; + } +} + +/* Class to print Level Order Traversal */ +class BinaryTree { + + Node root; + + /* Given a binary tree. Print its nodes in level order + using array for implementing queue */ + void printLevelOrder() + { + Queue queue = new LinkedList(); + queue.add(root); + while (!queue.isEmpty()) + { + + /* poll() removes the present head. + For more information on poll() visit + http://www.tutorialspoint.com/java/util/linkedlist_poll.htm */ + Node tempNode = queue.poll(); + System.out.print(tempNode.data + " "); + + /*Enqueue left child */ + if (tempNode.left != null) { + queue.add(tempNode.left); + } + + /*Enqueue right child */ + if (tempNode.right != null) { + queue.add(tempNode.right); + } + } + } + + public static void main(String args[]) + { + /* creating a binary tree and entering + the nodes */ + BinaryTree tree_level = new BinaryTree(); + tree_level.root = new Node(1); + tree_level.root.left = new Node(2); + tree_level.root.right = new Node(3); + tree_level.root.left.left = new Node(4); + tree_level.root.left.right = new Node(5); + + System.out.println("Level order traversal of binary tree is - "); + tree_level.printLevelOrder(); + } +} \ No newline at end of file diff --git a/data_structures/Trees/Level Order Traversal.java b/data_structures/Trees/Level Order Traversal.java new file mode 100644 index 00000000..845ab376 --- /dev/null +++ b/data_structures/Trees/Level Order Traversal.java @@ -0,0 +1,78 @@ +class Node +{ + int data; + Node left, right; + public Node(int item) + { + data = item; + left = right = null; + } +} + +class BinaryTree +{ + // Root of the Binary Tree + Node root; + + public BinaryTree() + { + root = null; + } + + /* function to print level order traversal of tree*/ + void printLevelOrder() + { + int h = height(root); + int i; + for (i=1; i<=h; i++) + printGivenLevel(root, i); + } + + /* Compute the "height" of a tree -- the number of + nodes along the longest path from the root node + down to the farthest leaf node.*/ + int height(Node root) + { + if (root == null) + return 0; + else + { + /* compute height of each subtree */ + int lheight = height(root.left); + int rheight = height(root.right); + + /* use the larger one */ + if (lheight > rheight) + return(lheight+1); + else return(rheight+1); + } + } + + /* Print nodes at the given level */ + void printGivenLevel (Node root ,int level) + { + if (root == null) + return; + if (level == 1) + System.out.print(root.data + " "); + else if (level > 1) + { + printGivenLevel(root.left, level-1); + printGivenLevel(root.right, level-1); + } + } + + /* Driver program to test above functions */ + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + tree.root= new Node(1); + tree.root.left= new Node(2); + tree.root.right= new Node(3); + tree.root.left.left= new Node(4); + tree.root.left.right= new Node(5); + + System.out.println("Level order traversal of binary tree is "); + tree.printLevelOrder(); + } +} \ No newline at end of file From e53249ba2381d2f20f3d4493ad70e2da0abb3b05 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Fri, 13 Oct 2017 06:57:26 -0700 Subject: [PATCH 23/36] Synced the directory structure to that of Python repo --- {Misc => Others}/Abecedarian.java | 0 {Misc => Others}/CountChar.java | 0 {Misc => Others}/Dijkshtra.java | 0 {Misc => Others}/Factorial.java | 0 {Misc => Others}/FibToN.java | 0 {Misc => Others}/FindingPrimes.java | 0 {Misc => Others}/GCD.java | 0 Huffman.java => Others/Huffman.java | 0 {Misc => Others}/KMP.java | 0 {Misc => Others}/LinearCongruentialGenerator.java | 0 {Misc => Others}/LowestBasePalindrome.java | 0 {Misc => Others}/Node.java | 0 {Misc => Others}/Palindrome.java | 0 {Misc => Others}/ReturnSubsequence.java | 0 {Misc => Others}/ReverseStackUsingRecursion.java | 0 {Misc => Others}/ReverseString.java | 0 {Misc => Others}/StackPostfixNotation.java | 0 {Misc => Others}/TowerOfHanoiUsingRecursion.java | 0 {Misc => Others}/countwords.java | 0 {Misc => Others}/crc32.java | 0 {Misc => Others}/ft.java | 0 insert_delete_in_array.java => Others/insert_delete_in_array.java | 0 {Misc => Others}/krishnamurthy.java | 0 {Misc => Others}/removeDuplicateFromString.java | 0 {Misc => Others}/root_precision.java | 0 25 files changed, 0 insertions(+), 0 deletions(-) rename {Misc => Others}/Abecedarian.java (100%) rename {Misc => Others}/CountChar.java (100%) rename {Misc => Others}/Dijkshtra.java (100%) rename {Misc => Others}/Factorial.java (100%) rename {Misc => Others}/FibToN.java (100%) rename {Misc => Others}/FindingPrimes.java (100%) rename {Misc => Others}/GCD.java (100%) rename Huffman.java => Others/Huffman.java (100%) rename {Misc => Others}/KMP.java (100%) rename {Misc => Others}/LinearCongruentialGenerator.java (100%) rename {Misc => Others}/LowestBasePalindrome.java (100%) rename {Misc => Others}/Node.java (100%) rename {Misc => Others}/Palindrome.java (100%) rename {Misc => Others}/ReturnSubsequence.java (100%) rename {Misc => Others}/ReverseStackUsingRecursion.java (100%) rename {Misc => Others}/ReverseString.java (100%) rename {Misc => Others}/StackPostfixNotation.java (100%) rename {Misc => Others}/TowerOfHanoiUsingRecursion.java (100%) rename {Misc => Others}/countwords.java (100%) rename {Misc => Others}/crc32.java (100%) rename {Misc => Others}/ft.java (100%) rename insert_delete_in_array.java => Others/insert_delete_in_array.java (100%) rename {Misc => Others}/krishnamurthy.java (100%) rename {Misc => Others}/removeDuplicateFromString.java (100%) rename {Misc => Others}/root_precision.java (100%) diff --git a/Misc/Abecedarian.java b/Others/Abecedarian.java similarity index 100% rename from Misc/Abecedarian.java rename to Others/Abecedarian.java diff --git a/Misc/CountChar.java b/Others/CountChar.java similarity index 100% rename from Misc/CountChar.java rename to Others/CountChar.java diff --git a/Misc/Dijkshtra.java b/Others/Dijkshtra.java similarity index 100% rename from Misc/Dijkshtra.java rename to Others/Dijkshtra.java diff --git a/Misc/Factorial.java b/Others/Factorial.java similarity index 100% rename from Misc/Factorial.java rename to Others/Factorial.java diff --git a/Misc/FibToN.java b/Others/FibToN.java similarity index 100% rename from Misc/FibToN.java rename to Others/FibToN.java diff --git a/Misc/FindingPrimes.java b/Others/FindingPrimes.java similarity index 100% rename from Misc/FindingPrimes.java rename to Others/FindingPrimes.java diff --git a/Misc/GCD.java b/Others/GCD.java similarity index 100% rename from Misc/GCD.java rename to Others/GCD.java diff --git a/Huffman.java b/Others/Huffman.java similarity index 100% rename from Huffman.java rename to Others/Huffman.java diff --git a/Misc/KMP.java b/Others/KMP.java similarity index 100% rename from Misc/KMP.java rename to Others/KMP.java diff --git a/Misc/LinearCongruentialGenerator.java b/Others/LinearCongruentialGenerator.java similarity index 100% rename from Misc/LinearCongruentialGenerator.java rename to Others/LinearCongruentialGenerator.java diff --git a/Misc/LowestBasePalindrome.java b/Others/LowestBasePalindrome.java similarity index 100% rename from Misc/LowestBasePalindrome.java rename to Others/LowestBasePalindrome.java diff --git a/Misc/Node.java b/Others/Node.java similarity index 100% rename from Misc/Node.java rename to Others/Node.java diff --git a/Misc/Palindrome.java b/Others/Palindrome.java similarity index 100% rename from Misc/Palindrome.java rename to Others/Palindrome.java diff --git a/Misc/ReturnSubsequence.java b/Others/ReturnSubsequence.java similarity index 100% rename from Misc/ReturnSubsequence.java rename to Others/ReturnSubsequence.java diff --git a/Misc/ReverseStackUsingRecursion.java b/Others/ReverseStackUsingRecursion.java similarity index 100% rename from Misc/ReverseStackUsingRecursion.java rename to Others/ReverseStackUsingRecursion.java diff --git a/Misc/ReverseString.java b/Others/ReverseString.java similarity index 100% rename from Misc/ReverseString.java rename to Others/ReverseString.java diff --git a/Misc/StackPostfixNotation.java b/Others/StackPostfixNotation.java similarity index 100% rename from Misc/StackPostfixNotation.java rename to Others/StackPostfixNotation.java diff --git a/Misc/TowerOfHanoiUsingRecursion.java b/Others/TowerOfHanoiUsingRecursion.java similarity index 100% rename from Misc/TowerOfHanoiUsingRecursion.java rename to Others/TowerOfHanoiUsingRecursion.java diff --git a/Misc/countwords.java b/Others/countwords.java similarity index 100% rename from Misc/countwords.java rename to Others/countwords.java diff --git a/Misc/crc32.java b/Others/crc32.java similarity index 100% rename from Misc/crc32.java rename to Others/crc32.java diff --git a/Misc/ft.java b/Others/ft.java similarity index 100% rename from Misc/ft.java rename to Others/ft.java diff --git a/insert_delete_in_array.java b/Others/insert_delete_in_array.java similarity index 100% rename from insert_delete_in_array.java rename to Others/insert_delete_in_array.java diff --git a/Misc/krishnamurthy.java b/Others/krishnamurthy.java similarity index 100% rename from Misc/krishnamurthy.java rename to Others/krishnamurthy.java diff --git a/Misc/removeDuplicateFromString.java b/Others/removeDuplicateFromString.java similarity index 100% rename from Misc/removeDuplicateFromString.java rename to Others/removeDuplicateFromString.java diff --git a/Misc/root_precision.java b/Others/root_precision.java similarity index 100% rename from Misc/root_precision.java rename to Others/root_precision.java From 295ff41346f7a32098ddb08769518c3e7cbb756c Mon Sep 17 00:00:00 2001 From: Youssef Ali Date: Fri, 13 Oct 2017 22:15:31 +0200 Subject: [PATCH 24/36] Create CountingSortIntegers.java --- Sorts/CountingSortIntegers.java | 66 +++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 Sorts/CountingSortIntegers.java diff --git a/Sorts/CountingSortIntegers.java b/Sorts/CountingSortIntegers.java new file mode 100644 index 00000000..b6bb1fde --- /dev/null +++ b/Sorts/CountingSortIntegers.java @@ -0,0 +1,66 @@ +/** + * + * @author Youssef Ali (https://github.com/youssefAli11997) + * + */ + +class CountingSortIntegers { + + /** + * This method implements the Counting Sort for integers + * + * @param array The array to be sorted + * @param last The count of total number of elements in array + * Sorts the array in increasing order + * It sorted only integer arrays especially positive integers + * It uses array elements as indexes in the frequency array + * Can accept only array elements within the range [0:10^8] + **/ + + public static void CSI(int array[], int last) { + + // The frequency array. It's initialized with zeros + int[] frequency = new int[100000001]; + // The final output array + int[] sortedArray = new int[array.length]; + int index = 0; + + // Counting the frequency of @param array elements + for(int i=0; i 1 4 6 9 12 23 54 78 231 + System.out.println("After Sorting:"); + for (int i=0;i Date: Fri, 13 Oct 2017 22:24:36 +0200 Subject: [PATCH 25/36] Update CountingSortIntegers.java --- Sorts/CountingSortIntegers.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Sorts/CountingSortIntegers.java b/Sorts/CountingSortIntegers.java index b6bb1fde..33b6e909 100644 --- a/Sorts/CountingSortIntegers.java +++ b/Sorts/CountingSortIntegers.java @@ -12,9 +12,9 @@ class CountingSortIntegers { * @param array The array to be sorted * @param last The count of total number of elements in array * Sorts the array in increasing order - * It sorted only integer arrays especially positive integers + * It sorts only integer arrays especially positive integers * It uses array elements as indexes in the frequency array - * Can accept only array elements within the range [0:10^8] + * It can accept only array elements within the range [0:10^8] **/ public static void CSI(int array[], int last) { From 22220d10499cdeb874a6202a6027672da3fff8d7 Mon Sep 17 00:00:00 2001 From: Youssef Ali Date: Sat, 14 Oct 2017 12:52:55 +0200 Subject: [PATCH 26/36] Create CountingSort.java --- Sorts/CountingSort.java | 90 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 Sorts/CountingSort.java diff --git a/Sorts/CountingSort.java b/Sorts/CountingSort.java new file mode 100644 index 00000000..e6828265 --- /dev/null +++ b/Sorts/CountingSort.java @@ -0,0 +1,90 @@ +import java.util.ArrayList; +import java.util.Map; +import java.util.TreeMap; + +/** + * + * @author Youssef Ali (https://github.com/youssefAli11997) + * + */ + +class CountingSort { + + /** + * This method implements the Generic Counting Sort + * + * @param array The array to be sorted + * @param last The count of total number of elements in array + * Sorts the array in increasing order + * It uses array elements as keys in the frequency map + **/ + + public static > void CS(T[] array, int last) { + + Map frequency = new TreeMap(); + // The final output array + ArrayList sortedArray = new ArrayList(); + + // Counting the frequency of @param array elements + for(T t : array) { + try{ + frequency.put(t, frequency.get(t)+1); + }catch(Exception e){ // new entry + frequency.put(t, 1); + } + } + + // Filling the sortedArray + for(Map.Entry element : frequency.entrySet()) { + for(int j=0; j 1 4 6 9 12 23 54 78 231 + System.out.println("After Sorting:"); + for (int i=0;i a b c d e + System.out.println("After Sorting:"); + for(int i=0; i Date: Sun, 15 Oct 2017 15:40:36 +0530 Subject: [PATCH 27/36] Prim's And kruskal's Algorithms --- .../Graphs/Kruskal's Algorithm.java | 174 ++++++++++++++++++ data_structures/Graphs/prim.java | 116 ++++++++++++ 2 files changed, 290 insertions(+) create mode 100644 data_structures/Graphs/Kruskal's Algorithm.java create mode 100644 data_structures/Graphs/prim.java diff --git a/data_structures/Graphs/Kruskal's Algorithm.java b/data_structures/Graphs/Kruskal's Algorithm.java new file mode 100644 index 00000000..6fc8412c --- /dev/null +++ b/data_structures/Graphs/Kruskal's Algorithm.java @@ -0,0 +1,174 @@ +// Java program for Kruskal's algorithm to find Minimum Spanning Tree +// of a given connected, undirected and weighted graph +import java.util.*; +import java.lang.*; +import java.io.*; + +class Graph +{ + // A class to represent a graph edge + class Edge implements Comparable + { + int src, dest, weight; + + // Comparator function used for sorting edges based on + // their weight + public int compareTo(Edge compareEdge) + { + return this.weight-compareEdge.weight; + } + }; + + // A class to represent a subset for union-find + class subset + { + int parent, rank; + }; + + int V, E; // V-> no. of vertices & E->no.of edges + Edge edge[]; // collection of all edges + + // Creates a graph with V vertices and E edges + Graph(int v, int e) + { + V = v; + E = e; + edge = new Edge[E]; + for (int i=0; i subsets[yroot].rank) + subsets[yroot].parent = xroot; + + // If ranks are same, then make one as root and increment + // its rank by one + else + { + subsets[yroot].parent = xroot; + subsets[xroot].rank++; + } + } + + // The main function to construct MST using Kruskal's algorithm + void KruskalMST() + { + Edge result[] = new Edge[V]; // Tnis will store the resultant MST + int e = 0; // An index variable, used for result[] + int i = 0; // An index variable, used for sorted edges + for (i=0; i Date: Wed, 18 Oct 2017 07:11:14 -0700 Subject: [PATCH 28/36] Update and rename prim.java to PrimMST.java --- data_structures/Graphs/{prim.java => PrimMST.java} | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) rename data_structures/Graphs/{prim.java => PrimMST.java} (99%) diff --git a/data_structures/Graphs/prim.java b/data_structures/Graphs/PrimMST.java similarity index 99% rename from data_structures/Graphs/prim.java rename to data_structures/Graphs/PrimMST.java index 4bc5e36b..2d366086 100644 --- a/data_structures/Graphs/prim.java +++ b/data_structures/Graphs/PrimMST.java @@ -5,7 +5,7 @@ import java.util.*; import java.lang.*; import java.io.*; -class MST +class PrimMST { // Number of vertices in the graph private static final int V=5; @@ -113,4 +113,4 @@ class MST // Print the solution t.primMST(graph); } -} \ No newline at end of file +} From df5e9a8c6fa9bcffbac4faf574b6d881c05ce367 Mon Sep 17 00:00:00 2001 From: sahilb2 Date: Thu, 19 Oct 2017 16:23:57 -0500 Subject: [PATCH 29/36] added QueueUsingTwoStacks.java class in Other folder --- Others/QueueUsingTwoStacks.java | 67 +++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 Others/QueueUsingTwoStacks.java diff --git a/Others/QueueUsingTwoStacks.java b/Others/QueueUsingTwoStacks.java new file mode 100644 index 00000000..34bd4488 --- /dev/null +++ b/Others/QueueUsingTwoStacks.java @@ -0,0 +1,67 @@ +import java.util.Stack; + +/** + * This implements Queue using two Stacks. + * + * Big O Runtime: + * insert(): O(1) + * remove(): O(1) amortized + * isEmpty(): O(1) + * + * A queue data structure functions the same as a real world queue. + * The elements that are added first are the first to be removed. + * New elements are added to the back/rear of the queue. + * + * @author sahilb2 + * + */ +class QueueUsingTwoStacks { + + // Stack to keep track of elements inserted into the queue + private Stack inStack; + // Stack to keep track of elements to be removed next in queue + private Stack outStack; + + /** + * Constructor + */ + public QueueUsingTwoStacks() { + this.inStack = new Stack(); + this.outStack = new Stack(); + } + + /** + * Inserts an element at the rear of the queue + * + * @param x element to be added + */ + public void insert(Object x) { + // Insert element into inStack + this.inStack.push(x); + } + + /** + * Remove an element from the front of the queue + * + * @return the new front of the queue + */ + public Object remove() { + if(this.outStack.isEmpty()) { + // Move all elements from inStack to outStack (preserving the order) + while(!this.inStack.isEmpty()) { + this.outStack.push( this.inStack.pop() ); + } + } + return this.outStack.pop(); + } + + /** + * Returns true if the queue is empty + * + * @return true if the queue is empty + */ + public boolean isEmpty() { + return (this.inStack.isEmpty() && this.outStack.isEmpty()); + } + +} From ea164f1ed698e46e9e61c6edcc8d974bd6eca03a Mon Sep 17 00:00:00 2001 From: sahilb2 Date: Thu, 19 Oct 2017 20:40:49 -0500 Subject: [PATCH 30/36] added main and test cases for QueueUsingTwoStacks.java --- Others/QueueUsingTwoStacks.java | 60 +++++++++++++++++++++++++++++++-- 1 file changed, 58 insertions(+), 2 deletions(-) diff --git a/Others/QueueUsingTwoStacks.java b/Others/QueueUsingTwoStacks.java index 34bd4488..19550df8 100644 --- a/Others/QueueUsingTwoStacks.java +++ b/Others/QueueUsingTwoStacks.java @@ -15,7 +15,7 @@ import java.util.Stack; * @author sahilb2 * */ -class QueueUsingTwoStacks { +class QueueWithStack { // Stack to keep track of elements inserted into the queue private Stack inStack; @@ -25,7 +25,7 @@ class QueueUsingTwoStacks { /** * Constructor */ - public QueueUsingTwoStacks() { + public QueueWithStack() { this.inStack = new Stack(); this.outStack = new Stack(); } @@ -65,3 +65,59 @@ class QueueUsingTwoStacks { } } + +/** + * This class is the example for the Queue class + * + * @author sahilb2 + * + */ +public class QueueUsingTwoStacks { + + /** + * Main method + * + * @param args Command line arguments + */ + public static void main(String args[]){ + QueueWithStack myQueue = new QueueWithStack(); + myQueue.insert(1); + // instack: [(top) 1] + // outStack: [] + myQueue.insert(2); + // instack: [(top) 2, 1] + // outStack: [] + myQueue.insert(3); + // instack: [(top) 3, 2, 1] + // outStack: [] + myQueue.insert(4); + // instack: [(top) 4, 3, 2, 1] + // outStack: [] + + System.out.println(myQueue.isEmpty()); //Will print false + + System.out.println(myQueue.remove()); //Will print 1 + // instack: [] + // outStack: [(top) 2, 3, 4] + + myQueue.insert(5); + // instack: [(top) 5] + // outStack: [(top) 2, 3, 4] + + myQueue.remove(); + // instack: [(top) 5] + // outStack: [(top) 3, 4] + myQueue.remove(); + // instack: [(top) 5] + // outStack: [(top) 4] + myQueue.remove(); + // instack: [(top) 5] + // outStack: [] + myQueue.remove(); + // instack: [] + // outStack: [] + + System.out.println(myQueue.isEmpty()); //Will print true + + } +} From 531c7639a6c77dbbd04fc6920d5401a88dac54dd Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sat, 21 Oct 2017 16:44:11 -0700 Subject: [PATCH 31/36] Create StackOfLinkedList.java --- data_structures/Stacks/StackOfLinkedList.java | 98 +++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 data_structures/Stacks/StackOfLinkedList.java diff --git a/data_structures/Stacks/StackOfLinkedList.java b/data_structures/Stacks/StackOfLinkedList.java new file mode 100644 index 00000000..8903e52f --- /dev/null +++ b/data_structures/Stacks/StackOfLinkedList.java @@ -0,0 +1,98 @@ +/** + * + * @author Varun Upadhyay (https://github.com/varunu28) + * + */ + +// An implementation of a Stack using a Linked List + +class StackOfLinkedList { + + public static void main(String[] args) { + + LinkedListStack stack = new LinkedListStack(); + stack.push(1); + stack.push(2); + stack.push(3); + stack.push(4); + + stack.printStack(); + + System.out.println("Size of stack currently is: " + stack.getSize()); + + stack.pop(); + stack.pop(); + + } + +} + +// A node class + +class Node { + public int data; + public Node next; + + public Node(int data) { + this.data = data; + this.next = null; + } +} + +/** + * A class which implements a stack using a linked list + * + * Contains all the stack methods : push, pop, printStack, isEmpty + **/ + +class LinkedListStack { + + Node head = null; + int size = 0; + + public void push(int x) { + Node n = new Node(x); + if (getSize() == 0) { + head = n; + } + else { + Node temp = head; + n.next = temp; + head = n; + } + size++; + } + + public void pop() { + if (getSize() == 0) { + System.out.println("Empty stack. Nothing to pop"); + } + + Node temp = head; + head = head.next; + size--; + + System.out.println("Popped element is: " + temp.data); + } + + public void printStack() { + + Node temp = head; + System.out.println("Stack is printed as below: "); + while (temp != null) { + System.out.print(temp.data + " "); + temp = temp.next; + } + System.out.println(); + + } + + public boolean isEmpty() { + return getSize() == 0; + } + + public int getSize() { + return size; + } + +} From 186c5d0253a2194ef4d19e6df7edcdec93ec6e5a Mon Sep 17 00:00:00 2001 From: MattBizzo Date: Mon, 23 Oct 2017 19:36:37 -0200 Subject: [PATCH 32/36] Adding cocktail sort --- Sorts/CocktailShakerSort.java | 82 +++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 Sorts/CocktailShakerSort.java diff --git a/Sorts/CocktailShakerSort.java b/Sorts/CocktailShakerSort.java new file mode 100644 index 00000000..594ef1bf --- /dev/null +++ b/Sorts/CocktailShakerSort.java @@ -0,0 +1,82 @@ +package Sorts; + +/** + * + * @author Mateus Bizzo (https://github.com/MattBizzo) + * + */ + +class CocktailShakerSort { + /** + * This method implements the Generic Cocktail Shaker Sort + * + * @param array + * The array to be sorted + * @param last + * The count of total number of elements in array Sorts the array in + * increasing order + **/ + + public static > void CS(T array[], int last) { + // Sorting + boolean swap; + do { + swap = false; + //front + for (int count = 0; count <= last - 2; count++) { + int comp = array[count].compareTo(array[count + 1]); + if (comp > 0) { + T aux = array[count]; + array[count] = array[count + 1]; + array[count + 1] = aux; + swap = true; + } + } + if (!swap) { //break if no swap occurred + break; + } + swap = false; + //back + for (int count = last - 2; count >= 0; count--) { + int comp = array[count].compareTo(array[count + 1]); + if (comp > 0) { + T aux = array[count]; + array[count] = array[count + 1]; + array[count + 1] = aux; + swap = true; + } + } + last--; + } while (swap); //end + } + + // Driver Program + public static void main(String[] args) { + // Integer Input + int[] arr1 = { 4, 23, 6, 78, 1, 54, 231, 9, 12 }; + int last = arr1.length; + Integer[] array = new Integer[last]; + for (int i = 0; i < last; i++) { + array[i] = arr1[i]; + } + + CS(array, last); + + // Output => 1 4 6 9 12 23 54 78 231 + for (int i = 0; i < last; i++) { + System.out.print(array[i] + "\t"); + } + System.out.println(); + + // String Input + String[] array1 = { "c", "a", "e", "b", "d" }; + last = array1.length; + + CS(array1, last); + + // Output => a b c d e + for (int i = 0; i < last; i++) { + System.out.print(array1[i] + "\t"); + } + } +} From 9d819349e2780a398303cbcfb303733437008452 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Mon, 23 Oct 2017 15:33:28 -0700 Subject: [PATCH 33/36] Delete InsertionSortInteger.java Solves #84 --- Sorts/InsertionSortInteger.java | 61 --------------------------------- 1 file changed, 61 deletions(-) delete mode 100644 Sorts/InsertionSortInteger.java diff --git a/Sorts/InsertionSortInteger.java b/Sorts/InsertionSortInteger.java deleted file mode 100644 index fa31ac25..00000000 --- a/Sorts/InsertionSortInteger.java +++ /dev/null @@ -1,61 +0,0 @@ -/** - * This is my implementation of an insertion sort. - * - * I decided to do this when i didn't feel comfortable enough about implementing - * different types of sorts, so this is my trial and error to try and get myself to implement - * the various sorts correctly. - * - * @author Kody C. Kendall - * - */ -public class InsertionSortInteger { - - - /** - * This method implements insertion sort by integer - * - * @param initialArray array to be sorted - * @return sorted array - */ - public int[] insertionIntArraySort(int[] initialArray){ - - int[] sortedArray = new int[initialArray.length]; - - //Marking first element as sorted. - sortedArray[0] = initialArray[0]; - - //For each element in the initialArray - for (int index = 1; index < initialArray.length; index++){ - - //Finding the last index that was sorted - int lastSortedIndex = index; - - //Extracting the next element to be compared w/ other sorted elements from initial array - int extractedElement = initialArray[index]; - - //Compare the values of the sorted index to the current extractedElement - for (lastSortedIndex = index; lastSortedIndex > 0; lastSortedIndex--){ - - //If our extracted element is smaller than element to the right, switch them. - if (sortedArray[lastSortedIndex-1] > extractedElement){ - //move the element to the left of extractedElement to the right in sortedArray - sortedArray[lastSortedIndex] = sortedArray[lastSortedIndex-1]; - //And move the current extractedElement to the left one (since it's smaller). - sortedArray[lastSortedIndex-1] = extractedElement; - } - else{ - //insert element where it is. - sortedArray[lastSortedIndex] = extractedElement; - //Terminating loop since element is in the right spot. - break; - } - - } - - } - - return sortedArray; - - } - -} From 952accaf4808a3439dbf5104393d03b4795a63d9 Mon Sep 17 00:00:00 2001 From: MattBizzo Date: Mon, 23 Oct 2017 21:01:02 -0200 Subject: [PATCH 34/36] Code changes by request --- Sorts/CocktailShakerSort.java | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/Sorts/CocktailShakerSort.java b/Sorts/CocktailShakerSort.java index 594ef1bf..4db840d9 100644 --- a/Sorts/CocktailShakerSort.java +++ b/Sorts/CocktailShakerSort.java @@ -1,4 +1,3 @@ -package Sorts; /** * @@ -18,10 +17,12 @@ class CocktailShakerSort { **/ public static > void CS(T array[], int last) { + // Sorting boolean swap; do { swap = false; + //front for (int count = 0; count <= last - 2; count++) { int comp = array[count].compareTo(array[count + 1]); @@ -32,10 +33,12 @@ class CocktailShakerSort { swap = true; } } - if (!swap) { //break if no swap occurred + //break if no swap occurred + if (!swap) { break; } swap = false; + //back for (int count = last - 2; count >= 0; count--) { int comp = array[count].compareTo(array[count + 1]); @@ -47,7 +50,8 @@ class CocktailShakerSort { } } last--; - } while (swap); //end + //end + } while (swap); } // Driver Program From 851432fe870be4218433703c0752cf1757dcdd60 Mon Sep 17 00:00:00 2001 From: Nguyen Duy Tiep Date: Tue, 24 Oct 2017 20:39:11 +0800 Subject: [PATCH 35/36] RSA encryption --- ciphers/RSA.java | 62 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 ciphers/RSA.java diff --git a/ciphers/RSA.java b/ciphers/RSA.java new file mode 100644 index 00000000..5baa61b0 --- /dev/null +++ b/ciphers/RSA.java @@ -0,0 +1,62 @@ +package ciphers; + +import java.math.BigInteger; +import java.security.SecureRandom; + +/** + * Created by Nguyen Duy Tiep on 23-Oct-17. + */ +public class RSA { + private BigInteger modulus, privateKey, publicKey; + + public RSA(int bits) { + generateKeys(bits); + } + + public synchronized String encrypt(String message) { + return (new BigInteger(message.getBytes())).modPow(publicKey, modulus).toString(); + } + + public synchronized BigInteger encrypt(BigInteger message) { + return message.modPow(publicKey, modulus); + } + + public synchronized String decrypt(String message) { + return new String((new BigInteger(message)).modPow(privateKey, modulus).toByteArray()); + } + + public synchronized BigInteger decrypt(BigInteger message) { + return message.modPow(privateKey, modulus); + } + + /** Generate a new public and private key set. */ + public synchronized void generateKeys(int bits) { + SecureRandom r = new SecureRandom(); + BigInteger p = new BigInteger(bits / 2, 100, r); + BigInteger q = new BigInteger(bits / 2, 100, r); + modulus = p.multiply(q); + + BigInteger m = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE)); + + publicKey = new BigInteger("3"); + + while (m.gcd(publicKey).intValue() > 1) { + publicKey = publicKey.add(new BigInteger("2")); + } + + privateKey = publicKey.modInverse(m); + } + + /** Trivial test program. */ + public static void main(String[] args) { + RSA rsa = new RSA(1024); + + String text1 = "This is a message"; + System.out.println("Plaintext: " + text1); + + String ciphertext = rsa.encrypt(text1); + System.out.println("Ciphertext: " + ciphertext); + + System.out.println("Plaintext: " + rsa.decrypt(ciphertext)); + } +} From 87b1f77e565cc18411c5017927c4a0d220afab9e Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Tue, 24 Oct 2017 10:37:46 -0700 Subject: [PATCH 36/36] Update and rename ft.java to FloydTriangle.java --- Others/{ft.java => FloydTriangle.java} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename Others/{ft.java => FloydTriangle.java} (94%) diff --git a/Others/ft.java b/Others/FloydTriangle.java similarity index 94% rename from Others/ft.java rename to Others/FloydTriangle.java index 815dbd29..243a4b1a 100644 --- a/Others/ft.java +++ b/Others/FloydTriangle.java @@ -1,7 +1,7 @@ import java.util.Scanner; -class FloydTriangle { +public class FloydTriangle { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the number of rows which you want in your Floyd Triangle: ");