From a23bac99e82831437ad39fe7c4a1b350110ea136 Mon Sep 17 00:00:00 2001 From: shellhub Date: Sat, 24 Oct 2020 18:22:35 +0800 Subject: [PATCH 1/2] support google java style --- .github/workflows/checkstyle.yml | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 .github/workflows/checkstyle.yml diff --git a/.github/workflows/checkstyle.yml b/.github/workflows/checkstyle.yml new file mode 100644 index 000000000000..1f9393690d2a --- /dev/null +++ b/.github/workflows/checkstyle.yml @@ -0,0 +1,24 @@ +name: Code Formatter + +on: [push] + +jobs: + format: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-python@v2 + - name: Set up JDK 12 + uses: actions/setup-java@v1 + with: + java-version: 12 + - run: wget https://github.com/google/google-java-format/releases/download/google-java-format-1.9/google-java-format-1.9-all-deps.jar -O formatter.jar + - run: java -jar formatter.jar --replace --set-exit-if-changed $(find . -type f -name "*.java") + - name: Commit Format changes + if: failure() + run: | + git config --global user.name github-actions + git config --global user.email '${GITHUB_ACTOR}@users.noreply.github.com' + git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY + git commit -am "Formatted with Google Java Formatter" + git push --force origin HEAD:$GITHUB_REF \ No newline at end of file From 5d59a2e828de8e9d4ba48001d39cc50805de30cd Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 24 Oct 2020 10:23:28 +0000 Subject: [PATCH 2/2] Formatted with Google Java Formatter --- Conversions/AnyBaseToAnyBase.java | 212 ++- Conversions/AnyBaseToDecimal.java | 82 +- Conversions/AnytoAny.java | 44 +- Conversions/BinaryToDecimal.java | 41 +- Conversions/BinaryToHexadecimal.java | 82 +- Conversions/BinaryToOctal.java | 69 +- Conversions/DecimalToAnyBase.java | 98 +- Conversions/DecimalToBinary.java | 87 +- Conversions/DecimalToHexaDecimal.java | 55 +- Conversions/DecimalToOctal.java | 46 +- Conversions/HexToOct.java | 106 +- Conversions/HexaDecimalToBinary.java | 45 +- Conversions/HexaDecimalToDecimal.java | 53 +- Conversions/IntegerToRoman.java | 58 +- Conversions/OctalToDecimal.java | 70 +- Conversions/OctalToHexadecimal.java | 91 +- Conversions/RomanToInteger.java | 94 +- DataStructures/Bags/Bag.java | 178 ++- DataStructures/Buffers/CircularBuffer.java | 204 ++- DataStructures/DynamicArray/DynamicArray.java | 350 ++--- DataStructures/Graphs/A_Star.java | 280 ++-- DataStructures/Graphs/BellmanFord.java | 288 ++-- DataStructures/Graphs/ConnectedComponent.java | 208 ++- DataStructures/Graphs/Cycles.java | 139 +- DataStructures/Graphs/FloydWarshall.java | 122 +- DataStructures/Graphs/Graphs.java | 212 ++- DataStructures/Graphs/Kruskal.java | 163 +-- DataStructures/Graphs/MatrixGraphs.java | 238 ++-- DataStructures/Graphs/PrimMST.java | 182 ++- DataStructures/HashMap/Hashing/HashMap.java | 259 ++-- .../HashMap/Hashing/HashMapLinearProbing.java | 353 ++--- DataStructures/HashMap/Hashing/Main.java | 81 +- .../HashMap/Hashing/MainLinearProbing.java | 107 +- DataStructures/Heaps/EmptyHeapException.java | 10 +- DataStructures/Heaps/Heap.java | 58 +- DataStructures/Heaps/HeapElement.java | 240 ++-- DataStructures/Heaps/MaxHeap.java | 194 +-- DataStructures/Heaps/MinHeap.java | 184 +-- DataStructures/Heaps/MinPriorityQueue.java | 220 ++- DataStructures/Lists/CircleLinkedList.java | 102 +- .../Lists/CountSinglyLinkedListRecursion.java | 38 +- DataStructures/Lists/CursorLinkedList.java | 292 ++-- DataStructures/Lists/DoublyLinkedList.java | 592 ++++---- .../Lists/MergeSortedArrayList.java | 94 +- .../Lists/MergeSortedSinglyLinkedList.java | 80 +- .../Lists/Merge_K_SortedLinkedlist.java | 84 +- .../SearchSinglyLinkedListRecursion.java | 47 +- DataStructures/Lists/SinglyLinkedList.java | 584 ++++---- .../Queues/GenericArrayListQueue.java | 132 +- DataStructures/Queues/LinkedQueue.java | 286 ++-- DataStructures/Queues/PriorityQueues.java | 196 ++- DataStructures/Queues/Queues.java | 307 ++--- DataStructures/Stacks/BalancedBrackets.java | 125 +- .../Stacks/DecimalToAnyUsingStack.java | 68 +- DataStructures/Stacks/NodeStack.java | 319 +++-- DataStructures/Stacks/StackArray.java | 299 ++-- DataStructures/Stacks/StackArrayList.java | 178 ++- DataStructures/Stacks/StackOfLinkedList.java | 219 ++- DataStructures/Trees/AVLTree.java | 372 +++-- DataStructures/Trees/BinaryTree.java | 445 +++--- DataStructures/Trees/GenericTree.java | 426 +++--- DataStructures/Trees/LevelOrderTraversal.java | 86 +- .../Trees/LevelOrderTraversalQueue.java | 71 +- DataStructures/Trees/PrintTopViewofTree.java | 146 +- DataStructures/Trees/RedBlackBST.java | 578 ++++---- DataStructures/Trees/TreeTraversal.java | 184 ++- DataStructures/Trees/TrieImp.java | 212 ++- DataStructures/Trees/ValidBSTOrNot.java | 68 +- DynamicProgramming/BoardPath.java | 100 +- DynamicProgramming/CoinChange.java | 127 +- DynamicProgramming/EditDistance.java | 127 +- DynamicProgramming/EggDropping.java | 62 +- DynamicProgramming/Fibonacci.java | 159 +-- DynamicProgramming/FordFulkerson.java | 114 +- DynamicProgramming/KadaneAlgorithm.java | 77 +- DynamicProgramming/Knapsack.java | 53 +- DynamicProgramming/LevenshteinDistance.java | 86 +- .../LongestCommonSubsequence.java | 100 +- .../LongestIncreasingSubsequence.java | 84 +- .../LongestPalindromicSubsequence.java | 95 +- .../LongestValidParentheses.java | 83 +- .../MatrixChainMultiplication.java | 225 ++- DynamicProgramming/MinimumSumPartition.java | 131 +- DynamicProgramming/RodCutting.java | 41 +- DynamicProgramming/SubsetSum.java | 72 +- Maths/AbsoluteMax.java | 47 +- Maths/AbsoluteMin.java | 47 +- Maths/AbsoluteValue.java | 33 +- Maths/AliquotSum.java | 51 +- Maths/AmicableNumber.java | 144 +- Maths/Area.java | 230 ++-- Maths/Armstrong.java | 69 +- Maths/Average.java | 74 +- Maths/Ceil.java | 42 +- Maths/Combinations.java | 58 +- Maths/Factorial.java | 41 +- Maths/FactorialRecursion.java | 38 +- Maths/FibonacciNumber.java | 60 +- Maths/FindMax.java | 54 +- Maths/FindMaxRecursion.java | 82 +- Maths/FindMin.java | 54 +- Maths/FindMinRecursion.java | 90 +- Maths/Floor.java | 42 +- Maths/GCD.java | 86 +- Maths/GCDRecursion.java | 52 +- Maths/LucasSeries.java | 73 +- Maths/MaxValue.java | 47 +- Maths/Median.java | 42 +- Maths/MinValue.java | 47 +- Maths/Mode.java | 96 +- Maths/NumberOfDigits.java | 103 +- Maths/PalindromeNumber.java | 46 +- Maths/ParseInteger.java | 54 +- Maths/PerfectCube.java | 41 +- Maths/PerfectNumber.java | 49 +- Maths/PerfectSquare.java | 40 +- Maths/Pow.java | 41 +- Maths/PowRecursion.java | 35 +- Maths/PowerOfTwoOrNot.java | 39 +- Maths/PrimeCheck.java | 56 +- Maths/PrimeFactorization.java | 48 +- Maths/PythagoreanTriple.java | 54 +- Maths/SumOfArithmeticSeries.java | 58 +- Maths/SumOfDigits.java | 96 +- Maths/VampireNumber.java | 132 +- MinimizingLateness/MinimizingLateness.java | 87 +- Misc/MedianOfRunningArray.java | 78 +- Misc/PalindromePrime.java | 68 +- Others/BestFit.java | 159 +-- Others/BrianKernighanAlgorithm.java | 65 +- Others/CRC32.java | 38 +- Others/CRCAlgorithm.java | 338 +++-- Others/CountChar.java | 32 +- Others/CountWords.java | 62 +- Others/Dijkstra.java | 351 +++-- Others/EulersFunction.java | 35 +- Others/FibToN.java | 42 +- Others/FirstFit.java | 120 +- Others/FloydTriangle.java | 23 +- Others/GuassLegendre.java | 59 +- Others/InsertDeleteInArray.java | 75 +- Others/KMP.java | 100 +- Others/Krishnamurthy.java | 41 +- Others/LinearCongruentialGenerator.java | 90 +- Others/LowestBasePalindrome.java | 237 ++-- Others/PasswordGen.java | 53 +- Others/PerlinNoise.java | 293 ++-- Others/QueueUsingTwoStacks.java | 260 ++-- Others/RabinKarp.java | 127 +- Others/RemoveDuplicateFromString.java | 65 +- Others/ReturnSubsequence.java | 77 +- Others/ReverseStackUsingRecursion.java | 87 +- Others/RootPrecision.java | 46 +- Others/SJF.java | 280 ++-- Others/SieveOfEratosthenes.java | 65 +- Others/SkylineProblem.java | 195 ++- Others/StackPostfixNotation.java | 62 +- Others/StringMatchFiniteAutomata.java | 168 ++- Others/ThreeSum.java | 85 +- Others/TopKWords.java | 131 +- Others/TowerOfHanoi.java | 34 +- Others/TwoPointers.java | 72 +- Others/WorstFit.java | 134 +- ProjectEuler/Problem01.java | 78 +- ProjectEuler/Problem02.java | 66 +- ProjectEuler/Problem04.java | 62 +- ProjectEuler/Problem06.java | 68 +- ProjectEuler/Problem07.java | 97 +- ProjectEuler/Problem09.java | 40 +- ProjectEuler/Problem10.java | 86 +- ProjectEuler/Problem12.java | 94 +- Searches/BinarySearch.java | 132 +- Searches/InterpolationSearch.java | 115 +- Searches/IterativeBinarySearch.java | 122 +- Searches/IterativeTernarySearch.java | 113 +- Searches/JumpSearch.java | 59 +- Searches/LinearSearch.java | 85 +- Searches/PerfectBinarySearch.java | 47 +- Searches/SaddlebackSearch.java | 119 +- Searches/SearchAlgorithm.java | 17 +- Searches/TernarySearch.java | 152 +-- Sorts/BitonicSort.java | 130 +- Sorts/BogoSort.java | 60 +- Sorts/BubbleSort.java | 68 +- Sorts/BubbleSortRecursion.java | 82 +- Sorts/BucketSort.java | 185 ++- Sorts/CocktailShakerSort.java | 98 +- Sorts/CombSort.java | 94 +- Sorts/CountingSort.java | 163 ++- Sorts/CycleSort.java | 104 +- Sorts/GnomeSort.java | 51 +- Sorts/HeapSort.java | 196 ++- Sorts/InsertionSort.java | 73 +- Sorts/MergeSort.java | 144 +- Sorts/PancakeSort.java | 55 +- Sorts/QuickSort.java | 162 ++- Sorts/RadixSort.java | 70 +- Sorts/SelectionSort.java | 95 +- Sorts/ShellSort.java | 58 +- Sorts/SortAlgorithm.java | 37 +- Sorts/SortUtils.java | 132 +- ciphers/AES.java | 1207 +++++++++-------- ciphers/AESEncryption.java | 193 ++- ciphers/Caesar.java | 199 ++- ciphers/ColumnarTranspositionCipher.java | 362 +++-- ciphers/RSA.java | 150 +- ciphers/SimpleSubstitutionCipher.java | 138 +- ciphers/Vigenere.java | 90 +- divideconquer/ClosestPair.java | 642 ++++----- divideconquer/SkylineAlgorithm.java | 295 ++-- strings/Alphabetical.java | 52 +- strings/CharactersSame.java | 42 +- strings/CheckAnagrams.java | 46 +- strings/Lower.java | 42 +- strings/Palindrome.java | 104 +- strings/Pangram.java | 58 +- strings/ReverseString.java | 67 +- strings/Rotation.java | 100 +- strings/Upper.java | 42 +- 219 files changed, 13754 insertions(+), 14578 deletions(-) diff --git a/Conversions/AnyBaseToAnyBase.java b/Conversions/AnyBaseToAnyBase.java index 8ecc79904c11..2fc4499a0526 100644 --- a/Conversions/AnyBaseToAnyBase.java +++ b/Conversions/AnyBaseToAnyBase.java @@ -6,130 +6,122 @@ import java.util.Scanner; /** - * 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. + * 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.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; + /** Smallest and largest base you want to accept as valid input */ + static final int MINIMUM_BASE = 2; - public static void main(String[] args) { - Scanner in = new Scanner(System.in); - String n; - int b1, b2; - while (true) { - try { - System.out.print("Enter number: "); - n = in.next(); - System.out.print("Enter beginning base (between " + MINIMUM_BASE + " and " + MAXIMUM_BASE + "): "); - b1 = in.nextInt(); - 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."); - in.next(); - } + static final int MAXIMUM_BASE = 36; + + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + String n; + int b1, b2; + while (true) { + try { + System.out.print("Enter number: "); + n = in.next(); + System.out.print( + "Enter beginning base (between " + MINIMUM_BASE + " and " + MAXIMUM_BASE + "): "); + b1 = in.nextInt(); + 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.println(base2base(n, b1, b2)); - in.close(); + 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."); + in.next(); + } } + System.out.println(base2base(n, b1, b2)); + in.close(); + } - /** - * 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); + /** 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 < digitsForBase.length; i++) - digitsList.add(digitsForBase[i]); + // Convert character array into set for convenience of contains() method + HashSet digitsList = new HashSet<>(); + for (int i = 0; i < digitsForBase.length; i++) digitsList.add(digitsForBase[i]); - // Check that every digit in n is within the list of valid digits for that base. - for (char c : n.toCharArray()) - if (!digitsList.contains(c)) - return false; + // Check that every digit in n is within the list of valid digits for that base. + for (char c : n.toCharArray()) if (!digitsList.contains(c)) return false; - return true; - } + return true; + } - /** - * 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; i < n.length(); i++) { - // store the character in charB1 - charB1 = n.charAt(i); - // if it is a non-number, convert it to a decimal value >9 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; - } + /** + * 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; i < n.length(); i++) { + // store the character in charB1 + charB1 = n.charAt(i); + // if it is a non-number, convert it to a decimal value >9 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. - if (0 == decimalValue) - return "0"; - // 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; + // 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. + if (0 == decimalValue) return "0"; + // 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; + } } diff --git a/Conversions/AnyBaseToDecimal.java b/Conversions/AnyBaseToDecimal.java index 6b4a680a06da..61b1a82f0ea3 100644 --- a/Conversions/AnyBaseToDecimal.java +++ b/Conversions/AnyBaseToDecimal.java @@ -1,53 +1,51 @@ package Conversions; -/** - * @author Varun Upadhyay (https://github.com/varunu28) - */ +/** @author Varun Upadhyay (https://github.com/varunu28) */ // Driver program public class AnyBaseToDecimal { - public static void main(String[] args) { - assert convertToDecimal("1010", 2) == Integer.valueOf("1010", 2); - assert convertToDecimal("777", 8) == Integer.valueOf("777", 8); - assert convertToDecimal("999", 10) == Integer.valueOf("999", 10); - assert convertToDecimal("ABCDEF", 16) == Integer.valueOf("ABCDEF", 16); - assert convertToDecimal("XYZ", 36) == Integer.valueOf("XYZ", 36); - } + public static void main(String[] args) { + assert convertToDecimal("1010", 2) == Integer.valueOf("1010", 2); + assert convertToDecimal("777", 8) == Integer.valueOf("777", 8); + assert convertToDecimal("999", 10) == Integer.valueOf("999", 10); + assert convertToDecimal("ABCDEF", 16) == Integer.valueOf("ABCDEF", 16); + assert convertToDecimal("XYZ", 36) == Integer.valueOf("XYZ", 36); + } - /** - * Convert any radix to decimal number - * - * @param s the string to be convert - * @param radix the radix - * @return decimal of bits - * @throws NumberFormatException if {@code bits} or {@code radix} is invalid - */ - public static int convertToDecimal(String s, int radix) { - int num = 0; - int pow = 1; + /** + * Convert any radix to decimal number + * + * @param s the string to be convert + * @param radix the radix + * @return decimal of bits + * @throws NumberFormatException if {@code bits} or {@code radix} is invalid + */ + public static int convertToDecimal(String s, int radix) { + int num = 0; + int pow = 1; - for (int i = s.length() - 1; i >= 0; i--) { - int digit = valOfChar(s.charAt(i)); - if (digit >= radix) { - throw new NumberFormatException("For input string " + s); - } - num += valOfChar(s.charAt(i)) * pow; - pow *= radix; - } - return num; + for (int i = s.length() - 1; i >= 0; i--) { + int digit = valOfChar(s.charAt(i)); + if (digit >= radix) { + throw new NumberFormatException("For input string " + s); + } + num += valOfChar(s.charAt(i)) * pow; + pow *= radix; } + return num; + } - /** - * Convert character to integer - * - * @param c the character - * @return represented digit of given character - * @throws NumberFormatException if {@code ch} is not UpperCase or Digit character. - */ - public static int valOfChar(char c) { - if (!(Character.isUpperCase(c) || Character.isDigit(c))) { - throw new NumberFormatException("invalid character :" + c); - } - return Character.isDigit(c) ? c - '0' : c - 'A' + 10; + /** + * Convert character to integer + * + * @param c the character + * @return represented digit of given character + * @throws NumberFormatException if {@code ch} is not UpperCase or Digit character. + */ + public static int valOfChar(char c) { + if (!(Character.isUpperCase(c) || Character.isDigit(c))) { + throw new NumberFormatException("invalid character :" + c); } + return Character.isDigit(c) ? c - '0' : c - 'A' + 10; + } } diff --git a/Conversions/AnytoAny.java b/Conversions/AnytoAny.java index 1bc115404696..c213513171ef 100644 --- a/Conversions/AnytoAny.java +++ b/Conversions/AnytoAny.java @@ -1,30 +1,30 @@ package Conversions; import java.util.Scanner; -//given a source number , source base, destination base, this code can give you the destination number. -//sn ,sb,db ---> ()dn . this is what we have to do . +// given a source number , source base, destination base, this code can give you the destination +// number. +// sn ,sb,db ---> ()dn . this is what we have to do . public class AnytoAny { - public static void main(String[] args) { - Scanner scn = new Scanner(System.in); - int sn = scn.nextInt(); - int sb = scn.nextInt(); - int db = scn.nextInt(); - int m = 1, dec = 0, dn = 0; - while (sn != 0) { - dec = dec + (sn % 10) * m; - m *= sb; - sn /= 10; - } - m = 1; - while (dec != 0) { - dn = dn + (dec % db) * m; - m *= 10; - dec /= db; - } - System.out.println(dn); - scn.close(); + public static void main(String[] args) { + Scanner scn = new Scanner(System.in); + int sn = scn.nextInt(); + int sb = scn.nextInt(); + int db = scn.nextInt(); + int m = 1, dec = 0, dn = 0; + while (sn != 0) { + dec = dec + (sn % 10) * m; + m *= sb; + sn /= 10; } - + m = 1; + while (dec != 0) { + dn = dn + (dec % db) * m; + m *= 10; + dec /= db; + } + System.out.println(dn); + scn.close(); + } } diff --git a/Conversions/BinaryToDecimal.java b/Conversions/BinaryToDecimal.java index 6db926d3b932..beb71af5107d 100644 --- a/Conversions/BinaryToDecimal.java +++ b/Conversions/BinaryToDecimal.java @@ -2,29 +2,26 @@ import java.util.Scanner; -/** - * This class converts a Binary number to a Decimal number - * - */ +/** This class converts a Binary number to a Decimal number */ class BinaryToDecimal { - /** - * Main Method - * - * @param args Command line arguments - */ - public static void main(String args[]) { - Scanner sc = new Scanner(System.in); - int binNum, binCopy, d, s = 0, power = 0; - System.out.print("Binary number: "); - binNum = sc.nextInt(); - binCopy = binNum; - while (binCopy != 0) { - d = binCopy % 10; - s += d * (int) Math.pow(2, power++); - binCopy /= 10; - } - System.out.println("Decimal equivalent:" + s); - sc.close(); + /** + * Main Method + * + * @param args Command line arguments + */ + public static void main(String args[]) { + Scanner sc = new Scanner(System.in); + int binNum, binCopy, d, s = 0, power = 0; + System.out.print("Binary number: "); + binNum = sc.nextInt(); + binCopy = binNum; + while (binCopy != 0) { + d = binCopy % 10; + s += d * (int) Math.pow(2, power++); + binCopy /= 10; } + System.out.println("Decimal equivalent:" + s); + sc.close(); + } } diff --git a/Conversions/BinaryToHexadecimal.java b/Conversions/BinaryToHexadecimal.java index d923c1d8041d..c5ff3298fd03 100644 --- a/Conversions/BinaryToHexadecimal.java +++ b/Conversions/BinaryToHexadecimal.java @@ -9,47 +9,47 @@ */ public class BinaryToHexadecimal { - /** - * This method converts a binary number to - * a hexadecimal number. - * - * @param binary The binary number - * @return The hexadecimal number - */ - static String binToHex(int binary) { - //hm to store hexadecimal codes for binary numbers within the range: 0000 to 1111 i.e. for decimal numbers 0 to 15 - HashMap hm = new HashMap<>(); - //String to store hexadecimal code - String hex = ""; - int i; - for (i = 0; i < 10; i++) { - hm.put(i, String.valueOf(i)); - } - for (i = 10; i < 16; i++) hm.put(i, String.valueOf((char) ('A' + i - 10))); - int currbit; - while (binary != 0) { - int code4 = 0; //to store decimal equivalent of number formed by 4 decimal digits - for (i = 0; i < 4; i++) { - currbit = binary % 10; - binary = binary / 10; - code4 += currbit * Math.pow(2, i); - } - hex = hm.get(code4) + hex; - } - return hex; + /** + * This method converts a binary number to a hexadecimal number. + * + * @param binary The binary number + * @return The hexadecimal number + */ + static String binToHex(int binary) { + // hm to store hexadecimal codes for binary numbers within the range: 0000 to 1111 i.e. for + // decimal numbers 0 to 15 + HashMap hm = new HashMap<>(); + // String to store hexadecimal code + String hex = ""; + int i; + for (i = 0; i < 10; i++) { + hm.put(i, String.valueOf(i)); } - - /** - * Main method - * - * @param args Command line arguments - */ - public static void main(String[] args) { - Scanner sc = new Scanner(System.in); - System.out.println("Enter binary number:"); - int binary = sc.nextInt(); - String hex = binToHex(binary); - System.out.println("Hexadecimal Code:" + hex); - sc.close(); + for (i = 10; i < 16; i++) hm.put(i, String.valueOf((char) ('A' + i - 10))); + int currbit; + while (binary != 0) { + int code4 = 0; // to store decimal equivalent of number formed by 4 decimal digits + for (i = 0; i < 4; i++) { + currbit = binary % 10; + binary = binary / 10; + code4 += currbit * Math.pow(2, i); + } + hex = hm.get(code4) + hex; } + return hex; + } + + /** + * Main method + * + * @param args Command line arguments + */ + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + System.out.println("Enter binary number:"); + int binary = sc.nextInt(); + String hex = binToHex(binary); + System.out.println("Hexadecimal Code:" + hex); + sc.close(); + } } diff --git a/Conversions/BinaryToOctal.java b/Conversions/BinaryToOctal.java index 833ab3a221f7..1ea555e42916 100644 --- a/Conversions/BinaryToOctal.java +++ b/Conversions/BinaryToOctal.java @@ -9,42 +9,39 @@ */ public class BinaryToOctal { - /** - * Main method - * - * @param args Command line arguments - */ - public static void main(String args[]) { - Scanner sc = new Scanner(System.in); - System.out.println("Input the binary number: "); - int b = sc.nextInt(); - System.out.println("Octal equivalent: " + convertBinaryToOctal(b)); - sc.close(); + /** + * Main method + * + * @param args Command line arguments + */ + public static void main(String args[]) { + Scanner sc = new Scanner(System.in); + System.out.println("Input the binary number: "); + int b = sc.nextInt(); + System.out.println("Octal equivalent: " + convertBinaryToOctal(b)); + sc.close(); + } + /** + * This method converts a binary number to an octal number. + * + * @param binary The binary number + * @return The octal number + */ + public static String convertBinaryToOctal(int binary) { + String octal = ""; + int currBit = 0, j = 1; + while (binary != 0) { + int code3 = 0; + for (int i = 0; i < 3; i++) { + currBit = binary % 10; + binary = binary / 10; + code3 += currBit * j; + j *= 2; + } + octal = code3 + octal; + j = 1; } - - /** - * This method converts a binary number to - * an octal number. - * - * @param binary The binary number - * @return The octal number - */ - public static String convertBinaryToOctal(int binary) { - String octal = ""; - int currBit = 0, j = 1; - while (binary != 0) { - int code3 = 0; - for (int i = 0; i < 3; i++) { - currBit = binary % 10; - binary = binary / 10; - code3 += currBit * j; - j *= 2; - } - octal = code3 + octal; - j = 1; - } - return octal; - } - + return octal; + } } diff --git a/Conversions/DecimalToAnyBase.java b/Conversions/DecimalToAnyBase.java index 4b23fc6bbef3..127cc22c0ce7 100644 --- a/Conversions/DecimalToAnyBase.java +++ b/Conversions/DecimalToAnyBase.java @@ -4,64 +4,58 @@ import java.io.InputStreamReader; import java.util.ArrayList; -/** - * - * @author Varun Upadhyay (https://github.com/varunu28) - * - */ +/** @author Varun Upadhyay (https://github.com/varunu28) */ // Driver Program public class DecimalToAnyBase { - public static void main (String[] args) throws Exception{ - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - System.out.println("Enter the decimal input below: "); - int decInput = Integer.parseInt(br.readLine()); - System.out.println(); - - System.out.println("Enter the base below: "); - int base = Integer.parseInt(br.readLine()); - System.out.println(); - - System.out.println("Decimal Input" + " is: " + decInput); - System.out.println("Value of " + decInput + " in base " + base + " is: " + convertToAnyBase(decInput, base)); - - br.close(); + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + System.out.println("Enter the decimal input below: "); + int decInput = Integer.parseInt(br.readLine()); + System.out.println(); + + System.out.println("Enter the base below: "); + int base = Integer.parseInt(br.readLine()); + System.out.println(); + + System.out.println("Decimal Input" + " is: " + decInput); + System.out.println( + "Value of " + decInput + " in base " + base + " is: " + convertToAnyBase(decInput, base)); + + br.close(); + } + + /** + * This method produces a String value of any given input decimal in any base + * + * @param inp Decimal of which we need the value in base in String format + * @return string format of the converted value in the given base + */ + public static String convertToAnyBase(int inp, int base) { + ArrayList charArr = new ArrayList<>(); + + while (inp > 0) { + charArr.add(reVal(inp % base)); + inp /= base; } - /** - * This method produces a String value of any given input decimal in any base - * @param inp Decimal of which we need the value in base in String format - * @return string format of the converted value in the given base - */ - - public static String convertToAnyBase(int inp, int base) { - ArrayList charArr = new ArrayList<>(); - - while (inp > 0) { - charArr.add(reVal(inp%base)); - inp /= base; - } + StringBuilder str = new StringBuilder(charArr.size()); - StringBuilder str = new StringBuilder(charArr.size()); - - for(Character ch: charArr) - { - str.append(ch); - } - - return str.reverse().toString(); + for (Character ch : charArr) { + str.append(ch); } - /** - * This method produces character value of the input integer and returns it - * @param num integer of which we need the character value of - * @return character value of input integer - */ - - public static char reVal(int num) { - if (num >= 0 && num <= 9) - return (char)(num + '0'); - else - return (char)(num - 10 + 'A'); - } + return str.reverse().toString(); + } + + /** + * This method produces character value of the input integer and returns it + * + * @param num integer of which we need the character value of + * @return character value of input integer + */ + public static char reVal(int num) { + if (num >= 0 && num <= 9) return (char) (num + '0'); + else return (char) (num - 10 + 'A'); + } } diff --git a/Conversions/DecimalToBinary.java b/Conversions/DecimalToBinary.java index 4dd1ba4f4414..0f79394c79db 100644 --- a/Conversions/DecimalToBinary.java +++ b/Conversions/DecimalToBinary.java @@ -2,59 +2,46 @@ import java.util.Scanner; -/** - * This class converts a Decimal number to a Binary number - * - * - */ +/** This class converts a Decimal number to a Binary number */ class DecimalToBinary { - /** - * Main Method - * - * @param args Command Line Arguments - */ - public static void main(String args[]) { - conventionalConversion(); - bitwiseConversion(); - } + /** + * Main Method + * + * @param args Command Line Arguments + */ + public static void main(String args[]) { + conventionalConversion(); + bitwiseConversion(); + } - /** - * This method converts a decimal number - * to a binary number using a conventional - * algorithm. - */ - public static void conventionalConversion() { - int n, b = 0, c = 0, d; - Scanner input = new Scanner(System.in); - System.out.printf("Conventional conversion.%n Enter the decimal number: "); - n = input.nextInt(); - while (n != 0) { - d = n % 2; - b = b + d * (int) Math.pow(10, c++); - n /= 2; - } //converting decimal to binary - System.out.println("\tBinary number: " + b); - input.close(); - } + /** This method converts a decimal number to a binary number using a conventional algorithm. */ + public static void conventionalConversion() { + int n, b = 0, c = 0, d; + Scanner input = new Scanner(System.in); + System.out.printf("Conventional conversion.%n Enter the decimal number: "); + n = input.nextInt(); + while (n != 0) { + d = n % 2; + b = b + d * (int) Math.pow(10, c++); + n /= 2; + } // converting decimal to binary + System.out.println("\tBinary number: " + b); + input.close(); + } - /** - * This method converts a decimal number - * to a binary number using a bitwise - * algorithm - */ - public static void bitwiseConversion() { - int n, b = 0, c = 0, d; - Scanner input = new Scanner(System.in); - System.out.printf("Bitwise conversion.%n Enter the decimal number: "); - n = input.nextInt(); - while (n != 0) { - d = (n & 1); - b += d * (int) Math.pow(10, c++); - n >>= 1; - } - System.out.println("\tBinary number: " + b); - input.close(); + /** This method converts a decimal number to a binary number using a bitwise algorithm */ + public static void bitwiseConversion() { + int n, b = 0, c = 0, d; + Scanner input = new Scanner(System.in); + System.out.printf("Bitwise conversion.%n Enter the decimal number: "); + n = input.nextInt(); + while (n != 0) { + d = (n & 1); + b += d * (int) Math.pow(10, c++); + n >>= 1; } - + System.out.println("\tBinary number: " + b); + input.close(); + } } diff --git a/Conversions/DecimalToHexaDecimal.java b/Conversions/DecimalToHexaDecimal.java index 3d0351dd0122..21abb681a547 100644 --- a/Conversions/DecimalToHexaDecimal.java +++ b/Conversions/DecimalToHexaDecimal.java @@ -1,32 +1,33 @@ package Conversions; -//hex = [0 - 9] -> [A - F] +// hex = [0 - 9] -> [A - F] class DecimalToHexaDecimal { - private static final int sizeOfIntInHalfBytes = 8; - private static final int numberOfBitsInAHalfByte = 4; - private static final int halfByte = 0x0F; - private static final char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', - 'F' }; + private static final int sizeOfIntInHalfBytes = 8; + private static final int numberOfBitsInAHalfByte = 4; + private static final int halfByte = 0x0F; + private static final char[] hexDigits = { + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' + }; - // Returns the hex value of the dec entered in the parameter. - public static String decToHex(int dec) { - StringBuilder hexBuilder = new StringBuilder(sizeOfIntInHalfBytes); - hexBuilder.setLength(sizeOfIntInHalfBytes); - for (int i = sizeOfIntInHalfBytes - 1; i >= 0; --i) { - int j = dec & halfByte; - hexBuilder.setCharAt(i, hexDigits[j]); - dec >>= numberOfBitsInAHalfByte; - } - return hexBuilder.toString().toLowerCase(); - } + // Returns the hex value of the dec entered in the parameter. + public static String decToHex(int dec) { + StringBuilder hexBuilder = new StringBuilder(sizeOfIntInHalfBytes); + hexBuilder.setLength(sizeOfIntInHalfBytes); + for (int i = sizeOfIntInHalfBytes - 1; i >= 0; --i) { + int j = dec & halfByte; + hexBuilder.setCharAt(i, hexDigits[j]); + dec >>= numberOfBitsInAHalfByte; + } + return hexBuilder.toString().toLowerCase(); + } - // Test above function. - public static void main(String[] args) { - System.out.println("Test..."); - int dec = 305445566; - String libraryDecToHex = Integer.toHexString(dec); - String decToHex = decToHex(dec); - System.out.println("Result from the library : " + libraryDecToHex); - System.out.println("Result decToHex method : " + decToHex); - } -} \ No newline at end of file + // Test above function. + public static void main(String[] args) { + System.out.println("Test..."); + int dec = 305445566; + String libraryDecToHex = Integer.toHexString(dec); + String decToHex = decToHex(dec); + System.out.println("Result from the library : " + libraryDecToHex); + System.out.println("Result decToHex method : " + decToHex); + } +} diff --git a/Conversions/DecimalToOctal.java b/Conversions/DecimalToOctal.java index 98c9f1bb0c48..1a4fa9f75b1c 100644 --- a/Conversions/DecimalToOctal.java +++ b/Conversions/DecimalToOctal.java @@ -2,32 +2,28 @@ import java.util.Scanner; -/** - * This class converts Decimal numbers to Octal Numbers - * - * - */ +/** This class converts Decimal numbers to Octal Numbers */ public class DecimalToOctal { - /** - * Main Method - * - * @param args Command line Arguments - */ + /** + * Main Method + * + * @param args Command line Arguments + */ - //enter in a decimal value to get Octal output - public static void main(String[] args) { - Scanner sc = new Scanner(System.in); - int n, k, d, s = 0, c = 0; - System.out.print("Decimal number: "); - n = sc.nextInt(); - k = n; - while (k != 0) { - d = k % 8; - s += d * (int) Math.pow(10, c++); - k /= 8; - } - - System.out.println("Octal equivalent:" + s); - sc.close(); + // enter in a decimal value to get Octal output + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + int n, k, d, s = 0, c = 0; + System.out.print("Decimal number: "); + n = sc.nextInt(); + k = n; + while (k != 0) { + d = k % 8; + s += d * (int) Math.pow(10, c++); + k /= 8; } + + System.out.println("Octal equivalent:" + s); + sc.close(); + } } diff --git a/Conversions/HexToOct.java b/Conversions/HexToOct.java index 2807735f72fb..c64f549a6fa5 100644 --- a/Conversions/HexToOct.java +++ b/Conversions/HexToOct.java @@ -8,62 +8,66 @@ * @author Tanmay Joshi */ public class HexToOct { - /** - * This method converts a Hexadecimal number to a decimal number - * - * @param s The Hexadecimal Number - * @return The Decimal number - */ - public static int hex2decimal(String s) { - String str = "0123456789ABCDEF"; - s = s.toUpperCase(); - int val = 0; - for (int i = 0; i < s.length(); i++) { - char a = s.charAt(i); - int n = str.indexOf(a); - val = 16 * val + n; - } - return val; + /** + * This method converts a Hexadecimal number to a decimal number + * + * @param s The Hexadecimal Number + * @return The Decimal number + */ + public static int hex2decimal(String s) { + String str = "0123456789ABCDEF"; + s = s.toUpperCase(); + int val = 0; + for (int i = 0; i < s.length(); i++) { + char a = s.charAt(i); + int n = str.indexOf(a); + val = 16 * val + n; } + return val; + } - /** - * This method converts a Decimal number to a octal number - * - * @param q The Decimal Number - * @return The Octal number - */ - public static int decimal2octal(int q) { - int now; - int i = 1; - int octnum = 0; - while (q > 0) { - now = q % 8; - octnum = (now * (int) (Math.pow(10, i))) + octnum; - q /= 8; - i++; - } - octnum /= 10; - return octnum; + /** + * This method converts a Decimal number to a octal number + * + * @param q The Decimal Number + * @return The Octal number + */ + public static int decimal2octal(int q) { + int now; + int i = 1; + int octnum = 0; + while (q > 0) { + now = q % 8; + octnum = (now * (int) (Math.pow(10, i))) + octnum; + q /= 8; + i++; } + octnum /= 10; + return octnum; + } - /** - * Main method that gets the hex input from user and converts it into octal. - * @param args arguments - */ - public static void main(String args[]) { - String hexadecnum; - int decnum, octalnum; - Scanner scan = new Scanner(System.in); + /** + * Main method that gets the hex input from user and converts it into octal. + * + * @param args arguments + */ + public static void main(String args[]) { + String hexadecnum; + int decnum, octalnum; + Scanner scan = new Scanner(System.in); - System.out.print("Enter Hexadecimal Number : "); - hexadecnum = scan.nextLine(); + System.out.print("Enter Hexadecimal Number : "); + hexadecnum = scan.nextLine(); - // first convert hexadecimal to decimal - decnum = hex2decimal(hexadecnum); //Pass the string to the hex2decimal function and get the decimal form in variable decnum + // first convert hexadecimal to decimal + decnum = + hex2decimal( + hexadecnum); // Pass the string to the hex2decimal function and get the decimal form in + // variable decnum - // convert decimal to octal - octalnum = decimal2octal(decnum); - System.out.println("Number in octal: " + octalnum); - scan.close(); - } + // convert decimal to octal + octalnum = decimal2octal(decnum); + System.out.println("Number in octal: " + octalnum); + scan.close(); + } } diff --git a/Conversions/HexaDecimalToBinary.java b/Conversions/HexaDecimalToBinary.java index 091822ce0cb4..06fbc7efd24a 100644 --- a/Conversions/HexaDecimalToBinary.java +++ b/Conversions/HexaDecimalToBinary.java @@ -1,36 +1,35 @@ package Conversions; -//Hex [0-9],[A-F] -> Binary [0,1] +// Hex [0-9],[A-F] -> Binary [0,1] public class HexaDecimalToBinary { - private final int LONG_BITS = 8; + private final int LONG_BITS = 8; - public void convert(String numHex) { - // String a HexaDecimal: - int conHex = Integer.parseInt(numHex, 16); - // Hex a Binary: - String binary = Integer.toBinaryString(conHex); - // Output: - System.out.println(numHex + " = " + completeDigits(binary)); - } + public void convert(String numHex) { + // String a HexaDecimal: + int conHex = Integer.parseInt(numHex, 16); + // Hex a Binary: + String binary = Integer.toBinaryString(conHex); + // Output: + System.out.println(numHex + " = " + completeDigits(binary)); + } - public String completeDigits(String binNum) { - for (int i = binNum.length(); i < LONG_BITS; i++) { - binNum = "0" + binNum; - } - return binNum; + public String completeDigits(String binNum) { + for (int i = binNum.length(); i < LONG_BITS; i++) { + binNum = "0" + binNum; } + return binNum; + } - public static void main(String[] args) { + public static void main(String[] args) { - //Testing Numbers: - String[] hexNums = {"1", "A1", "ef", "BA", "AA", "BB", - "19", "01", "02", "03", "04"}; - HexaDecimalToBinary objConvert = new HexaDecimalToBinary(); + // Testing Numbers: + String[] hexNums = {"1", "A1", "ef", "BA", "AA", "BB", "19", "01", "02", "03", "04"}; + HexaDecimalToBinary objConvert = new HexaDecimalToBinary(); - for (String num : hexNums) { - objConvert.convert(num); - } + for (String num : hexNums) { + objConvert.convert(num); } + } } diff --git a/Conversions/HexaDecimalToDecimal.java b/Conversions/HexaDecimalToDecimal.java index 14b0d94d76c2..d85177b791bb 100644 --- a/Conversions/HexaDecimalToDecimal.java +++ b/Conversions/HexaDecimalToDecimal.java @@ -4,37 +4,36 @@ public class HexaDecimalToDecimal { - // convert hexadecimal to decimal - public static int getHexaToDec(String hex) { - String digits = "0123456789ABCDEF"; - hex = hex.toUpperCase(); - int val = 0; - for (int i = 0; i < hex.length(); i++) { - int d = digits.indexOf(hex.charAt(i)); - val = 16 * val + d; - } - return val; + // convert hexadecimal to decimal + public static int getHexaToDec(String hex) { + String digits = "0123456789ABCDEF"; + hex = hex.toUpperCase(); + int val = 0; + for (int i = 0; i < hex.length(); i++) { + int d = digits.indexOf(hex.charAt(i)); + val = 16 * val + d; } + return val; + } - // Main method gets the hexadecimal input from user and converts it into Decimal output. - - public static void main(String args[]) { - String hexa_Input; - int dec_output; - Scanner scan = new Scanner(System.in); + // Main method gets the hexadecimal input from user and converts it into Decimal output. - System.out.print("Enter Hexadecimal Number : "); - hexa_Input = scan.nextLine(); + public static void main(String args[]) { + String hexa_Input; + int dec_output; + Scanner scan = new Scanner(System.in); - // convert hexadecimal to decimal + System.out.print("Enter Hexadecimal Number : "); + hexa_Input = scan.nextLine(); - dec_output = getHexaToDec(hexa_Input); - /* - Pass the string to the getHexaToDec function - and it returns the decimal form in the variable dec_output. - */ - System.out.println("Number in Decimal: " + dec_output); - scan.close(); + // convert hexadecimal to decimal - } + dec_output = getHexaToDec(hexa_Input); + /* + Pass the string to the getHexaToDec function + and it returns the decimal form in the variable dec_output. + */ + System.out.println("Number in Decimal: " + dec_output); + scan.close(); + } } diff --git a/Conversions/IntegerToRoman.java b/Conversions/IntegerToRoman.java index 8886ef4ad016..5c039a0f026e 100644 --- a/Conversions/IntegerToRoman.java +++ b/Conversions/IntegerToRoman.java @@ -3,47 +3,37 @@ /** * Converting Integers into Roman Numerals * - *('I', 1); - *('IV',4); - *('V', 5); - *('IV',9); - *('X', 10); - *('XL',40; - *('L', 50); - *('XC',90); - *('C', 100); - *('D', 500); - *('M', 1000); - * + *

('I', 1); ('IV',4); ('V', 5); ('IV',9); ('X', 10); ('XL',40; ('L', 50); ('XC',90); ('C', 100); + * ('D', 500); ('M', 1000); */ - - public class IntegerToRoman { - private static int[] allArabianRomanNumbers = new int[]{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; - private static String[] allRomanNumbers = new String[]{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; - - //Value must be > 0 + private static int[] allArabianRomanNumbers = + new int[] {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; + private static String[] allRomanNumbers = + new String[] {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; - public static String integerToRoman(int num) { - if (num <= 0) { - return ""; - } + // Value must be > 0 - StringBuilder builder = new StringBuilder(); + public static String integerToRoman(int num) { + if (num <= 0) { + return ""; + } - for (int a = 0; a < allArabianRomanNumbers.length; a++) { - int times = num / allArabianRomanNumbers[a]; - for (int b = 0; b < times; b++) { - builder.append(allRomanNumbers[a]); - } + StringBuilder builder = new StringBuilder(); - num -= times * allArabianRomanNumbers[a]; - } + for (int a = 0; a < allArabianRomanNumbers.length; a++) { + int times = num / allArabianRomanNumbers[a]; + for (int b = 0; b < times; b++) { + builder.append(allRomanNumbers[a]); + } - return builder.toString(); + num -= times * allArabianRomanNumbers[a]; } - public static void main(String[] args) { - System.out.println(IntegerToRoman.integerToRoman(2131)); - } + return builder.toString(); + } + + public static void main(String[] args) { + System.out.println(IntegerToRoman.integerToRoman(2131)); + } } diff --git a/Conversions/OctalToDecimal.java b/Conversions/OctalToDecimal.java index 3b8c996bc200..1f3ad662a3bc 100644 --- a/Conversions/OctalToDecimal.java +++ b/Conversions/OctalToDecimal.java @@ -4,46 +4,42 @@ /** * Converts any Octal Number to a Decimal Number - * - * @author Zachary Jones * + * @author Zachary Jones */ public class OctalToDecimal { - /** - * Main method - * - * @param args - * Command line arguments - */ - public static void main(String args[]) { - Scanner sc = new Scanner(System.in); - System.out.print("Octal Input: "); - String inputOctal = sc.nextLine(); - int result = convertOctalToDecimal(inputOctal); - if (result != -1) - System.out.println("Result convertOctalToDecimal : " + result); - sc.close(); - } + /** + * Main method + * + * @param args Command line arguments + */ + public static void main(String args[]) { + Scanner sc = new Scanner(System.in); + System.out.print("Octal Input: "); + String inputOctal = sc.nextLine(); + int result = convertOctalToDecimal(inputOctal); + if (result != -1) System.out.println("Result convertOctalToDecimal : " + result); + sc.close(); + } - /** - * This method converts an octal number to a decimal number. - * - * @param inputOctal - * The octal number - * @return The decimal number - */ - public static int convertOctalToDecimal(String inputOctal) { + /** + * This method converts an octal number to a decimal number. + * + * @param inputOctal The octal number + * @return The decimal number + */ + public static int convertOctalToDecimal(String inputOctal) { - try { - // Actual conversion of Octal to Decimal: - Integer outputDecimal = Integer.parseInt(inputOctal, 8); - return outputDecimal; - } catch (NumberFormatException ne) { - // Printing a warning message if the input is not a valid octal - // number: - System.out.println("Invalid Input, Expecting octal number 0-7"); - return -1; - } - } -} \ No newline at end of file + try { + // Actual conversion of Octal to Decimal: + Integer outputDecimal = Integer.parseInt(inputOctal, 8); + return outputDecimal; + } catch (NumberFormatException ne) { + // Printing a warning message if the input is not a valid octal + // number: + System.out.println("Invalid Input, Expecting octal number 0-7"); + return -1; + } + } +} diff --git a/Conversions/OctalToHexadecimal.java b/Conversions/OctalToHexadecimal.java index 4f15c488237b..4035ada70432 100644 --- a/Conversions/OctalToHexadecimal.java +++ b/Conversions/OctalToHexadecimal.java @@ -9,57 +9,54 @@ */ public class OctalToHexadecimal { - /** - * This method converts a Octal number to a decimal number - * - * @param s The Octal Number - * @return The Decimal number - */ - public static int octToDec(String s) { - int i = 0; - for (int j = 0; j < s.length(); j++) { - char num = s.charAt(j); - num -= '0'; - i *= 8; - i += num; - } - return i; + /** + * This method converts a Octal number to a decimal number + * + * @param s The Octal Number + * @return The Decimal number + */ + public static int octToDec(String s) { + int i = 0; + for (int j = 0; j < s.length(); j++) { + char num = s.charAt(j); + num -= '0'; + i *= 8; + i += num; } - - /** - * This method converts a Decimal number to a Hexadecimal number - * - * @param d The Decimal Number - * @return The Hexadecimal number - */ - public static String decimalToHex(int d) { - String digits = "0123456789ABCDEF"; - if (d <= 0) - return "0"; - String hex = ""; - while (d > 0) { - int digit = d % 16; - hex = digits.charAt(digit) + hex; - d = d / 16; - } - return hex; + return i; + } + + /** + * This method converts a Decimal number to a Hexadecimal number + * + * @param d The Decimal Number + * @return The Hexadecimal number + */ + public static String decimalToHex(int d) { + String digits = "0123456789ABCDEF"; + if (d <= 0) return "0"; + String hex = ""; + while (d > 0) { + int digit = d % 16; + hex = digits.charAt(digit) + hex; + d = d / 16; } + return hex; + } + public static void main(String args[]) { - public static void main(String args[]) { - - Scanner input = new Scanner(System.in); - System.out.print("Enter the Octal number: "); - // Take octal number as input from user in a string - String oct = input.next(); + Scanner input = new Scanner(System.in); + System.out.print("Enter the Octal number: "); + // Take octal number as input from user in a string + String oct = input.next(); - // Pass the octal number to function and get converted deciaml form - int decimal = octToDec(oct); + // Pass the octal number to function and get converted deciaml form + int decimal = octToDec(oct); - // Pass the decimla number to function and get converted Hex form of the number - String hex = decimalToHex(decimal); - System.out.println("The Hexadecimal equivalant is: " + hex); - input.close(); - } + // Pass the decimla number to function and get converted Hex form of the number + String hex = decimalToHex(decimal); + System.out.println("The Hexadecimal equivalant is: " + hex); + input.close(); + } } - diff --git a/Conversions/RomanToInteger.java b/Conversions/RomanToInteger.java index f66ab115ff1a..36a61e740a2a 100644 --- a/Conversions/RomanToInteger.java +++ b/Conversions/RomanToInteger.java @@ -4,63 +4,63 @@ public class RomanToInteger { - private static Map map = new HashMap() { - /** - * - */ + private static Map map = + new HashMap() { + /** */ private static final long serialVersionUID = 87605733047260530L; { - put('I', 1); - put('V', 5); - put('X', 10); - put('L', 50); - put('C', 100); - put('D', 500); - put('M', 1000); - }}; - //Roman Number = Roman Numerals - - /** - * This function convert Roman number into Integer - * - * @param A Roman number string - * @return integer - */ - public static int romanToInt(String A) { + put('I', 1); + put('V', 5); + put('X', 10); + put('L', 50); + put('C', 100); + put('D', 500); + put('M', 1000); + } + }; + // Roman Number = Roman Numerals - A = A.toUpperCase(); - char prev = ' '; + /** + * This function convert Roman number into Integer + * + * @param A Roman number string + * @return integer + */ + public static int romanToInt(String A) { - int sum = 0; + A = A.toUpperCase(); + char prev = ' '; - int newPrev = 0; - for (int i = A.length() - 1; i >= 0; i--) { - char c = A.charAt(i); + int sum = 0; - if (prev != ' ') { - // checking current Number greater then previous or not - newPrev = map.get(prev) > newPrev ? map.get(prev) : newPrev; - } + int newPrev = 0; + for (int i = A.length() - 1; i >= 0; i--) { + char c = A.charAt(i); - int currentNum = map.get(c); + if (prev != ' ') { + // checking current Number greater then previous or not + newPrev = map.get(prev) > newPrev ? map.get(prev) : newPrev; + } - // if current number greater then prev max previous then add - if (currentNum >= newPrev) { - sum += currentNum; - } else { - // subtract upcoming number until upcoming number not greater then prev max - sum -= currentNum; - } + int currentNum = map.get(c); - prev = c; - } + // if current number greater then prev max previous then add + if (currentNum >= newPrev) { + sum += currentNum; + } else { + // subtract upcoming number until upcoming number not greater then prev max + sum -= currentNum; + } - return sum; + prev = c; } - public static void main(String[] args) { - int sum = romanToInt("MDCCCIV"); - System.out.println(sum); - } -} + return sum; + } + + public static void main(String[] args) { + int sum = romanToInt("MDCCCIV"); + System.out.println(sum); + } +} diff --git a/DataStructures/Bags/Bag.java b/DataStructures/Bags/Bag.java index 2fd17ed65b04..dc89a8a33027 100644 --- a/DataStructures/Bags/Bag.java +++ b/DataStructures/Bags/Bag.java @@ -10,117 +10,101 @@ */ public class Bag implements Iterable { - private Node firstElement; // first element of the bag - private int size; // size of bag - - private static class Node { - private Element content; - private Node nextElement; - } - - /** - * Create an empty bag - */ - public Bag() { - firstElement = null; - size = 0; + private Node firstElement; // first element of the bag + private int size; // size of bag + + private static class Node { + private Element content; + private Node nextElement; + } + + /** Create an empty bag */ + public Bag() { + firstElement = null; + size = 0; + } + + /** @return true if this bag is empty, false otherwise */ + public boolean isEmpty() { + return firstElement == null; + } + + /** @return the number of elements */ + public int size() { + return size; + } + + /** @param element - the element to add */ + public void add(Element element) { + Node oldfirst = firstElement; + firstElement = new Node<>(); + firstElement.content = element; + firstElement.nextElement = oldfirst; + size++; + } + + /** + * Checks if the bag contains a specific element + * + * @param element which you want to look for + * @return true if bag contains element, otherwise false + */ + public boolean contains(Element element) { + Iterator iterator = this.iterator(); + while (iterator.hasNext()) { + if (iterator.next().equals(element)) { + return true; + } } + return false; + } - /** - * @return true if this bag is empty, false otherwise - */ - public boolean isEmpty() { - return firstElement == null; - } + /** @return an iterator that iterates over the elements in this bag in arbitrary order */ + public Iterator iterator() { + return new ListIterator<>(firstElement); + } - /** - * @return the number of elements - */ - public int size() { - return size; - } + @SuppressWarnings("hiding") + private class ListIterator implements Iterator { + private Node currentElement; - /** - * @param element - the element to add - */ - public void add(Element element) { - Node oldfirst = firstElement; - firstElement = new Node<>(); - firstElement.content = element; - firstElement.nextElement = oldfirst; - size++; + public ListIterator(Node firstElement) { + currentElement = firstElement; } - /** - * Checks if the bag contains a specific element - * - * @param element which you want to look for - * @return true if bag contains element, otherwise false - */ - public boolean contains(Element element) { - Iterator iterator = this.iterator(); - while (iterator.hasNext()) { - if (iterator.next().equals(element)) { - return true; - } - } - return false; + public boolean hasNext() { + return currentElement != null; } - /** - * @return an iterator that iterates over the elements in this bag in arbitrary order - */ - public Iterator iterator() { - return new ListIterator<>(firstElement); + /** remove is not allowed in a bag */ + @Override + public void remove() { + throw new UnsupportedOperationException(); } - @SuppressWarnings("hiding") - private class ListIterator implements Iterator { - private Node currentElement; - - public ListIterator(Node firstElement) { - currentElement = firstElement; - } - - public boolean hasNext() { - return currentElement != null; - } - - /** - * remove is not allowed in a bag - */ - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - - public Element next() { - if (!hasNext()) - throw new NoSuchElementException(); - Element element = currentElement.content; - currentElement = currentElement.nextElement; - return element; - } + public Element next() { + if (!hasNext()) throw new NoSuchElementException(); + Element element = currentElement.content; + currentElement = currentElement.nextElement; + return element; } + } - /** - * main-method for testing - */ - public static void main(String[] args) { - Bag bag = new Bag<>(); - - bag.add("1"); - bag.add("1"); - bag.add("2"); + /** main-method for testing */ + public static void main(String[] args) { + Bag bag = new Bag<>(); - System.out.println("size of bag = " + bag.size()); - for (String s : bag) { - System.out.println(s); - } + bag.add("1"); + bag.add("1"); + bag.add("2"); - System.out.println(bag.contains(null)); - System.out.println(bag.contains("1")); - System.out.println(bag.contains("3")); + System.out.println("size of bag = " + bag.size()); + for (String s : bag) { + System.out.println(s); } + System.out.println(bag.contains(null)); + System.out.println(bag.contains("1")); + System.out.println(bag.contains("3")); + } } diff --git a/DataStructures/Buffers/CircularBuffer.java b/DataStructures/Buffers/CircularBuffer.java index a723f693089c..5c0304dbd366 100644 --- a/DataStructures/Buffers/CircularBuffer.java +++ b/DataStructures/Buffers/CircularBuffer.java @@ -4,129 +4,127 @@ import java.util.concurrent.atomic.AtomicInteger; public class CircularBuffer { - private char[] _buffer; - public final int _buffer_size; - private int _write_index = 0; - private int _read_index = 0; - private AtomicInteger _readable_data = new AtomicInteger(0); - - public CircularBuffer(int buffer_size) { - if (!IsPowerOfTwo(buffer_size)) { - throw new IllegalArgumentException(); - } - this._buffer_size = buffer_size; - _buffer = new char[buffer_size]; + private char[] _buffer; + public final int _buffer_size; + private int _write_index = 0; + private int _read_index = 0; + private AtomicInteger _readable_data = new AtomicInteger(0); + + public CircularBuffer(int buffer_size) { + if (!IsPowerOfTwo(buffer_size)) { + throw new IllegalArgumentException(); } + this._buffer_size = buffer_size; + _buffer = new char[buffer_size]; + } - private boolean IsPowerOfTwo(int i) { - return (i & (i - 1)) == 0; - } + private boolean IsPowerOfTwo(int i) { + return (i & (i - 1)) == 0; + } - private int getTrueIndex(int i) { - return i % _buffer_size; - } + private int getTrueIndex(int i) { + return i % _buffer_size; + } - - public Character readOutChar() { - Character result = null; - - - //if we have data to read - if (_readable_data.get() > 0) { - - result = Character.valueOf(_buffer[getTrueIndex(_read_index)]); - _readable_data.decrementAndGet(); - _read_index++; - } + public Character readOutChar() { + Character result = null; - return result; + // if we have data to read + if (_readable_data.get() > 0) { + + result = Character.valueOf(_buffer[getTrueIndex(_read_index)]); + _readable_data.decrementAndGet(); + _read_index++; } - public boolean writeToCharBuffer(char c) { - boolean result = false; + return result; + } - //if we can write to the buffer - if (_readable_data.get() < _buffer_size) { - //write to buffer - _buffer[getTrueIndex(_write_index)] = c; - _readable_data.incrementAndGet(); - _write_index++; - result = true; - } + public boolean writeToCharBuffer(char c) { + boolean result = false; - return result; + // if we can write to the buffer + if (_readable_data.get() < _buffer_size) { + // write to buffer + _buffer[getTrueIndex(_write_index)] = c; + _readable_data.incrementAndGet(); + _write_index++; + result = true; } - private static class TestWriteWorker implements Runnable { - String _alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"; - Random _random = new Random(); - CircularBuffer _buffer; - - public TestWriteWorker(CircularBuffer cb) { - this._buffer = cb; - } + return result; + } - private char getRandomChar() { - return _alphabet.charAt(_random.nextInt(_alphabet.length())); - } + private static class TestWriteWorker implements Runnable { + String _alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"; + Random _random = new Random(); + CircularBuffer _buffer; - public void run() { - while (!Thread.interrupted()) { - if (!_buffer.writeToCharBuffer(getRandomChar())) { - Thread.yield(); - try { - Thread.sleep(10); - } catch (InterruptedException e) { - return; - } - } - } - } + public TestWriteWorker(CircularBuffer cb) { + this._buffer = cb; } - private static class TestReadWorker implements Runnable { - CircularBuffer _buffer; - - public TestReadWorker(CircularBuffer cb) { - this._buffer = cb; - } + private char getRandomChar() { + return _alphabet.charAt(_random.nextInt(_alphabet.length())); + } - @Override - public void run() { - System.out.println("Printing Buffer:"); - while (!Thread.interrupted()) { - Character c = _buffer.readOutChar(); - if (c != null) { - System.out.print(c.charValue()); - } else { - Thread.yield(); - try { - Thread.sleep(10); - } catch (InterruptedException e) { - System.out.println(); - return; - } - } - } + public void run() { + while (!Thread.interrupted()) { + if (!_buffer.writeToCharBuffer(getRandomChar())) { + Thread.yield(); + try { + Thread.sleep(10); + } catch (InterruptedException e) { + return; + } } + } } + } - public static void main(String[] args) throws InterruptedException { - int buffer_size = 1024; - //create circular buffer - CircularBuffer cb = new CircularBuffer(buffer_size); - - //create threads that read and write the buffer. - Thread write_thread = new Thread(new TestWriteWorker(cb)); - Thread read_thread = new Thread(new TestReadWorker(cb)); - read_thread.start(); - write_thread.start(); + private static class TestReadWorker implements Runnable { + CircularBuffer _buffer; - //wait some amount of time - Thread.sleep(10000); + public TestReadWorker(CircularBuffer cb) { + this._buffer = cb; + } - //interrupt threads and exit - write_thread.interrupt(); - read_thread.interrupt(); + @Override + public void run() { + System.out.println("Printing Buffer:"); + while (!Thread.interrupted()) { + Character c = _buffer.readOutChar(); + if (c != null) { + System.out.print(c.charValue()); + } else { + Thread.yield(); + try { + Thread.sleep(10); + } catch (InterruptedException e) { + System.out.println(); + return; + } + } + } } + } + + public static void main(String[] args) throws InterruptedException { + int buffer_size = 1024; + // create circular buffer + CircularBuffer cb = new CircularBuffer(buffer_size); + + // create threads that read and write the buffer. + Thread write_thread = new Thread(new TestWriteWorker(cb)); + Thread read_thread = new Thread(new TestReadWorker(cb)); + read_thread.start(); + write_thread.start(); + + // wait some amount of time + Thread.sleep(10000); + + // interrupt threads and exit + write_thread.interrupt(); + read_thread.interrupt(); + } } diff --git a/DataStructures/DynamicArray/DynamicArray.java b/DataStructures/DynamicArray/DynamicArray.java index f016448729fa..d095627c6cdf 100644 --- a/DataStructures/DynamicArray/DynamicArray.java +++ b/DataStructures/DynamicArray/DynamicArray.java @@ -7,202 +7,210 @@ /** * This class implements a dynamic array + * * @param the type that each index of the array will hold */ public class DynamicArray implements Iterable { - private int capacity; - private int size; - private Object[] elements; - - /** - * constructor - * @param capacity the starting length of the desired array - */ - public DynamicArray(final int capacity) { - this.size = 0; - this.capacity = capacity; - this.elements = new Object[this.capacity]; - } + private int capacity; + private int size; + private Object[] elements; + + /** + * constructor + * + * @param capacity the starting length of the desired array + */ + public DynamicArray(final int capacity) { + this.size = 0; + this.capacity = capacity; + this.elements = new Object[this.capacity]; + } + + /** No-args constructor */ + public DynamicArray() { + this.size = 0; + this.capacity = 10; + this.elements = new Object[this.capacity]; + } + + /** + * Doubles the capacity of the array + * + * @return int the new capacity of the array + */ + public int newCapacity() { + this.capacity *= 2; + // changed from this.capacity <<= 1; now much easier to understand + return this.capacity; + } + + /** + * Adds an element to the array If full, creates a copy array twice the size of the current one + * + * @param element the element of type to be added to the array + */ + public void add(final E element) { + if (this.size == this.elements.length) { + this.elements = Arrays.copyOf(this.elements, newCapacity()); + } + + this.elements[this.size] = element; + size++; + } + + /** + * Places element of type at the desired index + * + * @param index the index for the element to be placed + * @param element the element to be inserted + */ + public void put(final int index, E element) { + this.elements[index] = element; + } + + /** + * get method for element at a given index returns null if the index is empty + * + * @param index the desired index of the element + * @return the element at the specified index + */ + public E get(final int index) { + return getElement(index); + } + + /** + * Removes an element from the array + * + * @param index the index of the element to be removed + * @return the element removed + */ + public E remove(final int index) { + final E oldElement = getElement(index); + fastRemove(this.elements, index); + + return oldElement; + } + + /** + * get method for size field + * + * @return int size + */ + public int getSize() { + return this.size; + } + + /** + * isEmpty helper method + * + * @return boolean true if the array contains no elements, false otherwise + */ + public boolean isEmpty() { + return this.size == 0; + } + + public Stream stream() { + return StreamSupport.stream(spliterator(), false); + } + + private void fastRemove(final Object[] elements, final int index) { + final int newSize = this.size - 1; + + if (newSize > index) { + System.arraycopy(elements, index + 1, elements, index, newSize - index); + } + + elements[this.size = newSize] = null; + } + + private E getElement(final int index) { + return (E) this.elements[index]; + } + + /** + * returns a String representation of this object + * + * @return String a String representing the array + */ + @Override + public String toString() { + return Arrays.toString(Arrays.stream(this.elements).filter(Objects::nonNull).toArray()); + } + + /** + * Creates and returns a new Dynamic Array Iterator + * + * @return Iterator a Dynamic Array Iterator + */ + @Override + public Iterator iterator() { + return new DynamicArrayIterator(); + } + + private class DynamicArrayIterator implements Iterator { + + private int cursor; - /** - * No-args constructor - */ - public DynamicArray() { - this.size = 0; - this.capacity = 10; - this.elements = new Object[this.capacity]; + @Override + public boolean hasNext() { + return this.cursor != size; } - /** - * Doubles the capacity of the array - * @return int the new capacity of the array - */ - public int newCapacity() { - this.capacity *= 2; - //changed from this.capacity <<= 1; now much easier to understand - return this.capacity; - } + @Override + public E next() { + if (this.cursor > DynamicArray.this.size) throw new NoSuchElementException(); - /** - * Adds an element to the array - * If full, creates a copy array twice the size of the current one - * @param element the element of type to be added to the array - */ - public void add(final E element) { - if (this.size == this.elements.length) { - this.elements = Arrays.copyOf(this.elements, newCapacity()); - } - - this.elements[this.size] = element; - size++; - } - - /** - * Places element of type at the desired index - * @param index the index for the element to be placed - * @param element the element to be inserted - */ - public void put(final int index, E element) { - this.elements[index] = element; - } + if (this.cursor > DynamicArray.this.elements.length) + throw new ConcurrentModificationException(); - /** - * get method for element at a given index - * returns null if the index is empty - * @param index the desired index of the element - * @return the element at the specified index - */ - public E get(final int index) { - return getElement(index); - } - - /** - * Removes an element from the array - * @param index the index of the element to be removed - * @return the element removed - */ - public E remove(final int index) { - final E oldElement = getElement(index); - fastRemove(this.elements, index); - - return oldElement; - } - - /** - * get method for size field - * @return int size - */ - public int getSize() { - return this.size; - } + final E element = DynamicArray.this.getElement(this.cursor); + this.cursor++; - /** - * isEmpty helper method - * @return boolean true if the array contains no elements, false otherwise - */ - public boolean isEmpty() { - return this.size == 0; + return element; } - - public Stream stream() { - return StreamSupport.stream(spliterator(), false); - } - - private void fastRemove(final Object[] elements, final int index) { - final int newSize = this.size - 1; - if (newSize > index) { - System.arraycopy(elements, index + 1, elements, index, newSize - index); - } - - elements[this.size = newSize] = null; - } + @Override + public void remove() { + if (this.cursor < 0) throw new IllegalStateException(); - private E getElement(final int index) { - return (E) this.elements[index]; + DynamicArray.this.remove(this.cursor); + this.cursor--; } - /** - * returns a String representation of this object - * @return String a String representing the array - */ @Override - public String toString() { - return Arrays.toString(Arrays.stream(this.elements).filter(Objects::nonNull).toArray()); - } + public void forEachRemaining(Consumer action) { + Objects.requireNonNull(action); - /** - * Creates and returns a new Dynamic Array Iterator - * @return Iterator a Dynamic Array Iterator - */ - @Override - public Iterator iterator() { - return new DynamicArrayIterator(); + for (int i = 0; i < DynamicArray.this.size; i++) { + action.accept(DynamicArray.this.getElement(i)); + } } + } - private class DynamicArrayIterator implements Iterator { - - private int cursor; - - @Override - public boolean hasNext() { - return this.cursor != size; - } - - @Override - public E next() { - if (this.cursor > DynamicArray.this.size) throw new NoSuchElementException(); - - if (this.cursor > DynamicArray.this.elements.length) throw new ConcurrentModificationException(); - - final E element = DynamicArray.this.getElement(this.cursor); - this.cursor++; + /** + * This class is the driver for the DynamicArray class it tests a variety of methods and prints + * the output + */ + public static void main(String[] args) { + DynamicArray names = new DynamicArray<>(); + names.add("Peubes"); + names.add("Marley"); - return element; - } - - @Override - public void remove() { - if (this.cursor < 0) throw new IllegalStateException(); - - DynamicArray.this.remove(this.cursor); - this.cursor--; - } - - @Override - public void forEachRemaining(Consumer action) { - Objects.requireNonNull(action); - - for (int i = 0; i < DynamicArray.this.size; i++) { - action.accept(DynamicArray.this.getElement(i)); - } - } + for (String name : names) { + System.out.println(name); } - /** - * This class is the driver for the DynamicArray class - * it tests a variety of methods and prints the output - */ - public static void main(String[] args) { - DynamicArray names = new DynamicArray<>(); - names.add("Peubes"); - names.add("Marley"); - - for (String name : names) { - System.out.println(name); - } - - names.stream().forEach(System.out::println); + names.stream().forEach(System.out::println); - System.out.println(names); + System.out.println(names); - System.out.println(names.getSize()); + System.out.println(names.getSize()); - names.remove(0); + names.remove(0); - for (String name : names) { - System.out.println(name); - } + for (String name : names) { + System.out.println(name); } + } } diff --git a/DataStructures/Graphs/A_Star.java b/DataStructures/Graphs/A_Star.java index 9fa92ce32118..09a809a30938 100644 --- a/DataStructures/Graphs/A_Star.java +++ b/DataStructures/Graphs/A_Star.java @@ -8,152 +8,172 @@ public class A_Star { - private static class Graph { - //Graph's structure can be changed only applying changes to this class. - private ArrayList [] graph; - - //Initialise ArrayLists in Constructor - public Graph(int size) { - this.graph = new ArrayList[size]; - for (int i = 0; i < size; i++) { - this.graph[i] = new ArrayList<>(); - } - } - - private ArrayList getNeighbours(int from) { return this.graph[from]; } - - //Graph is bidirectional, for just one direction remove second instruction of this method. - private void addEdge (Edge edge) { - this.graph[edge.getFrom()].add(new Edge(edge.getFrom(), edge.getTo(), edge.getWeight())); - this.graph[edge.getTo()].add(new Edge(edge.getTo(), edge.getFrom(), edge.getWeight())); - } + private static class Graph { + // Graph's structure can be changed only applying changes to this class. + private ArrayList[] graph; + + // Initialise ArrayLists in Constructor + public Graph(int size) { + this.graph = new ArrayList[size]; + for (int i = 0; i < size; i++) { + this.graph[i] = new ArrayList<>(); + } } - private static class Edge { - private int from; - private int to; - private int weight; - - public Edge(int from, int to, int weight) { - this.from = from; - this.to = to; - this.weight = weight; - } - - public int getFrom() { return from; } - - public int getTo() { return to; } - - public int getWeight() { return weight; } + private ArrayList getNeighbours(int from) { + return this.graph[from]; } - //class to iterate during the algorithm execution, and also used to return the solution. - private static class PathAndDistance { - private int distance; //distance advanced so far. - private ArrayList path; //list of visited nodes in this path. - private int estimated; //heuristic value associated to the last node od the path (current node). - - public PathAndDistance(int distance, ArrayList path, int estimated) { - this.distance = distance; - this.path = path; - this.estimated = estimated; - } + // Graph is bidirectional, for just one direction remove second instruction of this method. + private void addEdge(Edge edge) { + this.graph[edge.getFrom()].add(new Edge(edge.getFrom(), edge.getTo(), edge.getWeight())); + this.graph[edge.getTo()].add(new Edge(edge.getTo(), edge.getFrom(), edge.getWeight())); + } + } - public int getDistance() { return distance; } + private static class Edge { + private int from; + private int to; + private int weight; - public ArrayList getPath() { return path; } + public Edge(int from, int to, int weight) { + this.from = from; + this.to = to; + this.weight = weight; + } - public int getEstimated() { return estimated; } + public int getFrom() { + return from; + } - private void printSolution () { - if (this.path != null) - System.out.println("Optimal path: " + this.path.toString() + - ", distance: " + this.distance); - else - System.out.println("There is no path available to connect the points"); - } + public int getTo() { + return to; } - private static void initializeGraph(Graph graph, ArrayList data) { - for (int i = 0; i < data.size(); i+=4) { - graph.addEdge(new Edge(data.get(i), data.get(i + 1), data.get(i + 2))); - } - /* - .x. node - (y) cost - - or | or / bidirectional connection - - ( 98)- .7. -(86)- .4. - | - ( 85)- .17. -(142)- .18. -(92)- .8. -(87)- .11. - | - . 1. -------------------- (160) - | \ | - (211) \ .6. - | \ | - . 5. (101)-.13. -(138) (115) - | | | / - ( 99) ( 97) | / - | | | / - .12. -(151)- .15. -(80)- .14. | / - | | | | / - ( 71) (140) (146)- .2. -(120) - | | | - .19. -( 75)- . 0. .10. -(75)- .3. - | | - (118) ( 70) - | | - .16. -(111)- .9. - */ + public int getWeight() { + return weight; + } + } + + // class to iterate during the algorithm execution, and also used to return the solution. + private static class PathAndDistance { + private int distance; // distance advanced so far. + private ArrayList path; // list of visited nodes in this path. + private int + estimated; // heuristic value associated to the last node od the path (current node). + + public PathAndDistance(int distance, ArrayList path, int estimated) { + this.distance = distance; + this.path = path; + this.estimated = estimated; } - public static void main(String[] args) { - //heuristic function optimistic values - int[] heuristic = {366, 0, 160, 242, 161, 178, 77, 151, 226, - 244, 241, 234, 380, 98, 193, 253, 329, 80, 199, 374}; + public int getDistance() { + return distance; + } - Graph graph = new Graph(20); - ArrayList graphData = new ArrayList<>(Arrays.asList(0, 19, 75, null, - 0, 15, 140, null, 0, 16, 118, null, 19, 12, 71, null, 12, 15, 151, null, - 16, 9, 111, null, 9, 10, 70, null, 10, 3, 75, null, 3, 2, 120, null, - 2, 14, 146, null, 2, 13, 138, null, 2, 6, 115, null, 15, 14, 80, null, - 15, 5, 99, null, 14, 13, 97, null, 5, 1, 211, null, 13, 1, 101, null, - 6, 1, 160, null, 1, 17, 85, null, 17, 7, 98, null, 7, 4, 86, null, - 17, 18, 142, null, 18, 8, 92, null, 8, 11, 87)); - initializeGraph(graph, graphData); + public ArrayList getPath() { + return path; + } - PathAndDistance solution = aStar(3, 1, graph, heuristic); - solution.printSolution(); + public int getEstimated() { + return estimated; + } + private void printSolution() { + if (this.path != null) + System.out.println( + "Optimal path: " + this.path.toString() + ", distance: " + this.distance); + else System.out.println("There is no path available to connect the points"); } + } - public static PathAndDistance aStar(int from, int to, Graph graph, int[] heuristic) { - //nodes are prioritised by the less value of the current distance of their paths, and the estimated value - //given by the heuristic function to reach the destination point from the current point. - PriorityQueue queue = new PriorityQueue<> - (Comparator.comparingInt(a -> (a.getDistance() + a.getEstimated()))); - - //dummy data to start the algorithm from the beginning point - queue.add(new PathAndDistance(0, new ArrayList<>(Arrays.asList(from)), 0)); - - boolean solutionFound = false; - PathAndDistance currentData = new PathAndDistance(-1, null, -1); - while (!queue.isEmpty() && !solutionFound) { - currentData = queue.poll(); //first in the queue, best node so keep exploring. - int currentPosition = currentData.getPath().get(currentData.getPath().size() - 1); //current node. - if (currentPosition == to) - solutionFound = true; - else - for (Edge edge : graph.getNeighbours(currentPosition)) - if (!currentData.getPath().contains(edge.getTo())) { //Avoid Cycles - ArrayList updatedPath = new ArrayList<>(currentData.getPath()); - updatedPath.add(edge.getTo()); //Add the new node to the path, update the distance, - // and the heuristic function value associated to that path. - queue.add(new PathAndDistance(currentData.getDistance() + edge.getWeight(), - updatedPath, heuristic[edge.getTo()])); - } - } - return (solutionFound) ? currentData : new PathAndDistance(-1, null, -1); - //Out of while loop, if there is a solution, the current Data stores the optimal path, and its distance + private static void initializeGraph(Graph graph, ArrayList data) { + for (int i = 0; i < data.size(); i += 4) { + graph.addEdge(new Edge(data.get(i), data.get(i + 1), data.get(i + 2))); + } + /* + .x. node + (y) cost + - or | or / bidirectional connection + + ( 98)- .7. -(86)- .4. + | + ( 85)- .17. -(142)- .18. -(92)- .8. -(87)- .11. + | + . 1. -------------------- (160) + | \ | + (211) \ .6. + | \ | + . 5. (101)-.13. -(138) (115) + | | | / + ( 99) ( 97) | / + | | | / + .12. -(151)- .15. -(80)- .14. | / + | | | | / + ( 71) (140) (146)- .2. -(120) + | | | + .19. -( 75)- . 0. .10. -(75)- .3. + | | + (118) ( 70) + | | + .16. -(111)- .9. + */ + } + + public static void main(String[] args) { + // heuristic function optimistic values + int[] heuristic = { + 366, 0, 160, 242, 161, 178, 77, 151, 226, 244, 241, 234, 380, 98, 193, 253, 329, 80, 199, 374 + }; + + Graph graph = new Graph(20); + ArrayList graphData = + new ArrayList<>( + Arrays.asList( + 0, 19, 75, null, 0, 15, 140, null, 0, 16, 118, null, 19, 12, 71, null, 12, 15, 151, + null, 16, 9, 111, null, 9, 10, 70, null, 10, 3, 75, null, 3, 2, 120, null, 2, 14, + 146, null, 2, 13, 138, null, 2, 6, 115, null, 15, 14, 80, null, 15, 5, 99, null, 14, + 13, 97, null, 5, 1, 211, null, 13, 1, 101, null, 6, 1, 160, null, 1, 17, 85, null, + 17, 7, 98, null, 7, 4, 86, null, 17, 18, 142, null, 18, 8, 92, null, 8, 11, 87)); + initializeGraph(graph, graphData); + + PathAndDistance solution = aStar(3, 1, graph, heuristic); + solution.printSolution(); + } + + public static PathAndDistance aStar(int from, int to, Graph graph, int[] heuristic) { + // nodes are prioritised by the less value of the current distance of their paths, and the + // estimated value + // given by the heuristic function to reach the destination point from the current point. + PriorityQueue queue = + new PriorityQueue<>(Comparator.comparingInt(a -> (a.getDistance() + a.getEstimated()))); + + // dummy data to start the algorithm from the beginning point + queue.add(new PathAndDistance(0, new ArrayList<>(Arrays.asList(from)), 0)); + + boolean solutionFound = false; + PathAndDistance currentData = new PathAndDistance(-1, null, -1); + while (!queue.isEmpty() && !solutionFound) { + currentData = queue.poll(); // first in the queue, best node so keep exploring. + int currentPosition = + currentData.getPath().get(currentData.getPath().size() - 1); // current node. + if (currentPosition == to) solutionFound = true; + else + for (Edge edge : graph.getNeighbours(currentPosition)) + if (!currentData.getPath().contains(edge.getTo())) { // Avoid Cycles + ArrayList updatedPath = new ArrayList<>(currentData.getPath()); + updatedPath.add(edge.getTo()); // Add the new node to the path, update the distance, + // and the heuristic function value associated to that path. + queue.add( + new PathAndDistance( + currentData.getDistance() + edge.getWeight(), + updatedPath, + heuristic[edge.getTo()])); + } } + return (solutionFound) ? currentData : new PathAndDistance(-1, null, -1); + // Out of while loop, if there is a solution, the current Data stores the optimal path, and its + // distance + } } diff --git a/DataStructures/Graphs/BellmanFord.java b/DataStructures/Graphs/BellmanFord.java index 41c89bb020ee..841277a3a1bf 100644 --- a/DataStructures/Graphs/BellmanFord.java +++ b/DataStructures/Graphs/BellmanFord.java @@ -1,161 +1,161 @@ package DataStructures.Graphs; import java.util.*; + class BellmanFord -/*Implementation of Bellman ford to detect negative cycles. Graph accepts inputs in form of edges which have +/*Implementation of Bellman ford to detect negative cycles. Graph accepts inputs in form of edges which have start vertex, end vertes and weights. Vertices should be labelled with a number between 0 and total number of vertices-1,both inclusive*/ { - int vertex,edge; - private Edge edges[]; - private int index=0; - BellmanFord(int v,int e) - { - vertex=v; - edge=e; - edges=new Edge[e]; - } - class Edge - { - int u,v; - int w; - /** - *@param u Source Vertex - * @param v End vertex - * @param c Weight - */ - public Edge(int a,int b,int c) - { - u=a; - v=b; - w=c; - } - } + int vertex, edge; + private Edge edges[]; + private int index = 0; + + BellmanFord(int v, int e) { + vertex = v; + edge = e; + edges = new Edge[e]; + } + + class Edge { + int u, v; + int w; /** - * @param p[] Parent array which shows updates in edges - * @param i Current vertex under consideration + * @param u Source Vertex + * @param v End vertex + * @param c Weight */ - void printPath(int p[],int i) - { - if(p[i]==-1)//Found the path back to parent - return; - printPath(p,p[i]); - System.out.print(i+" "); + public Edge(int a, int b, int c) { + u = a; + v = b; + w = c; } - public static void main(String args[]) - { - BellmanFord obj=new BellmanFord(0,0);//Dummy object to call nonstatic variables - obj.go(); + } + /** + * @param p[] Parent array which shows updates in edges + * @param i Current vertex under consideration + */ + void printPath(int p[], int i) { + if (p[i] == -1) // Found the path back to parent + return; + printPath(p, p[i]); + System.out.print(i + " "); + } + + public static void main(String args[]) { + BellmanFord obj = new BellmanFord(0, 0); // Dummy object to call nonstatic variables + obj.go(); + } + + public void + go() // Interactive run for understanding the class first time. Assumes source vertex is 0 and + // shows distaance to all vertices + { + Scanner sc = new Scanner(System.in); // Grab scanner object for user input + int i, v, e, u, ve, w, j, neg = 0; + System.out.println("Enter no. of vertices and edges please"); + v = sc.nextInt(); + e = sc.nextInt(); + Edge arr[] = new Edge[e]; // Array of edges + System.out.println("Input edges"); + for (i = 0; i < e; i++) { + u = sc.nextInt(); + ve = sc.nextInt(); + w = sc.nextInt(); + arr[i] = new Edge(u, ve, w); } - public void go()//Interactive run for understanding the class first time. Assumes source vertex is 0 and shows distaance to all vertices - { - Scanner sc=new Scanner(System.in);//Grab scanner object for user input - int i,v,e,u,ve,w,j,neg=0; - System.out.println("Enter no. of vertices and edges please"); - v=sc.nextInt(); - e=sc.nextInt(); - Edge arr[]=new Edge[e];//Array of edges - System.out.println("Input edges"); - for(i=0;i dist[arr[j].u] + arr[j].w) { + dist[arr[j].v] = dist[arr[j].u] + arr[j].w; // Update + p[arr[j].v] = arr[j].u; } - int dist[]=new int[v];//Distance array for holding the finalized shortest path distance between source and all vertices - int p[]=new int[v];//Parent array for holding the paths - for(i=0;idist[arr[j].u]+arr[j].w) - { - dist[arr[j].v]=dist[arr[j].u]+arr[j].w;//Update - p[arr[j].v]=arr[j].u; - } - } - } - //Final cycle for negative checking - for(j=0;jdist[arr[j].u]+arr[j].w) - { - neg=1; - System.out.println("Negative cycle"); - break; - } - if(neg==0)//Go ahead and show results of computaion - { - System.out.println("Distances are: "); - for(i=0;i dist[arr[j].u] + arr[j].w) { + neg = 1; + System.out.println("Negative cycle"); + break; + } + if (neg == 0) // Go ahead and show results of computaion { - int i,j,v=vertex,e=edge,neg=0; - double dist[]=new double[v];//Distance array for holding the finalized shortest path distance between source and all vertices - int p[]=new int[v];//Parent array for holding the paths - for(i=0;idist[arr[j].u]+arr[j].w) - { - dist[arr[j].v]=dist[arr[j].u]+arr[j].w;//Update - p[arr[j].v]=arr[j].u; - } - } - } - //Final cycle for negative checking - for(j=0;jdist[arr[j].u]+arr[j].w) - { - neg=1; - System.out.println("Negative cycle"); - break; - } - if(neg==0)//Go ahead and show results of computaion - { - System.out.println("Distance is: "+dist[end]); - System.out.println("Path followed:"); - System.out.print(source+" "); - printPath(p,end); - System.out.println(); - } + System.out.println("Distances are: "); + for (i = 0; i < v; i++) System.out.println(i + " " + dist[i]); + System.out.println("Path followed:"); + for (i = 0; i < v; i++) { + System.out.print("0 "); + printPath(p, i); + System.out.println(); + } } - /** - *@param x Source Vertex - * @param y End vertex - * @param z Weight - */ - public void addEdge(int x,int y,int z)//Adds unidirectionl Edge - { - edges[index++]=new Edge(x,y,z); + sc.close(); + } + /** + * @param source Starting vertex + * @param end Ending vertex + * @param Edge Array of edges + */ + public void show( + int source, + int end, + Edge arr[]) // Just shows results of computation, if graph is passed to it. The graph should + // be created by using addEdge() method and passed by calling getEdgeArray() method + { + int i, j, v = vertex, e = edge, neg = 0; + double dist[] = + new double + [v]; // Distance array for holding the finalized shortest path distance between source + // and all vertices + int p[] = new int[v]; // Parent array for holding the paths + for (i = 0; i < v; i++) dist[i] = Integer.MAX_VALUE; // Initializing distance values + dist[source] = 0; + p[source] = -1; + for (i = 0; i < v - 1; i++) { + for (j = 0; j < e; j++) { + if ((int) dist[arr[j].u] != Integer.MAX_VALUE + && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) { + dist[arr[j].v] = dist[arr[j].u] + arr[j].w; // Update + p[arr[j].v] = arr[j].u; + } + } } - public Edge[] getEdgeArray() + // Final cycle for negative checking + for (j = 0; j < e; j++) + if ((int) dist[arr[j].u] != Integer.MAX_VALUE && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) { + neg = 1; + System.out.println("Negative cycle"); + break; + } + if (neg == 0) // Go ahead and show results of computaion { - return edges; + System.out.println("Distance is: " + dist[end]); + System.out.println("Path followed:"); + System.out.print(source + " "); + printPath(p, end); + System.out.println(); } -} \ No newline at end of file + } + /** + * @param x Source Vertex + * @param y End vertex + * @param z Weight + */ + public void addEdge(int x, int y, int z) // Adds unidirectionl Edge + { + edges[index++] = new Edge(x, y, z); + } + + public Edge[] getEdgeArray() { + return edges; + } +} diff --git a/DataStructures/Graphs/ConnectedComponent.java b/DataStructures/Graphs/ConnectedComponent.java index 4582bfd4406f..7f9403cadaec 100644 --- a/DataStructures/Graphs/ConnectedComponent.java +++ b/DataStructures/Graphs/ConnectedComponent.java @@ -11,131 +11,129 @@ */ class Graph> { - class Node { - E name; + class Node { + E name; - public Node(E name) { - this.name = name; - } + public Node(E name) { + this.name = name; } + } - class Edge { - Node startNode, endNode; + class Edge { + Node startNode, endNode; - public Edge(Node startNode, Node endNode) { - this.startNode = startNode; - this.endNode = endNode; - } + public Edge(Node startNode, Node endNode) { + this.startNode = startNode; + this.endNode = endNode; } - - ArrayList edgeList; - ArrayList nodeList; - - public Graph() { - edgeList = new ArrayList(); - nodeList = new ArrayList(); + } + + ArrayList edgeList; + ArrayList nodeList; + + public Graph() { + edgeList = new ArrayList(); + nodeList = new ArrayList(); + } + + /** + * Adds a new Edge to the graph. If the nodes aren't yet in nodeList, they will be added to it. + * + * @param startNode the starting Node from the edge + * @param endNode the ending Node from the edge + */ + public void addEdge(E startNode, E endNode) { + Node start = null, end = null; + for (Node node : nodeList) { + if (startNode.compareTo(node.name) == 0) { + start = node; + } else if (endNode.compareTo(node.name) == 0) { + end = node; + } } - - /** - * Adds a new Edge to the graph. If the nodes aren't yet in nodeList, they - * will be added to it. - * - * @param startNode the starting Node from the edge - * @param endNode the ending Node from the edge - */ - public void addEdge(E startNode, E endNode) { - Node start = null, end = null; - for (Node node : nodeList) { - if (startNode.compareTo(node.name) == 0) { - start = node; - } else if (endNode.compareTo(node.name) == 0) { - end = node; - } - } - if (start == null) { - start = new Node(startNode); - nodeList.add(start); - } - if (end == null) { - end = new Node(endNode); - nodeList.add(end); - } - - edgeList.add(new Edge(start, end)); + if (start == null) { + start = new Node(startNode); + nodeList.add(start); + } + if (end == null) { + end = new Node(endNode); + nodeList.add(end); } - /** - * Main method used for counting the connected components. Iterates through - * the array of nodes to do a depth first search to get all nodes of the - * graph from the actual node. These nodes are added to the array - * markedNodes and will be ignored if they are chosen in the nodeList. - * - * @return returns the amount of unconnected graphs - */ - public int countGraphs() { - int count = 0; - Set markedNodes = new HashSet(); - - for (Node n : nodeList) { - if (!markedNodes.contains(n)) { - markedNodes.add(n); - markedNodes.addAll(depthFirstSearch(n, new ArrayList())); - count++; - } - } - - return count; + edgeList.add(new Edge(start, end)); + } + + /** + * Main method used for counting the connected components. Iterates through the array of nodes to + * do a depth first search to get all nodes of the graph from the actual node. These nodes are + * added to the array markedNodes and will be ignored if they are chosen in the nodeList. + * + * @return returns the amount of unconnected graphs + */ + public int countGraphs() { + int count = 0; + Set markedNodes = new HashSet(); + + for (Node n : nodeList) { + if (!markedNodes.contains(n)) { + markedNodes.add(n); + markedNodes.addAll(depthFirstSearch(n, new ArrayList())); + count++; + } } - /** - * Implementation of depth first search. - * - * @param n the actual visiting node - * @param visited A list of already visited nodes in the depth first search - * @return returns a set of visited nodes - */ - public ArrayList depthFirstSearch(Node n, ArrayList visited) { - visited.add(n); - for (Edge e : edgeList) { - if (e.startNode.equals(n) && !visited.contains(e.endNode)) { - depthFirstSearch(e.endNode, visited); - } - } - return visited; + return count; + } + + /** + * Implementation of depth first search. + * + * @param n the actual visiting node + * @param visited A list of already visited nodes in the depth first search + * @return returns a set of visited nodes + */ + public ArrayList depthFirstSearch(Node n, ArrayList visited) { + visited.add(n); + for (Edge e : edgeList) { + if (e.startNode.equals(n) && !visited.contains(e.endNode)) { + depthFirstSearch(e.endNode, visited); + } } + return visited; + } } public class ConnectedComponent { - public static void main(String[] args) { - Graph graphChars = new Graph<>(); + public static void main(String[] args) { + Graph graphChars = new Graph<>(); - // Graph 1 - graphChars.addEdge('a', 'b'); - graphChars.addEdge('a', 'e'); - graphChars.addEdge('b', 'e'); - graphChars.addEdge('b', 'c'); - graphChars.addEdge('c', 'd'); - graphChars.addEdge('d', 'a'); + // Graph 1 + graphChars.addEdge('a', 'b'); + graphChars.addEdge('a', 'e'); + graphChars.addEdge('b', 'e'); + graphChars.addEdge('b', 'c'); + graphChars.addEdge('c', 'd'); + graphChars.addEdge('d', 'a'); - graphChars.addEdge('x', 'y'); - graphChars.addEdge('x', 'z'); + graphChars.addEdge('x', 'y'); + graphChars.addEdge('x', 'z'); - graphChars.addEdge('w', 'w'); + graphChars.addEdge('w', 'w'); - Graph graphInts = new Graph<>(); + Graph graphInts = new Graph<>(); - // Graph 2 - graphInts.addEdge(1, 2); - graphInts.addEdge(2, 3); - graphInts.addEdge(2, 4); - graphInts.addEdge(3, 5); + // Graph 2 + graphInts.addEdge(1, 2); + graphInts.addEdge(2, 3); + graphInts.addEdge(2, 4); + graphInts.addEdge(3, 5); - graphInts.addEdge(7, 8); - graphInts.addEdge(8, 10); - graphInts.addEdge(10, 8); + graphInts.addEdge(7, 8); + graphInts.addEdge(8, 10); + graphInts.addEdge(10, 8); - System.out.println("Amount of different char-graphs: " + graphChars.countGraphs()); - System.out.println("Amount of different int-graphs: " + graphInts.countGraphs()); - } + System.out.println("Amount of different char-graphs: " + graphChars.countGraphs()); + System.out.println("Amount of different int-graphs: " + graphInts.countGraphs()); + } } diff --git a/DataStructures/Graphs/Cycles.java b/DataStructures/Graphs/Cycles.java index 0b0ae22d7e8d..27b0c2bf3c42 100644 --- a/DataStructures/Graphs/Cycles.java +++ b/DataStructures/Graphs/Cycles.java @@ -1,92 +1,87 @@ package DataStructures.Graphs; -import java.util.Scanner; import java.util.ArrayList; - +import java.util.Scanner; class Cycle { - private int nodes, edges; - private int[][] adjacencyMatrix; - private boolean[] visited; - ArrayList> cycles = new ArrayList>(); - + private int nodes, edges; + private int[][] adjacencyMatrix; + private boolean[] visited; + ArrayList> cycles = new ArrayList>(); - public Cycle() { - Scanner in = new Scanner(System.in); - System.out.print("Enter the no. of nodes: "); - nodes = in.nextInt(); - System.out.print("Enter the no. of Edges: "); - edges = in.nextInt(); + public Cycle() { + Scanner in = new Scanner(System.in); + System.out.print("Enter the no. of nodes: "); + nodes = in.nextInt(); + System.out.print("Enter the no. of Edges: "); + edges = in.nextInt(); - adjacencyMatrix = new int[nodes][nodes]; - visited = new boolean[nodes]; - - for (int i = 0; i < nodes; i++) { - visited[i] = false; - } + adjacencyMatrix = new int[nodes][nodes]; + visited = new boolean[nodes]; - System.out.println("Enter the details of each edges "); + for (int i = 0; i < nodes; i++) { + visited[i] = false; + } - for (int i = 0; i < edges; i++) { - int start, end; - start = in.nextInt(); - end = in.nextInt(); - adjacencyMatrix[start][end] = 1; - } - in.close(); + System.out.println("Enter the details of each edges "); + for (int i = 0; i < edges; i++) { + int start, end; + start = in.nextInt(); + end = in.nextInt(); + adjacencyMatrix[start][end] = 1; } - - public void start() { - for (int i = 0; i < nodes; i++) { - ArrayList temp = new ArrayList<>(); - dfs(i, i, temp); - for (int j = 0; j < nodes; j++) { - adjacencyMatrix[i][j] = 0; - adjacencyMatrix[j][i] = 0; - } - } + in.close(); + } + + public void start() { + for (int i = 0; i < nodes; i++) { + ArrayList temp = new ArrayList<>(); + dfs(i, i, temp); + for (int j = 0; j < nodes; j++) { + adjacencyMatrix[i][j] = 0; + adjacencyMatrix[j][i] = 0; + } } - - private void dfs(Integer start, Integer curr, ArrayList temp) { - temp.add(curr); - visited[curr] = true; - for (int i = 0; i < nodes; i++) { - if (adjacencyMatrix[curr][i] == 1) { - if (i == start) { - cycles.add(new ArrayList(temp)); - } else { - if (!visited[i]) { - dfs(start, i, temp); - } - } - } - } - - if (temp.size() > 0) { - temp.remove(temp.size() - 1); + } + + private void dfs(Integer start, Integer curr, ArrayList temp) { + temp.add(curr); + visited[curr] = true; + for (int i = 0; i < nodes; i++) { + if (adjacencyMatrix[curr][i] == 1) { + if (i == start) { + cycles.add(new ArrayList(temp)); + } else { + if (!visited[i]) { + dfs(start, i, temp); + } } - visited[curr] = false; + } } - public void printAll() { - for (int i = 0; i < cycles.size(); i++) { - for (int j = 0; j < cycles.get(i).size(); j++) { - System.out.print(cycles.get(i).get(j) + " -> "); - } - System.out.println(cycles.get(i).get(0)); - System.out.println(); - } - + if (temp.size() > 0) { + temp.remove(temp.size() - 1); } - + visited[curr] = false; + } + + public void printAll() { + for (int i = 0; i < cycles.size(); i++) { + for (int j = 0; j < cycles.get(i).size(); j++) { + System.out.print(cycles.get(i).get(j) + " -> "); + } + System.out.println(cycles.get(i).get(0)); + System.out.println(); + } + } } public class Cycles { - public static void main(String[] args) { - Cycle c = new Cycle(); - c.start(); - c.printAll(); - } -} \ No newline at end of file + public static void main(String[] args) { + Cycle c = new Cycle(); + c.start(); + c.printAll(); + } +} diff --git a/DataStructures/Graphs/FloydWarshall.java b/DataStructures/Graphs/FloydWarshall.java index d6a6b48d4770..84cc3eddf6be 100644 --- a/DataStructures/Graphs/FloydWarshall.java +++ b/DataStructures/Graphs/FloydWarshall.java @@ -4,70 +4,74 @@ import java.util.Scanner; public class FloydWarshall { - private int DistanceMatrix[][]; - private int numberofvertices;//number of vertices in the graph - public static final int INFINITY = 999; + private int DistanceMatrix[][]; + private int numberofvertices; // number of vertices in the graph + public static final int INFINITY = 999; - public FloydWarshall(int numberofvertices) { - DistanceMatrix = new int[numberofvertices + 1][numberofvertices + 1];//stores the value of distance from all the possible path form the source vertex to destination vertex - Arrays.fill(DistanceMatrix, 0); - this.numberofvertices = numberofvertices; - } + public FloydWarshall(int numberofvertices) { + DistanceMatrix = + new int[numberofvertices + 1] + [numberofvertices + + 1]; // stores the value of distance from all the possible path form the source + // vertex to destination vertex + Arrays.fill(DistanceMatrix, 0); + this.numberofvertices = numberofvertices; + } - public void floydwarshall(int AdjacencyMatrix[][])//calculates all the distances from source to destination vertex - { - for (int source = 1; source <= numberofvertices; source++) { - for (int destination = 1; destination <= numberofvertices; destination++) { - DistanceMatrix[source][destination] = AdjacencyMatrix[source][destination]; - } - } - for (int intermediate = 1; intermediate <= numberofvertices; intermediate++) { - for (int source = 1; source <= numberofvertices; source++) { - for (int destination = 1; destination <= numberofvertices; destination++) { - if (DistanceMatrix[source][intermediate] + DistanceMatrix[intermediate][destination] - < DistanceMatrix[source][destination]) - // if the new distance calculated is less then the earlier shortest - // calculated distance it get replaced as new shortest distance - { - DistanceMatrix[source][destination] = DistanceMatrix[source][intermediate] - + DistanceMatrix[intermediate][destination]; - } - } - } - } - for (int source = 1; source <= numberofvertices; source++) - System.out.print("\t" + source); - System.out.println(); - for (int source = 1; source <= numberofvertices; source++) { - System.out.print(source + "\t"); - for (int destination = 1; destination <= numberofvertices; destination++) { - System.out.print(DistanceMatrix[source][destination] + "\t"); - } - System.out.println(); + public void floydwarshall( + int AdjacencyMatrix[][]) // calculates all the distances from source to destination vertex + { + for (int source = 1; source <= numberofvertices; source++) { + for (int destination = 1; destination <= numberofvertices; destination++) { + DistanceMatrix[source][destination] = AdjacencyMatrix[source][destination]; + } + } + for (int intermediate = 1; intermediate <= numberofvertices; intermediate++) { + for (int source = 1; source <= numberofvertices; source++) { + for (int destination = 1; destination <= numberofvertices; destination++) { + if (DistanceMatrix[source][intermediate] + DistanceMatrix[intermediate][destination] + < DistanceMatrix[source][destination]) + // if the new distance calculated is less then the earlier shortest + // calculated distance it get replaced as new shortest distance + { + DistanceMatrix[source][destination] = + DistanceMatrix[source][intermediate] + DistanceMatrix[intermediate][destination]; + } } + } + } + for (int source = 1; source <= numberofvertices; source++) System.out.print("\t" + source); + System.out.println(); + for (int source = 1; source <= numberofvertices; source++) { + System.out.print(source + "\t"); + for (int destination = 1; destination <= numberofvertices; destination++) { + System.out.print(DistanceMatrix[source][destination] + "\t"); + } + System.out.println(); } + } - public static void main(String... arg) { - Scanner scan = new Scanner(System.in); - System.out.println("Enter the number of vertices"); - int numberOfVertices = scan.nextInt(); - int[][] adjacencyMatrix = new int[numberOfVertices + 1][numberOfVertices + 1]; - System.out.println("Enter the Weighted Matrix for the graph"); - for (int source = 1; source <= numberOfVertices; source++) { - for (int destination = 1; destination <= numberOfVertices; destination++) { - adjacencyMatrix[source][destination] = scan.nextInt(); - if (source == destination) { - adjacencyMatrix[source][destination] = 0; - continue; - } - if (adjacencyMatrix[source][destination] == 0) { - adjacencyMatrix[source][destination] = INFINITY; - } - } + public static void main(String... arg) { + Scanner scan = new Scanner(System.in); + System.out.println("Enter the number of vertices"); + int numberOfVertices = scan.nextInt(); + int[][] adjacencyMatrix = new int[numberOfVertices + 1][numberOfVertices + 1]; + System.out.println("Enter the Weighted Matrix for the graph"); + for (int source = 1; source <= numberOfVertices; source++) { + for (int destination = 1; destination <= numberOfVertices; destination++) { + adjacencyMatrix[source][destination] = scan.nextInt(); + if (source == destination) { + adjacencyMatrix[source][destination] = 0; + continue; + } + if (adjacencyMatrix[source][destination] == 0) { + adjacencyMatrix[source][destination] = INFINITY; } - System.out.println("The Transitive Closure of the Graph"); - FloydWarshall floydwarshall = new FloydWarshall(numberOfVertices); - floydwarshall.floydwarshall(adjacencyMatrix); - scan.close(); + } } + System.out.println("The Transitive Closure of the Graph"); + FloydWarshall floydwarshall = new FloydWarshall(numberOfVertices); + floydwarshall.floydwarshall(adjacencyMatrix); + scan.close(); + } } diff --git a/DataStructures/Graphs/Graphs.java b/DataStructures/Graphs/Graphs.java index ea03b05f246b..9a1f713836b2 100644 --- a/DataStructures/Graphs/Graphs.java +++ b/DataStructures/Graphs/Graphs.java @@ -1,133 +1,129 @@ package DataStructures.Graphs; import java.util.ArrayList; -import java.lang.StringBuilder; class AdjacencyListGraph> { - ArrayList verticies; + ArrayList verticies; - public AdjacencyListGraph() { - verticies = new ArrayList<>(); - } + public AdjacencyListGraph() { + verticies = new ArrayList<>(); + } - private class Vertex { - E data; - ArrayList adjacentVerticies; + private class Vertex { + E data; + ArrayList adjacentVerticies; - public Vertex(E data) { - adjacentVerticies = new ArrayList<>(); - this.data = data; - } + public Vertex(E data) { + adjacentVerticies = new ArrayList<>(); + this.data = data; + } - public boolean addAdjacentVertex(Vertex to) { - for (Vertex v : adjacentVerticies) { - if (v.data.compareTo(to.data) == 0) { - return false; // the edge already exists - } - } - return adjacentVerticies.add(to); // this will return true; + public boolean addAdjacentVertex(Vertex to) { + for (Vertex v : adjacentVerticies) { + if (v.data.compareTo(to.data) == 0) { + return false; // the edge already exists } + } + return adjacentVerticies.add(to); // this will return true; + } - public boolean removeAdjacentVertex(E to) { - // use indexes here so it is possible to - // remove easily without implementing - // equals method that ArrayList.remove(Object o) uses - for (int i = 0; i < adjacentVerticies.size(); i++) { - if (adjacentVerticies.get(i).data.compareTo(to) == 0) { - adjacentVerticies.remove(i); - return true; - } - } - return false; + public boolean removeAdjacentVertex(E to) { + // use indexes here so it is possible to + // remove easily without implementing + // equals method that ArrayList.remove(Object o) uses + for (int i = 0; i < adjacentVerticies.size(); i++) { + if (adjacentVerticies.get(i).data.compareTo(to) == 0) { + adjacentVerticies.remove(i); + return true; } + } + return false; } + } - /** - * this method removes an edge from the graph between two specified - * verticies - * - * @param from the data of the vertex the edge is from - * @param to the data of the vertex the edge is going to - * @return returns false if the edge doesn't exist, returns true if the edge exists and is removed - */ - public boolean removeEdge(E from, E to) { - Vertex fromV = null; - for (Vertex v : verticies) { - if (from.compareTo(v.data) == 0) { - fromV = v; - break; - } - } - if (fromV == null) return false; - return fromV.removeAdjacentVertex(to); + /** + * this method removes an edge from the graph between two specified verticies + * + * @param from the data of the vertex the edge is from + * @param to the data of the vertex the edge is going to + * @return returns false if the edge doesn't exist, returns true if the edge exists and is removed + */ + public boolean removeEdge(E from, E to) { + Vertex fromV = null; + for (Vertex v : verticies) { + if (from.compareTo(v.data) == 0) { + fromV = v; + break; + } } + if (fromV == null) return false; + return fromV.removeAdjacentVertex(to); + } - /** - * this method adds an edge to the graph between two specified - * verticies - * - * @param from the data of the vertex the edge is from - * @param to the data of the vertex the edge is going to - * @return returns true if the edge did not exist, return false if it already did - */ - public boolean addEdge(E from, E to) { - Vertex fromV = null, toV = null; - for (Vertex v : verticies) { - if (from.compareTo(v.data) == 0) { // see if from vertex already exists - fromV = v; - } else if (to.compareTo(v.data) == 0) { // see if to vertex already exists - toV = v; - } - if (fromV != null && toV != null) break; // both nodes exist so stop searching - } - if (fromV == null) { - fromV = new Vertex(from); - verticies.add(fromV); - } - if (toV == null) { - toV = new Vertex(to); - verticies.add(toV); - } - return fromV.addAdjacentVertex(toV); + /** + * this method adds an edge to the graph between two specified verticies + * + * @param from the data of the vertex the edge is from + * @param to the data of the vertex the edge is going to + * @return returns true if the edge did not exist, return false if it already did + */ + public boolean addEdge(E from, E to) { + Vertex fromV = null, toV = null; + for (Vertex v : verticies) { + if (from.compareTo(v.data) == 0) { // see if from vertex already exists + fromV = v; + } else if (to.compareTo(v.data) == 0) { // see if to vertex already exists + toV = v; + } + if (fromV != null && toV != null) break; // both nodes exist so stop searching + } + if (fromV == null) { + fromV = new Vertex(from); + verticies.add(fromV); + } + if (toV == null) { + toV = new Vertex(to); + verticies.add(toV); } + return fromV.addAdjacentVertex(toV); + } - /** - * this gives a list of verticies in the graph and their adjacencies - * - * @return returns a string describing this graph - */ - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - for (Vertex v : verticies) { - sb.append("Vertex: "); - sb.append(v.data); - sb.append("\n"); - sb.append("Adjacent verticies: "); - for (Vertex v2 : v.adjacentVerticies) { - sb.append(v2.data); - sb.append(" "); - } - sb.append("\n"); - } - return sb.toString(); + /** + * this gives a list of verticies in the graph and their adjacencies + * + * @return returns a string describing this graph + */ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + for (Vertex v : verticies) { + sb.append("Vertex: "); + sb.append(v.data); + sb.append("\n"); + sb.append("Adjacent verticies: "); + for (Vertex v2 : v.adjacentVerticies) { + sb.append(v2.data); + sb.append(" "); + } + sb.append("\n"); } + return sb.toString(); + } } public class Graphs { - public static void main(String args[]) { - AdjacencyListGraph graph = new AdjacencyListGraph<>(); - assert graph.addEdge(1, 2); - assert graph.addEdge(1, 5); - assert graph.addEdge(2, 5); - assert !graph.addEdge(1, 2); - assert graph.addEdge(2, 3); - assert graph.addEdge(3, 4); - assert graph.addEdge(4, 1); - assert !graph.addEdge(2, 3); - System.out.println(graph); - } - + public static void main(String args[]) { + AdjacencyListGraph graph = new AdjacencyListGraph<>(); + assert graph.addEdge(1, 2); + assert graph.addEdge(1, 5); + assert graph.addEdge(2, 5); + assert !graph.addEdge(1, 2); + assert graph.addEdge(2, 3); + assert graph.addEdge(3, 4); + assert graph.addEdge(4, 1); + assert !graph.addEdge(2, 3); + System.out.println(graph); + } } diff --git a/DataStructures/Graphs/Kruskal.java b/DataStructures/Graphs/Kruskal.java index 731b821be076..941f30593ad9 100644 --- a/DataStructures/Graphs/Kruskal.java +++ b/DataStructures/Graphs/Kruskal.java @@ -1,8 +1,12 @@ -//Problem -> Connect all the edges with the minimum cost. -//Possible Solution -> Kruskal Algorithm (KA), KA finds the minimum-spanning-tree, which means, the group of edges with the minimum sum of their weights that connect the whole graph. -//The graph needs to be connected, because if there are nodes impossible to reach, there are no edges that could connect every node in the graph. -//KA is a Greedy Algorithm, because edges are analysed based on their weights, that is why a Priority Queue is used, to take first those less weighted. -//This implementations below has some changes compared to conventional ones, but they are explained all along the code. +// Problem -> Connect all the edges with the minimum cost. +// Possible Solution -> Kruskal Algorithm (KA), KA finds the minimum-spanning-tree, which means, the +// group of edges with the minimum sum of their weights that connect the whole graph. +// The graph needs to be connected, because if there are nodes impossible to reach, there are no +// edges that could connect every node in the graph. +// KA is a Greedy Algorithm, because edges are analysed based on their weights, that is why a +// Priority Queue is used, to take first those less weighted. +// This implementations below has some changes compared to conventional ones, but they are explained +// all along the code. import java.util.Comparator; import java.util.HashSet; @@ -10,89 +14,90 @@ public class Kruskal { - //Complexity: O(E log V) time, where E is the number of edges in the graph and V is the number of vertices + // Complexity: O(E log V) time, where E is the number of edges in the graph and V is the number of + // vertices - private static class Edge{ - private int from; - private int to; - private int weight; + private static class Edge { + private int from; + private int to; + private int weight; - public Edge(int from, int to, int weight) { - this.from = from; - this.to = to; - this.weight = weight; - } + public Edge(int from, int to, int weight) { + this.from = from; + this.to = to; + this.weight = weight; } + } - private static void addEdge (HashSet[] graph, int from, int to, int weight) { - graph[from].add(new Edge(from, to, weight)); - } + private static void addEdge(HashSet[] graph, int from, int to, int weight) { + graph[from].add(new Edge(from, to, weight)); + } - public static void main(String[] args) { - HashSet[] graph = new HashSet[7]; - for (int i = 0; i < graph.length; i++) { - graph[i] = new HashSet<>(); - } - addEdge(graph,0, 1, 2); - addEdge(graph,0, 2, 3); - addEdge(graph,0, 3, 3); - addEdge(graph,1, 2, 4); - addEdge(graph,2, 3, 5); - addEdge(graph,1, 4, 3); - addEdge(graph,2, 4, 1); - addEdge(graph,3, 5, 7); - addEdge(graph,4, 5, 8); - addEdge(graph,5, 6, 9); + public static void main(String[] args) { + HashSet[] graph = new HashSet[7]; + for (int i = 0; i < graph.length; i++) { + graph[i] = new HashSet<>(); + } + addEdge(graph, 0, 1, 2); + addEdge(graph, 0, 2, 3); + addEdge(graph, 0, 3, 3); + addEdge(graph, 1, 2, 4); + addEdge(graph, 2, 3, 5); + addEdge(graph, 1, 4, 3); + addEdge(graph, 2, 4, 1); + addEdge(graph, 3, 5, 7); + addEdge(graph, 4, 5, 8); + addEdge(graph, 5, 6, 9); - System.out.println("Initial Graph: "); - for (int i = 0; i < graph.length; i++) { - for (Edge edge: graph[i]) { - System.out.println(i + " <-- weight " + edge.weight + " --> " + edge.to); - } - } + System.out.println("Initial Graph: "); + for (int i = 0; i < graph.length; i++) { + for (Edge edge : graph[i]) { + System.out.println(i + " <-- weight " + edge.weight + " --> " + edge.to); + } + } - Kruskal k = new Kruskal(); - HashSet[] solGraph = k.kruskal(graph); + Kruskal k = new Kruskal(); + HashSet[] solGraph = k.kruskal(graph); - System.out.println("\nMinimal Graph: "); - for (int i = 0; i < solGraph.length; i++) { - for (Edge edge: solGraph[i]) { - System.out.println(i + " <-- weight " + edge.weight + " --> " + edge.to); - } - } + System.out.println("\nMinimal Graph: "); + for (int i = 0; i < solGraph.length; i++) { + for (Edge edge : solGraph[i]) { + System.out.println(i + " <-- weight " + edge.weight + " --> " + edge.to); + } } + } - public HashSet[] kruskal (HashSet[] graph) { - int nodes = graph.length; - int [] captain = new int [nodes]; - //captain of i, stores the set with all the connected nodes to i - HashSet[] connectedGroups = new HashSet[nodes]; - HashSet[] minGraph = new HashSet[nodes]; - PriorityQueue edges = new PriorityQueue<>((Comparator.comparingInt(edge -> edge.weight))); - for (int i = 0; i < nodes; i++) { - minGraph[i] = new HashSet<>(); - connectedGroups[i] = new HashSet<>(); - connectedGroups[i].add(i); - captain[i] = i; - edges.addAll(graph[i]); - } - int connectedElements = 0; - //as soon as two sets merge all the elements, the algorithm must stop - while (connectedElements != nodes && !edges.isEmpty()) { - Edge edge = edges.poll(); - //This if avoids cycles - if (!connectedGroups[captain[edge.from]].contains(edge.to) - && !connectedGroups[captain[edge.to]].contains(edge.from)) { - //merge sets of the captains of each point connected by the edge - connectedGroups[captain[edge.from]].addAll(connectedGroups[captain[edge.to]]); - //update captains of the elements merged - connectedGroups[captain[edge.from]].forEach(i -> captain[i] = captain[edge.from]); - //add Edge to minimal graph - addEdge(minGraph, edge.from, edge.to, edge.weight); - //count how many elements have been merged - connectedElements = connectedGroups[captain[edge.from]].size(); - } - } - return minGraph; + public HashSet[] kruskal(HashSet[] graph) { + int nodes = graph.length; + int[] captain = new int[nodes]; + // captain of i, stores the set with all the connected nodes to i + HashSet[] connectedGroups = new HashSet[nodes]; + HashSet[] minGraph = new HashSet[nodes]; + PriorityQueue edges = new PriorityQueue<>((Comparator.comparingInt(edge -> edge.weight))); + for (int i = 0; i < nodes; i++) { + minGraph[i] = new HashSet<>(); + connectedGroups[i] = new HashSet<>(); + connectedGroups[i].add(i); + captain[i] = i; + edges.addAll(graph[i]); + } + int connectedElements = 0; + // as soon as two sets merge all the elements, the algorithm must stop + while (connectedElements != nodes && !edges.isEmpty()) { + Edge edge = edges.poll(); + // This if avoids cycles + if (!connectedGroups[captain[edge.from]].contains(edge.to) + && !connectedGroups[captain[edge.to]].contains(edge.from)) { + // merge sets of the captains of each point connected by the edge + connectedGroups[captain[edge.from]].addAll(connectedGroups[captain[edge.to]]); + // update captains of the elements merged + connectedGroups[captain[edge.from]].forEach(i -> captain[i] = captain[edge.from]); + // add Edge to minimal graph + addEdge(minGraph, edge.from, edge.to, edge.weight); + // count how many elements have been merged + connectedElements = connectedGroups[captain[edge.from]].size(); + } } + return minGraph; + } } diff --git a/DataStructures/Graphs/MatrixGraphs.java b/DataStructures/Graphs/MatrixGraphs.java index 32a7c990e3ef..2265d2826a1b 100644 --- a/DataStructures/Graphs/MatrixGraphs.java +++ b/DataStructures/Graphs/MatrixGraphs.java @@ -2,145 +2,141 @@ public class MatrixGraphs { - public static void main(String args[]) { - AdjacencyMatrixGraph graph = new AdjacencyMatrixGraph(10); - graph.addEdge(1, 2); - graph.addEdge(1, 5); - graph.addEdge(2, 5); - graph.addEdge(1, 2); - graph.addEdge(2, 3); - graph.addEdge(3, 4); - graph.addEdge(4, 1); - graph.addEdge(2, 3); - System.out.println(graph); - } - + public static void main(String args[]) { + AdjacencyMatrixGraph graph = new AdjacencyMatrixGraph(10); + graph.addEdge(1, 2); + graph.addEdge(1, 5); + graph.addEdge(2, 5); + graph.addEdge(1, 2); + graph.addEdge(2, 3); + graph.addEdge(3, 4); + graph.addEdge(4, 1); + graph.addEdge(2, 3); + System.out.println(graph); + } } class AdjacencyMatrixGraph { - private int _numberOfVertices; - private int _numberOfEdges; - private int[][] _adjacency; - - static final int EDGE_EXIST = 1; - static final int EDGE_NONE = 0; - - public AdjacencyMatrixGraph(int givenNumberOfVertices) { - this.setNumberOfVertices(givenNumberOfVertices); - this.setNumberOfEdges(0); - this.setAdjacency(new int[givenNumberOfVertices][givenNumberOfVertices]); - for (int i = 0; i < givenNumberOfVertices; i++) { - for (int j = 0; j < givenNumberOfVertices; j++) { - this.adjacency()[i][j] = AdjacencyMatrixGraph.EDGE_NONE; - } - } + private int _numberOfVertices; + private int _numberOfEdges; + private int[][] _adjacency; + + static final int EDGE_EXIST = 1; + static final int EDGE_NONE = 0; + + public AdjacencyMatrixGraph(int givenNumberOfVertices) { + this.setNumberOfVertices(givenNumberOfVertices); + this.setNumberOfEdges(0); + this.setAdjacency(new int[givenNumberOfVertices][givenNumberOfVertices]); + for (int i = 0; i < givenNumberOfVertices; i++) { + for (int j = 0; j < givenNumberOfVertices; j++) { + this.adjacency()[i][j] = AdjacencyMatrixGraph.EDGE_NONE; + } } + } - private void setNumberOfVertices(int newNumberOfVertices) { - this._numberOfVertices = newNumberOfVertices; - } + private void setNumberOfVertices(int newNumberOfVertices) { + this._numberOfVertices = newNumberOfVertices; + } - public int numberOfVertices() { - return this._numberOfVertices; - } + public int numberOfVertices() { + return this._numberOfVertices; + } - private void setNumberOfEdges(int newNumberOfEdges) { - this._numberOfEdges = newNumberOfEdges; - } + private void setNumberOfEdges(int newNumberOfEdges) { + this._numberOfEdges = newNumberOfEdges; + } - public int numberOfEdges() { - return this._numberOfEdges; - } + public int numberOfEdges() { + return this._numberOfEdges; + } - private void setAdjacency(int[][] newAdjacency) { - this._adjacency = newAdjacency; - } + private void setAdjacency(int[][] newAdjacency) { + this._adjacency = newAdjacency; + } - private int[][] adjacency() { - return this._adjacency; - } + private int[][] adjacency() { + return this._adjacency; + } - private boolean adjacencyOfEdgeDoesExist(int from, int to) { - return (this.adjacency()[from][to] != AdjacencyMatrixGraph.EDGE_NONE); - } + private boolean adjacencyOfEdgeDoesExist(int from, int to) { + return (this.adjacency()[from][to] != AdjacencyMatrixGraph.EDGE_NONE); + } - public boolean vertexDoesExist(int aVertex) { - if (aVertex >= 0 && aVertex < this.numberOfVertices()) { - return true; - } else { - return false; - } + public boolean vertexDoesExist(int aVertex) { + if (aVertex >= 0 && aVertex < this.numberOfVertices()) { + return true; + } else { + return false; } + } - public boolean edgeDoesExist(int from, int to) { - if (this.vertexDoesExist(from) && this.vertexDoesExist(to)) { - return (this.adjacencyOfEdgeDoesExist(from, to)); - } - - return false; + public boolean edgeDoesExist(int from, int to) { + if (this.vertexDoesExist(from) && this.vertexDoesExist(to)) { + return (this.adjacencyOfEdgeDoesExist(from, to)); } - /** - * This method adds an edge to the graph between two specified - * vertices - * - * @param from the data of the vertex the edge is from - * @param to the data of the vertex the edge is going to - * @return returns true if the edge did not exist, return false if it already did - */ - public boolean addEdge(int from, int to) { - if (this.vertexDoesExist(from) && this.vertexDoesExist(to)) { - if (!this.adjacencyOfEdgeDoesExist(from, to)) { - this.adjacency()[from][to] = AdjacencyMatrixGraph.EDGE_EXIST; - this.adjacency()[to][from] = AdjacencyMatrixGraph.EDGE_EXIST; - this.setNumberOfEdges(this.numberOfEdges() + 1); - return true; - } - } - - return false; + return false; + } + + /** + * This method adds an edge to the graph between two specified vertices + * + * @param from the data of the vertex the edge is from + * @param to the data of the vertex the edge is going to + * @return returns true if the edge did not exist, return false if it already did + */ + public boolean addEdge(int from, int to) { + if (this.vertexDoesExist(from) && this.vertexDoesExist(to)) { + if (!this.adjacencyOfEdgeDoesExist(from, to)) { + this.adjacency()[from][to] = AdjacencyMatrixGraph.EDGE_EXIST; + this.adjacency()[to][from] = AdjacencyMatrixGraph.EDGE_EXIST; + this.setNumberOfEdges(this.numberOfEdges() + 1); + return true; + } } - /** - * this method removes an edge from the graph between two specified - * vertices - * - * @param from the data of the vertex the edge is from - * @param to the data of the vertex the edge is going to - * @return returns false if the edge doesn't exist, returns true if the edge exists and is removed - */ - public boolean removeEdge(int from, int to) { - if (!this.vertexDoesExist(from) || !this.vertexDoesExist(to)) { - if (this.adjacencyOfEdgeDoesExist(from, to)) { - this.adjacency()[from][to] = AdjacencyMatrixGraph.EDGE_NONE; - this.adjacency()[to][from] = AdjacencyMatrixGraph.EDGE_NONE; - this.setNumberOfEdges(this.numberOfEdges() - 1); - return true; - } - } - return false; + return false; + } + + /** + * this method removes an edge from the graph between two specified vertices + * + * @param from the data of the vertex the edge is from + * @param to the data of the vertex the edge is going to + * @return returns false if the edge doesn't exist, returns true if the edge exists and is removed + */ + public boolean removeEdge(int from, int to) { + if (!this.vertexDoesExist(from) || !this.vertexDoesExist(to)) { + if (this.adjacencyOfEdgeDoesExist(from, to)) { + this.adjacency()[from][to] = AdjacencyMatrixGraph.EDGE_NONE; + this.adjacency()[to][from] = AdjacencyMatrixGraph.EDGE_NONE; + this.setNumberOfEdges(this.numberOfEdges() - 1); + return true; + } } - - /** - * this gives a list of vertices in the graph and their adjacencies - * - * @return returns a string describing this graph - */ - public String toString() { - String s = " "; - for (int i = 0; i < this.numberOfVertices(); i++) { - s = s + String.valueOf(i) + " "; - } - s = s + " \n"; - - for (int i = 0; i < this.numberOfVertices(); i++) { - s = s + String.valueOf(i) + " : "; - for (int j = 0; j < this.numberOfVertices(); j++) { - s = s + String.valueOf(this._adjacency[i][j]) + " "; - } - s = s + "\n"; - } - return s; + return false; + } + + /** + * this gives a list of vertices in the graph and their adjacencies + * + * @return returns a string describing this graph + */ + public String toString() { + String s = " "; + for (int i = 0; i < this.numberOfVertices(); i++) { + s = s + String.valueOf(i) + " "; } - + s = s + " \n"; + + for (int i = 0; i < this.numberOfVertices(); i++) { + s = s + String.valueOf(i) + " : "; + for (int j = 0; j < this.numberOfVertices(); j++) { + s = s + String.valueOf(this._adjacency[i][j]) + " "; + } + s = s + "\n"; + } + return s; + } } diff --git a/DataStructures/Graphs/PrimMST.java b/DataStructures/Graphs/PrimMST.java index 474893775870..9c3b973ffd63 100644 --- a/DataStructures/Graphs/PrimMST.java +++ b/DataStructures/Graphs/PrimMST.java @@ -1,106 +1,102 @@ package DataStructures.Graphs; /** - * A Java program for Prim's Minimum Spanning Tree (MST) algorithm. - * adjacency matrix representation of the graph + * A Java program for Prim's Minimum Spanning Tree (MST) algorithm. adjacency matrix representation + * of the graph */ class PrimMST { - // Number of vertices in the graph - private static final int V = 5; - - // A utility function to find the vertex with minimum key - // value, from the set of vertices not yet included in MST - int minKey(int key[], Boolean mstSet[]) { - // Initialize min value - int min = Integer.MAX_VALUE, min_index = -1; - - for (int v = 0; v < V; v++) - if (mstSet[v] == false && key[v] < min) { - min = key[v]; - min_index = v; - } - - return min_index; + // Number of vertices in the graph + private static final int V = 5; + + // A utility function to find the vertex with minimum key + // value, from the set of vertices not yet included in MST + int minKey(int key[], Boolean mstSet[]) { + // Initialize min value + int min = Integer.MAX_VALUE, min_index = -1; + + for (int v = 0; v < V; v++) + if (mstSet[v] == false && key[v] < min) { + min = key[v]; + min_index = v; + } + + return min_index; + } + + // A utility function to print the constructed MST stored in + // parent[] + void printMST(int parent[], int n, int graph[][]) { + System.out.println("Edge Weight"); + for (int i = 1; i < V; i++) + System.out.println(parent[i] + " - " + i + " " + graph[i][parent[i]]); + } + + // Function to construct and print MST for a graph represented + // using adjacency matrix representation + void primMST(int graph[][]) { + // Array to store constructed MST + int parent[] = new int[V]; + + // Key values used to pick minimum weight edge in cut + int key[] = new int[V]; + + // To represent set of vertices not yet included in MST + Boolean mstSet[] = new Boolean[V]; + + // Initialize all keys as INFINITE + for (int i = 0; i < V; i++) { + key[i] = Integer.MAX_VALUE; + mstSet[i] = false; } - // A utility function to print the constructed MST stored in - // parent[] - void printMST(int parent[], int n, int graph[][]) { - System.out.println("Edge Weight"); - for (int i = 1; i < V; i++) - System.out.println(parent[i] + " - " + i + " " + - graph[i][parent[i]]); - } - - // Function to construct and print MST for a graph represented - // using adjacency matrix representation - void primMST(int graph[][]) { - // Array to store constructed MST - int parent[] = new int[V]; - - // Key values used to pick minimum weight edge in cut - int key[] = new int[V]; - - // To represent set of vertices not yet included in MST - Boolean mstSet[] = new Boolean[V]; - - // Initialize all keys as INFINITE - for (int i = 0; i < V; i++) { - key[i] = Integer.MAX_VALUE; - mstSet[i] = false; + // Always include first 1st vertex in MST. + key[0] = 0; // Make key 0 so that this vertex is + // picked as first vertex + parent[0] = -1; // First node is always root of MST + + // The MST will have V vertices + for (int count = 0; count < V - 1; count++) { + // Pick thd minimum key vertex from the set of vertices + // not yet included in MST + int u = minKey(key, mstSet); + + // Add the picked vertex to the MST Set + mstSet[u] = true; + + // Update key value and parent index of the adjacent + // vertices of the picked vertex. Consider only those + // vertices which are not yet included in MST + for (int v = 0; v < V; v++) + + // graph[u][v] is non zero only for adjacent vertices of m + // mstSet[v] is false for vertices not yet included in MST + // Update the key only if graph[u][v] is smaller than key[v] + if (graph[u][v] != 0 && mstSet[v] == false && graph[u][v] < key[v]) { + parent[v] = u; + key[v] = graph[u][v]; } - - // Always include first 1st vertex in MST. - key[0] = 0; // Make key 0 so that this vertex is - // picked as first vertex - parent[0] = -1; // First node is always root of MST - - // The MST will have V vertices - for (int count = 0; count < V - 1; count++) { - // Pick thd minimum key vertex from the set of vertices - // not yet included in MST - int u = minKey(key, mstSet); - - // Add the picked vertex to the MST Set - mstSet[u] = true; - - // Update key value and parent index of the adjacent - // vertices of the picked vertex. Consider only those - // vertices which are not yet included in MST - for (int v = 0; v < V; v++) - - // graph[u][v] is non zero only for adjacent vertices of m - // mstSet[v] is false for vertices not yet included in MST - // Update the key only if graph[u][v] is smaller than key[v] - if (graph[u][v] != 0 && mstSet[v] == false && - graph[u][v] < key[v]) { - parent[v] = u; - key[v] = graph[u][v]; - } - } - - // print the constructed MST - printMST(parent, V, graph); } - public static void main(String[] args) { - /* Let us create the following graph - 2 3 - (0)--(1)--(2) - | / \ | - 6| 8/ \5 |7 - | / \ | - (3)-------(4) - 9 */ - PrimMST t = new PrimMST(); - int graph[][] = new int[][]{{0, 2, 0, 6, 0}, - {2, 0, 3, 8, 5}, - {0, 3, 0, 0, 7}, - {6, 8, 0, 0, 9}, - {0, 5, 7, 9, 0}, + // print the constructed MST + printMST(parent, V, graph); + } + + public static void main(String[] args) { + /* Let us create the following graph + 2 3 + (0)--(1)--(2) + | / \ | + 6| 8/ \5 |7 + | / \ | + (3)-------(4) + 9 */ + PrimMST t = new PrimMST(); + int graph[][] = + new int[][] { + {0, 2, 0, 6, 0}, {2, 0, 3, 8, 5}, {0, 3, 0, 0, 7}, {6, 8, 0, 0, 9}, {0, 5, 7, 9, 0}, }; - // Print the solution - t.primMST(graph); - } + // Print the solution + t.primMST(graph); + } } diff --git a/DataStructures/HashMap/Hashing/HashMap.java b/DataStructures/HashMap/Hashing/HashMap.java index c7d6c7c4beb6..38ea337fa1ec 100644 --- a/DataStructures/HashMap/Hashing/HashMap.java +++ b/DataStructures/HashMap/Hashing/HashMap.java @@ -1,148 +1,145 @@ package DataStructures.HashMap.Hashing; public class HashMap { - private int hsize; - private LinkedList[] buckets; - - public HashMap(int hsize) { - buckets = new LinkedList[hsize]; - for (int i = 0; i < hsize; i++) { - buckets[i] = new LinkedList(); - // Java requires explicit initialisaton of each object - } - this.hsize = hsize; + private int hsize; + private LinkedList[] buckets; + + public HashMap(int hsize) { + buckets = new LinkedList[hsize]; + for (int i = 0; i < hsize; i++) { + buckets[i] = new LinkedList(); + // Java requires explicit initialisaton of each object } + this.hsize = hsize; + } + + public int hashing(int key) { + int hash = key % hsize; + if (hash < 0) hash += hsize; + return hash; + } + + public void insertHash(int key) { + int hash = hashing(key); + buckets[hash].insert(key); + } - public int hashing(int key) { - int hash = key % hsize; - if (hash < 0) - hash += hsize; - return hash; + public void deleteHash(int key) { + int hash = hashing(key); + + buckets[hash].delete(key); + } + + public void displayHashtable() { + for (int i = 0; i < hsize; i++) { + System.out.printf("Bucket %d :", i); + System.out.println(buckets[i].display()); } + } - public void insertHash(int key) { - int hash = hashing(key); - buckets[hash].insert(key); + public static class LinkedList { + private Node first; + + public LinkedList() { + first = null; } + public void insert(int key) { + if (isEmpty()) { + first = new Node(key); + return; + } - public void deleteHash(int key) { - int hash = hashing(key); + Node temp = findEnd(first); + temp.setNext(new Node(key)); + } - buckets[hash].delete(key); + private Node findEnd(Node n) { + if (n.getNext() == null) { + return n; + } else { + return findEnd(n.getNext()); + } + } + + public Node findKey(int key) { + if (!isEmpty()) { + return findKey(first, key); + } else { + System.out.println("List is empty"); + return null; + } + } + + private Node findKey(Node n, int key) { + if (n.getKey() == key) { + return n; + } else if (n.getNext() == null) { + System.out.println("Key not found"); + return null; + } else { + return findKey(n.getNext(), key); + } + } + + public void delete(int key) { + if (!isEmpty()) { + if (first.getKey() == key) { + first = null; + } else { + delete(first, key); + } + } else { + System.out.println("List is empty"); + } } - public void displayHashtable() { - for (int i = 0; i < hsize; i++) { - System.out.printf("Bucket %d :", i); - System.out.println(buckets[i].display()); + private void delete(Node n, int key) { + if (n.getNext().getKey() == key) { + if (n.getNext().getNext() == null) { + n.setNext(null); + } else { + n.setNext(n.getNext().getNext()); } + } } - - public static class LinkedList { - private Node first; - - public LinkedList() { - first = null; - } - - public void insert(int key){ - if(isEmpty()) { - first = new Node(key); - return; - } - - Node temp = findEnd(first); - temp.setNext(new Node(key)); - } - - private Node findEnd(Node n) { - if(n.getNext() == null) { - return n; - } else { - return findEnd(n.getNext()); - } - } - - public Node findKey(int key) { - if(!isEmpty()) { - return findKey(first, key); - } else { - System.out.println("List is empty"); - return null; - } - - } - - private Node findKey(Node n, int key) { - if(n.getKey() == key) { - return n; - } else if(n.getNext() == null) { - System.out.println("Key not found"); - return null; - } else { - return findKey(n.getNext(),key); - } - } - - public void delete(int key) { - if(!isEmpty()) { - if(first.getKey() == key) { - first = null; - } else { - delete(first,key); - } - } else { - System.out.println("List is empty"); - } - } - - private void delete(Node n, int key) { - if(n.getNext().getKey() == key) { - if(n.getNext().getNext() == null) { - n.setNext(null); - } else { - n.setNext(n.getNext().getNext()); - } - } - } - - public String display() { - return display(first); - } - - private String display(Node n) { - if(n == null) { - return "null"; - } else { - return n.getKey() + "->" + display(n.getNext()); - } - } - - public boolean isEmpty() { - return first == null; - } - } - - public static class Node { - private Node next; - private int key; - - public Node(int key) { - next = null; - this.key = key; - } - - public Node getNext() { - return next; - } - - public int getKey() { - return key; - } - - public void setNext(Node next) { - this.next = next; - } + + public String display() { + return display(first); + } + + private String display(Node n) { + if (n == null) { + return "null"; + } else { + return n.getKey() + "->" + display(n.getNext()); + } + } + + public boolean isEmpty() { + return first == null; + } + } + + public static class Node { + private Node next; + private int key; + + public Node(int key) { + next = null; + this.key = key; + } + + public Node getNext() { + return next; + } + + public int getKey() { + return key; + } + + public void setNext(Node next) { + this.next = next; } + } } diff --git a/DataStructures/HashMap/Hashing/HashMapLinearProbing.java b/DataStructures/HashMap/Hashing/HashMapLinearProbing.java index 4da123b808aa..62ac6e8bb91e 100644 --- a/DataStructures/HashMap/Hashing/HashMapLinearProbing.java +++ b/DataStructures/HashMap/Hashing/HashMapLinearProbing.java @@ -3,191 +3,194 @@ import java.util.*; /** - * This class is an implementation of a hash table using linear probing - * It uses a dynamic array to lengthen the size of the hash table when - * load factor > .7 + * This class is an implementation of a hash table using linear probing It uses a dynamic array to + * lengthen the size of the hash table when load factor > .7 */ public class HashMapLinearProbing { - private int hsize; //size of the hash table - private Integer[] buckets; //array representing the table - private Integer AVAILABLE; - private int size; //amount of elements in the hash table - - /** - * Constructor initializes buckets array, hsize, and creates dummy object for AVAILABLE - * @param hsize the desired size of the hash map - */ - public HashMapLinearProbing(int hsize) { - this.buckets = new Integer[hsize]; - this.hsize = hsize; - this.AVAILABLE = new Integer(Integer.MIN_VALUE); - this.size = 0; + private int hsize; // size of the hash table + private Integer[] buckets; // array representing the table + private Integer AVAILABLE; + private int size; // amount of elements in the hash table + + /** + * Constructor initializes buckets array, hsize, and creates dummy object for AVAILABLE + * + * @param hsize the desired size of the hash map + */ + public HashMapLinearProbing(int hsize) { + this.buckets = new Integer[hsize]; + this.hsize = hsize; + this.AVAILABLE = new Integer(Integer.MIN_VALUE); + this.size = 0; + } + + /** + * The Hash Function takes a given key and finds an index based on its data + * + * @param key the desired key to be converted + * @return int an index corresponding to the key + */ + public int hashing(int key) { + int hash = key % hsize; + if (hash < 0) { + hash += hsize; } - - /** - * The Hash Function takes a given key and finds an index based on its data - * @param key the desired key to be converted - * @return int an index corresponding to the key - */ - public int hashing(int key) { - int hash = key % hsize; - if (hash < 0) { - hash += hsize; - } - return hash; + return hash; + } + + /** + * inserts the key into the hash map by wrapping it as an Integer object + * + * @param key the desired key to be inserted in the hash map + */ + public void insertHash(int key) { + Integer wrappedInt = new Integer(key); + int hash = hashing(key); + + if (isFull()) { + System.out.println("Hash table is full"); + return; } - - /** - * inserts the key into the hash map by wrapping it as an Integer object - * @param key the desired key to be inserted in the hash map - */ - public void insertHash(int key) { - Integer wrappedInt = new Integer(key); - int hash = hashing(key); - - if(isFull()) { - System.out.println("Hash table is full"); - return; - } - - for (int i = 0;i < hsize; i++) { - if(buckets[hash] == null || buckets[hash] == AVAILABLE) { - buckets[hash] = wrappedInt; - size++; - return; - } - - if(hash + 1 < hsize) { - hash++; - } else { - hash = 0; - } - } + + for (int i = 0; i < hsize; i++) { + if (buckets[hash] == null || buckets[hash] == AVAILABLE) { + buckets[hash] = wrappedInt; + size++; + return; + } + + if (hash + 1 < hsize) { + hash++; + } else { + hash = 0; + } } - - /** - * deletes a key from the hash map and adds an available placeholder - * @param key the desired key to be deleted - */ - public void deleteHash(int key) { - Integer wrappedInt = new Integer(key); - int hash = hashing(key); - - if(isEmpty()) { - System.out.println("Table is empty"); - return; - } - - for(int i = 0;i < hsize; i++) { - if(buckets[hash] != null && buckets[hash].equals(wrappedInt)) { - buckets[hash] = AVAILABLE; - size--; - return; - } - - if(hash + 1 < hsize) { - hash++; - } else { - hash = 0; - } - } - System.out.println("Key " + key + " not found"); + } + + /** + * deletes a key from the hash map and adds an available placeholder + * + * @param key the desired key to be deleted + */ + public void deleteHash(int key) { + Integer wrappedInt = new Integer(key); + int hash = hashing(key); + + if (isEmpty()) { + System.out.println("Table is empty"); + return; } - - /** - * Displays the hash table line by line - */ - public void displayHashtable() { - for (int i = 0; i < hsize; i++) { - if(buckets[i] == null || buckets[i] == AVAILABLE) { - System.out.println("Bucket " + i + ": Empty"); - } else { - System.out.println("Bucket " + i + ": " + buckets[i].toString()); - } - - } + + for (int i = 0; i < hsize; i++) { + if (buckets[hash] != null && buckets[hash].equals(wrappedInt)) { + buckets[hash] = AVAILABLE; + size--; + return; + } + + if (hash + 1 < hsize) { + hash++; + } else { + hash = 0; + } } - - /** - * Finds the index of location based on an inputed key - * @param key the desired key to be found - * @return int the index where the key is located - */ - public int findHash(int key) { - Integer wrappedInt = new Integer(key); - int hash = hashing(key); - - if(isEmpty()) { - System.out.println("Table is empty"); - return -1; - } - - for(int i = 0;i < hsize; i++) { - try { - if(buckets[hash].equals(wrappedInt)) { - buckets[hash] = AVAILABLE; - return hash; - } - } catch (Exception E) {} - - if(hash + 1 < hsize) { - hash++; - } else { - hash = 0; - } - } - System.out.println("Key " + key + " not found"); - return -1; + System.out.println("Key " + key + " not found"); + } + + /** Displays the hash table line by line */ + public void displayHashtable() { + for (int i = 0; i < hsize; i++) { + if (buckets[i] == null || buckets[i] == AVAILABLE) { + System.out.println("Bucket " + i + ": Empty"); + } else { + System.out.println("Bucket " + i + ": " + buckets[i].toString()); + } + } + } + + /** + * Finds the index of location based on an inputed key + * + * @param key the desired key to be found + * @return int the index where the key is located + */ + public int findHash(int key) { + Integer wrappedInt = new Integer(key); + int hash = hashing(key); + + if (isEmpty()) { + System.out.println("Table is empty"); + return -1; } - - private void lengthenTable() { - buckets = Arrays.copyOf(buckets, hsize * 2); - hsize *= 2; - System.out.println("Table size is now: " + hsize); + + for (int i = 0; i < hsize; i++) { + try { + if (buckets[hash].equals(wrappedInt)) { + buckets[hash] = AVAILABLE; + return hash; + } + } catch (Exception E) { + } + + if (hash + 1 < hsize) { + hash++; + } else { + hash = 0; + } } - - /** - * Checks the load factor of the hash table - * if greater than .7, automatically lengthens table - * to prevent further collisions - */ - public void checkLoadFactor() { - double factor = (double) size / hsize; - if(factor > .7) { - System.out.println("Load factor is " + factor + ", lengthening table"); - lengthenTable(); - } else { - System.out.println("Load factor is " + factor); - } + System.out.println("Key " + key + " not found"); + return -1; + } + + private void lengthenTable() { + buckets = Arrays.copyOf(buckets, hsize * 2); + hsize *= 2; + System.out.println("Table size is now: " + hsize); + } + + /** + * Checks the load factor of the hash table if greater than .7, automatically lengthens table to + * prevent further collisions + */ + public void checkLoadFactor() { + double factor = (double) size / hsize; + if (factor > .7) { + System.out.println("Load factor is " + factor + ", lengthening table"); + lengthenTable(); + } else { + System.out.println("Load factor is " + factor); } - - /** - * isFull returns true if the hash map is full and false if not full - * @return boolean is Empty - */ - public boolean isFull() { - boolean response = true; - for(int i = 0; i< hsize;i++) { - if(buckets[i] == null || buckets[i] == AVAILABLE) { - response = false; - break; - } - } - return response; + } + + /** + * isFull returns true if the hash map is full and false if not full + * + * @return boolean is Empty + */ + public boolean isFull() { + boolean response = true; + for (int i = 0; i < hsize; i++) { + if (buckets[i] == null || buckets[i] == AVAILABLE) { + response = false; + break; + } } - - /** - * isEmpty returns true if the hash map is empty and false if not empty - * @return boolean is Empty - */ - public boolean isEmpty() { - boolean response = true; - for(int i = 0; i< hsize;i++) { - if(buckets[i] != null) { - response = false; - break; - } - } - return response; + return response; + } + + /** + * isEmpty returns true if the hash map is empty and false if not empty + * + * @return boolean is Empty + */ + public boolean isEmpty() { + boolean response = true; + for (int i = 0; i < hsize; i++) { + if (buckets[i] != null) { + response = false; + break; + } } + return response; + } } diff --git a/DataStructures/HashMap/Hashing/Main.java b/DataStructures/HashMap/Hashing/Main.java index 9611b6025135..3cbe7f57a42d 100644 --- a/DataStructures/HashMap/Hashing/Main.java +++ b/DataStructures/HashMap/Hashing/Main.java @@ -3,46 +3,49 @@ import java.util.Scanner; public class Main { - public static void main(String[] args) { + public static void main(String[] args) { - int choice, key; + int choice, key; - HashMap h = new HashMap(7); - Scanner In = new Scanner(System.in); + HashMap h = new HashMap(7); + Scanner In = new Scanner(System.in); - while (true) { - System.out.println("Enter your Choice :"); - System.out.println("1. Add Key"); - System.out.println("2. Delete Key"); - System.out.println("3. Print Table"); - System.out.println("4. Exit"); - - choice = In.nextInt(); + while (true) { + System.out.println("Enter your Choice :"); + System.out.println("1. Add Key"); + System.out.println("2. Delete Key"); + System.out.println("3. Print Table"); + System.out.println("4. Exit"); - switch (choice) { - case 1: { - System.out.println("Enter the Key: "); - key = In.nextInt(); - h.insertHash(key); - break; - } - case 2: { - System.out.println("Enter the Key delete: "); - key = In.nextInt(); - h.deleteHash(key); - break; - } - case 3: { - System.out.println("Print table"); - h.displayHashtable(); - break; - } - case 4: { - In.close(); - return; - } - } - - } - } -} \ No newline at end of file + choice = In.nextInt(); + + switch (choice) { + case 1: + { + System.out.println("Enter the Key: "); + key = In.nextInt(); + h.insertHash(key); + break; + } + case 2: + { + System.out.println("Enter the Key delete: "); + key = In.nextInt(); + h.deleteHash(key); + break; + } + case 3: + { + System.out.println("Print table"); + h.displayHashtable(); + break; + } + case 4: + { + In.close(); + return; + } + } + } + } +} diff --git a/DataStructures/HashMap/Hashing/MainLinearProbing.java b/DataStructures/HashMap/Hashing/MainLinearProbing.java index c26435bdf960..90d1a7906704 100644 --- a/DataStructures/HashMap/Hashing/MainLinearProbing.java +++ b/DataStructures/HashMap/Hashing/MainLinearProbing.java @@ -3,58 +3,63 @@ import java.util.Scanner; public class MainLinearProbing { - public static void main(String[] args) { + public static void main(String[] args) { - int choice, key; + int choice, key; - HashMapLinearProbing h = new HashMapLinearProbing(7); - Scanner In = new Scanner(System.in); + HashMapLinearProbing h = new HashMapLinearProbing(7); + Scanner In = new Scanner(System.in); - while (true) { - System.out.println("Enter your Choice :"); - System.out.println("1. Add Key"); - System.out.println("2. Delete Key"); - System.out.println("3. Print Table"); - System.out.println("4. Exit"); - System.out.println("5. Search and print key index"); - System.out.println("6. Check load factor"); - - choice = In.nextInt(); + while (true) { + System.out.println("Enter your Choice :"); + System.out.println("1. Add Key"); + System.out.println("2. Delete Key"); + System.out.println("3. Print Table"); + System.out.println("4. Exit"); + System.out.println("5. Search and print key index"); + System.out.println("6. Check load factor"); - switch (choice) { - case 1: { - System.out.println("Enter the Key: "); - key = In.nextInt(); - h.insertHash(key); - break; - } - case 2: { - System.out.println("Enter the Key delete: "); - key = In.nextInt(); - h.deleteHash(key); - break; - } - case 3: { - System.out.println("Print table"); - h.displayHashtable(); - break; - } - case 4: { - In.close(); - return; - } - case 5: { - System.out.println("Enter the Key to find and print: "); - key = In.nextInt(); - System.out.println("Key: "+ key + " is at index: "+ h.findHash(key)); - break; - } - case 6: { - h.checkLoadFactor(); - break; - } - } - - } - } -} \ No newline at end of file + choice = In.nextInt(); + + switch (choice) { + case 1: + { + System.out.println("Enter the Key: "); + key = In.nextInt(); + h.insertHash(key); + break; + } + case 2: + { + System.out.println("Enter the Key delete: "); + key = In.nextInt(); + h.deleteHash(key); + break; + } + case 3: + { + System.out.println("Print table"); + h.displayHashtable(); + break; + } + case 4: + { + In.close(); + return; + } + case 5: + { + System.out.println("Enter the Key to find and print: "); + key = In.nextInt(); + System.out.println("Key: " + key + " is at index: " + h.findHash(key)); + break; + } + case 6: + { + h.checkLoadFactor(); + break; + } + } + } + } +} diff --git a/DataStructures/Heaps/EmptyHeapException.java b/DataStructures/Heaps/EmptyHeapException.java index a0fda5f53786..c47442951a6a 100644 --- a/DataStructures/Heaps/EmptyHeapException.java +++ b/DataStructures/Heaps/EmptyHeapException.java @@ -1,14 +1,12 @@ package DataStructures.Heaps; /** - * @author Nicolas Renard - * Exception to be thrown if the getElement method is used on an empty heap. + * @author Nicolas Renard Exception to be thrown if the getElement method is used on an empty heap. */ @SuppressWarnings("serial") public class EmptyHeapException extends Exception { - public EmptyHeapException(String message) { - super(message); - } - + public EmptyHeapException(String message) { + super(message); + } } diff --git a/DataStructures/Heaps/Heap.java b/DataStructures/Heaps/Heap.java index 0b7da3436581..75e113f8334f 100644 --- a/DataStructures/Heaps/Heap.java +++ b/DataStructures/Heaps/Heap.java @@ -2,39 +2,39 @@ /** * Interface common to heap data structures.
- *

Heaps are tree-like data structures that allow storing elements in a specific - * way. Each node corresponds to an element and has one parent node (except for the root) and - * at most two children nodes. Every element contains a key, and those keys - * indicate how the tree shall be built. For instance, for a min-heap, the key of a node shall - * be greater than or equal to its parent's and lower than or equal to its children's (the opposite rule applies to a - * max-heap).

- *

All heap-related operations (inserting or deleting an element, extracting the min or max) are performed in - * O(log n) time.

+ * + *

Heaps are tree-like data structures that allow storing elements in a specific way. Each node + * corresponds to an element and has one parent node (except for the root) and at most two children + * nodes. Every element contains a key, and those keys indicate how the tree shall be built. For + * instance, for a min-heap, the key of a node shall be greater than or equal to its parent's and + * lower than or equal to its children's (the opposite rule applies to a max-heap). + * + *

All heap-related operations (inserting or deleting an element, extracting the min or max) are + * performed in O(log n) time. * * @author Nicolas Renard */ public interface Heap { - /** - * @return the top element in the heap, the one with lowest key for min-heap or with - * the highest key for max-heap - * @throws EmptyHeapException if heap is empty - */ - HeapElement getElement() throws EmptyHeapException; - - /** - * Inserts an element in the heap. Adds it to then end and toggle it until it finds its - * right position. - * - * @param element an instance of the HeapElement class. - */ - void insertElement(HeapElement element); + /** + * @return the top element in the heap, the one with lowest key for min-heap or with the highest + * key for max-heap + * @throws EmptyHeapException if heap is empty + */ + HeapElement getElement() throws EmptyHeapException; - /** - * Delete an element in the heap. - * - * @param elementIndex int containing the position in the heap of the element to be deleted. - */ - void deleteElement(int elementIndex); + /** + * Inserts an element in the heap. Adds it to then end and toggle it until it finds its right + * position. + * + * @param element an instance of the HeapElement class. + */ + void insertElement(HeapElement element); -} \ No newline at end of file + /** + * Delete an element in the heap. + * + * @param elementIndex int containing the position in the heap of the element to be deleted. + */ + void deleteElement(int elementIndex); +} diff --git a/DataStructures/Heaps/HeapElement.java b/DataStructures/Heaps/HeapElement.java index 028d9b3e67de..5db98783eb7f 100644 --- a/DataStructures/Heaps/HeapElement.java +++ b/DataStructures/Heaps/HeapElement.java @@ -1,137 +1,125 @@ package DataStructures.Heaps; -import java.lang.Double; -import java.lang.Object; /** * Class for heap elements.
- *

A heap element contains two attributes: a key which will be used to build the tree (int - * or double, either primitive type or object) and any kind of IMMUTABLE object the user sees fit - * to carry any information he/she likes. Be aware that the use of a mutable object might - * jeopardize the integrity of this information.

+ * + *

A heap element contains two attributes: a key which will be used to build the tree (int or + * double, either primitive type or object) and any kind of IMMUTABLE object the user sees fit to + * carry any information he/she likes. Be aware that the use of a mutable object might jeopardize + * the integrity of this information. * * @author Nicolas Renard */ public class HeapElement { - private final double key; - private final Object additionalInfo; - - // Constructors - - /** - * @param key : a number of primitive type 'double' - * @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry - * additional information of use for the user - */ - public HeapElement(double key, Object info) { - this.key = key; - this.additionalInfo = info; - } - - /** - * @param key : a number of primitive type 'int' - * @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry - * additional information of use for the user - */ - public HeapElement(int key, Object info) { - this.key = key; - this.additionalInfo = info; - } - - /** - * @param key : a number of object type 'Integer' - * @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry - * additional information of use for the user - */ - public HeapElement(Integer key, Object info) { - this.key = key; - this.additionalInfo = info; - } - - /** - * @param key : a number of object type 'Double' - * @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry - * additional information of use for the user - */ - public HeapElement(Double key, Object info) { - this.key = key; - this.additionalInfo = info; - } - - /** - * @param key : a number of primitive type 'double' - */ - public HeapElement(double key) { - this.key = key; - this.additionalInfo = null; - } - - /** - * @param key : a number of primitive type 'int' - */ - public HeapElement(int key) { - this.key = key; - this.additionalInfo = null; - } - - /** - * @param key : a number of object type 'Integer' - */ - public HeapElement(Integer key) { - this.key = key; - this.additionalInfo = null; - } - - /** - * @param key : a number of object type 'Double' - */ - public HeapElement(Double key) { - this.key = key; - this.additionalInfo = null; - } - - // Getters - - /** - * @return the object containing the additional info provided by the user. - */ - public Object getInfo() { - return additionalInfo; - } - - /** - * @return the key value of the element - */ - public double getKey() { - return key; - } - - // Overridden object methods - - public String toString() { - return "Key: " + key + " - " + additionalInfo.toString(); - } - - /** - * @param otherHeapElement - * @return true if the keys on both elements are identical and the additional info objects - * are identical. - */ - @Override - public boolean equals(Object o) { - if (o != null) { - if (!(o instanceof HeapElement)) return false; - HeapElement otherHeapElement = (HeapElement) o; - return (this.key == otherHeapElement.key) && (this.additionalInfo.equals(otherHeapElement.additionalInfo)); - } - return false; - } - - @Override - public int hashCode() { - int result = 0; - result = 31*result + (int) key; - result = 31*result + (additionalInfo != null ? additionalInfo.hashCode() : 0); - return result; + private final double key; + private final Object additionalInfo; + + // Constructors + + /** + * @param key : a number of primitive type 'double' + * @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry + * additional information of use for the user + */ + public HeapElement(double key, Object info) { + this.key = key; + this.additionalInfo = info; + } + + /** + * @param key : a number of primitive type 'int' + * @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry + * additional information of use for the user + */ + public HeapElement(int key, Object info) { + this.key = key; + this.additionalInfo = info; + } + + /** + * @param key : a number of object type 'Integer' + * @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry + * additional information of use for the user + */ + public HeapElement(Integer key, Object info) { + this.key = key; + this.additionalInfo = info; + } + + /** + * @param key : a number of object type 'Double' + * @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry + * additional information of use for the user + */ + public HeapElement(Double key, Object info) { + this.key = key; + this.additionalInfo = info; + } + + /** @param key : a number of primitive type 'double' */ + public HeapElement(double key) { + this.key = key; + this.additionalInfo = null; + } + + /** @param key : a number of primitive type 'int' */ + public HeapElement(int key) { + this.key = key; + this.additionalInfo = null; + } + + /** @param key : a number of object type 'Integer' */ + public HeapElement(Integer key) { + this.key = key; + this.additionalInfo = null; + } + + /** @param key : a number of object type 'Double' */ + public HeapElement(Double key) { + this.key = key; + this.additionalInfo = null; + } + + // Getters + + /** @return the object containing the additional info provided by the user. */ + public Object getInfo() { + return additionalInfo; + } + + /** @return the key value of the element */ + public double getKey() { + return key; + } + + // Overridden object methods + + public String toString() { + return "Key: " + key + " - " + additionalInfo.toString(); + } + + /** + * @param otherHeapElement + * @return true if the keys on both elements are identical and the additional info objects are + * identical. + */ + @Override + public boolean equals(Object o) { + if (o != null) { + if (!(o instanceof HeapElement)) return false; + HeapElement otherHeapElement = (HeapElement) o; + return (this.key == otherHeapElement.key) + && (this.additionalInfo.equals(otherHeapElement.additionalInfo)); } + return false; + } + + @Override + public int hashCode() { + int result = 0; + result = 31 * result + (int) key; + result = 31 * result + (additionalInfo != null ? additionalInfo.hashCode() : 0); + return result; + } } diff --git a/DataStructures/Heaps/MaxHeap.java b/DataStructures/Heaps/MaxHeap.java index 3945caa97fde..1c9e0a08348f 100644 --- a/DataStructures/Heaps/MaxHeap.java +++ b/DataStructures/Heaps/MaxHeap.java @@ -4,116 +4,122 @@ import java.util.List; /** - * Heap tree where a node's key is higher than or equal to its parent's and lower than or equal - * to its children's. + * Heap tree where a node's key is higher than or equal to its parent's and lower than or equal to + * its children's. * * @author Nicolas Renard */ public class MaxHeap implements Heap { - private final List maxHeap; + private final List maxHeap; - public MaxHeap(List listElements) { - maxHeap = new ArrayList<>(); - for (HeapElement heapElement : listElements) { - if (heapElement != null) insertElement(heapElement); - else System.out.println("Null element. Not added to heap"); - } - if (maxHeap.size() == 0) System.out.println("No element has been added, empty heap."); + public MaxHeap(List listElements) { + maxHeap = new ArrayList<>(); + for (HeapElement heapElement : listElements) { + if (heapElement != null) insertElement(heapElement); + else System.out.println("Null element. Not added to heap"); } + if (maxHeap.size() == 0) System.out.println("No element has been added, empty heap."); + } - /** - * Get the element at a given index. The key for the list is equal to index value - 1 - * - * @param elementIndex index - * @return heapElement - */ - public HeapElement getElement(int elementIndex) { - if ((elementIndex <= 0) || (elementIndex > maxHeap.size())) - throw new IndexOutOfBoundsException("Index out of heap range"); - return maxHeap.get(elementIndex - 1); - } - - // Get the key of the element at a given index - private double getElementKey(int elementIndex) { - return maxHeap.get(elementIndex - 1).getKey(); - } - - // Swaps two elements in the heap - private void swap(int index1, int index2) { - HeapElement temporaryElement = maxHeap.get(index1 - 1); - maxHeap.set(index1 - 1, maxHeap.get(index2 - 1)); - maxHeap.set(index2 - 1, temporaryElement); - } + /** + * Get the element at a given index. The key for the list is equal to index value - 1 + * + * @param elementIndex index + * @return heapElement + */ + public HeapElement getElement(int elementIndex) { + if ((elementIndex <= 0) || (elementIndex > maxHeap.size())) + throw new IndexOutOfBoundsException("Index out of heap range"); + return maxHeap.get(elementIndex - 1); + } - // Toggle an element up to its right place as long as its key is lower than its parent's - private void toggleUp(int elementIndex) { - double key = maxHeap.get(elementIndex - 1).getKey(); - while (getElementKey((int) Math.floor(elementIndex / 2.0)) < key) { - swap(elementIndex, (int) Math.floor(elementIndex / 2.0)); - elementIndex = (int) Math.floor(elementIndex / 2.0); - } - } + // Get the key of the element at a given index + private double getElementKey(int elementIndex) { + return maxHeap.get(elementIndex - 1).getKey(); + } - // Toggle an element down to its right place as long as its key is higher - // than any of its children's - private void toggleDown(int elementIndex) { - double key = maxHeap.get(elementIndex - 1).getKey(); - boolean wrongOrder = (key < getElementKey(elementIndex * 2)) || (key < getElementKey(Math.min(elementIndex * 2, maxHeap.size()))); - while ((2 * elementIndex <= maxHeap.size()) && wrongOrder) { - // Check whether it shall swap the element with its left child or its right one if any. - if ((2 * elementIndex < maxHeap.size()) && (getElementKey(elementIndex * 2 + 1) > getElementKey(elementIndex * 2))) { - swap(elementIndex, 2 * elementIndex + 1); - elementIndex = 2 * elementIndex + 1; - } else { - swap(elementIndex, 2 * elementIndex); - elementIndex = 2 * elementIndex; - } - wrongOrder = (key < getElementKey(elementIndex * 2)) || (key < getElementKey(Math.min(elementIndex * 2, maxHeap.size()))); + // Swaps two elements in the heap + private void swap(int index1, int index2) { + HeapElement temporaryElement = maxHeap.get(index1 - 1); + maxHeap.set(index1 - 1, maxHeap.get(index2 - 1)); + maxHeap.set(index2 - 1, temporaryElement); + } - } + // Toggle an element up to its right place as long as its key is lower than its parent's + private void toggleUp(int elementIndex) { + double key = maxHeap.get(elementIndex - 1).getKey(); + while (getElementKey((int) Math.floor(elementIndex / 2.0)) < key) { + swap(elementIndex, (int) Math.floor(elementIndex / 2.0)); + elementIndex = (int) Math.floor(elementIndex / 2.0); } + } - private HeapElement extractMax() { - HeapElement result = maxHeap.get(0); - deleteElement(0); - return result; + // Toggle an element down to its right place as long as its key is higher + // than any of its children's + private void toggleDown(int elementIndex) { + double key = maxHeap.get(elementIndex - 1).getKey(); + boolean wrongOrder = + (key < getElementKey(elementIndex * 2)) + || (key < getElementKey(Math.min(elementIndex * 2, maxHeap.size()))); + while ((2 * elementIndex <= maxHeap.size()) && wrongOrder) { + // Check whether it shall swap the element with its left child or its right one if any. + if ((2 * elementIndex < maxHeap.size()) + && (getElementKey(elementIndex * 2 + 1) > getElementKey(elementIndex * 2))) { + swap(elementIndex, 2 * elementIndex + 1); + elementIndex = 2 * elementIndex + 1; + } else { + swap(elementIndex, 2 * elementIndex); + elementIndex = 2 * elementIndex; + } + wrongOrder = + (key < getElementKey(elementIndex * 2)) + || (key < getElementKey(Math.min(elementIndex * 2, maxHeap.size()))); } + } - @Override - public void insertElement(HeapElement element) { - maxHeap.add(element); - toggleUp(maxHeap.size()); + private HeapElement extractMax() { + HeapElement result = maxHeap.get(0); + deleteElement(0); + return result; + } - } + @Override + public void insertElement(HeapElement element) { + maxHeap.add(element); + toggleUp(maxHeap.size()); + } - @Override - public void deleteElement(int elementIndex) { - if (maxHeap.isEmpty()) - try { - throw new EmptyHeapException("Attempt to delete an element from an empty heap"); - } catch (EmptyHeapException e) { - e.printStackTrace(); - } - if ((elementIndex > maxHeap.size()) || (elementIndex <= 0)) - throw new IndexOutOfBoundsException("Index out of heap range"); - // The last element in heap replaces the one to be deleted - maxHeap.set(elementIndex - 1, getElement(maxHeap.size())); - maxHeap.remove(maxHeap.size()); - // Shall the new element be moved up... - if (getElementKey(elementIndex) > getElementKey((int) Math.floor(elementIndex / 2.0))) toggleUp(elementIndex); - // ... or down ? - else if (((2 * elementIndex <= maxHeap.size()) && (getElementKey(elementIndex) < getElementKey(elementIndex * 2))) || - ((2 * elementIndex < maxHeap.size()) && (getElementKey(elementIndex) < getElementKey(elementIndex * 2)))) - toggleDown(elementIndex); - } + @Override + public void deleteElement(int elementIndex) { + if (maxHeap.isEmpty()) + try { + throw new EmptyHeapException("Attempt to delete an element from an empty heap"); + } catch (EmptyHeapException e) { + e.printStackTrace(); + } + if ((elementIndex > maxHeap.size()) || (elementIndex <= 0)) + throw new IndexOutOfBoundsException("Index out of heap range"); + // The last element in heap replaces the one to be deleted + maxHeap.set(elementIndex - 1, getElement(maxHeap.size())); + maxHeap.remove(maxHeap.size()); + // Shall the new element be moved up... + if (getElementKey(elementIndex) > getElementKey((int) Math.floor(elementIndex / 2.0))) + toggleUp(elementIndex); + // ... or down ? + else if (((2 * elementIndex <= maxHeap.size()) + && (getElementKey(elementIndex) < getElementKey(elementIndex * 2))) + || ((2 * elementIndex < maxHeap.size()) + && (getElementKey(elementIndex) < getElementKey(elementIndex * 2)))) + toggleDown(elementIndex); + } - @Override - public HeapElement getElement() throws EmptyHeapException { - try { - return extractMax(); - } catch (Exception e) { - throw new EmptyHeapException("Heap is empty. Error retrieving element"); - } + @Override + public HeapElement getElement() throws EmptyHeapException { + try { + return extractMax(); + } catch (Exception e) { + throw new EmptyHeapException("Heap is empty. Error retrieving element"); } -} \ No newline at end of file + } +} diff --git a/DataStructures/Heaps/MinHeap.java b/DataStructures/Heaps/MinHeap.java index 39ee6ebf7b8f..1c384063c932 100644 --- a/DataStructures/Heaps/MinHeap.java +++ b/DataStructures/Heaps/MinHeap.java @@ -4,111 +4,117 @@ import java.util.List; /** - * Heap tree where a node's key is higher than or equal to its parent's and lower than or equal - * to its children's. + * Heap tree where a node's key is higher than or equal to its parent's and lower than or equal to + * its children's. * * @author Nicolas Renard */ public class MinHeap implements Heap { - private final List minHeap; + private final List minHeap; - public MinHeap(List listElements) { - minHeap = new ArrayList<>(); - for (HeapElement heapElement : listElements) { - if (heapElement != null) insertElement(heapElement); - else System.out.println("Null element. Not added to heap"); - } - if (minHeap.size() == 0) System.out.println("No element has been added, empty heap."); + public MinHeap(List listElements) { + minHeap = new ArrayList<>(); + for (HeapElement heapElement : listElements) { + if (heapElement != null) insertElement(heapElement); + else System.out.println("Null element. Not added to heap"); } + if (minHeap.size() == 0) System.out.println("No element has been added, empty heap."); + } - // Get the element at a given index. The key for the list is equal to index value - 1 - public HeapElement getElement(int elementIndex) { - if ((elementIndex <= 0) || (elementIndex > minHeap.size())) - throw new IndexOutOfBoundsException("Index out of heap range"); - return minHeap.get(elementIndex - 1); - } - - // Get the key of the element at a given index - private double getElementKey(int elementIndex) { - return minHeap.get(elementIndex - 1).getKey(); - } - - // Swaps two elements in the heap - private void swap(int index1, int index2) { - HeapElement temporaryElement = minHeap.get(index1 - 1); - minHeap.set(index1 - 1, minHeap.get(index2 - 1)); - minHeap.set(index2 - 1, temporaryElement); - } + // Get the element at a given index. The key for the list is equal to index value - 1 + public HeapElement getElement(int elementIndex) { + if ((elementIndex <= 0) || (elementIndex > minHeap.size())) + throw new IndexOutOfBoundsException("Index out of heap range"); + return minHeap.get(elementIndex - 1); + } - // Toggle an element up to its right place as long as its key is lower than its parent's - private void toggleUp(int elementIndex) { - double key = minHeap.get(elementIndex - 1).getKey(); - while (getElementKey((int) Math.floor(elementIndex / 2.0)) > key) { - swap(elementIndex, (int) Math.floor(elementIndex / 2.0)); - elementIndex = (int) Math.floor(elementIndex / 2.0); - } - } + // Get the key of the element at a given index + private double getElementKey(int elementIndex) { + return minHeap.get(elementIndex - 1).getKey(); + } - // Toggle an element down to its right place as long as its key is higher - // than any of its children's - private void toggleDown(int elementIndex) { - double key = minHeap.get(elementIndex - 1).getKey(); - boolean wrongOrder = (key > getElementKey(elementIndex * 2)) || (key > getElementKey(Math.min(elementIndex * 2, minHeap.size()))); - while ((2 * elementIndex <= minHeap.size()) && wrongOrder) { - // Check whether it shall swap the element with its left child or its right one if any. - if ((2 * elementIndex < minHeap.size()) && (getElementKey(elementIndex * 2 + 1) < getElementKey(elementIndex * 2))) { - swap(elementIndex, 2 * elementIndex + 1); - elementIndex = 2 * elementIndex + 1; - } else { - swap(elementIndex, 2 * elementIndex); - elementIndex = 2 * elementIndex; - } - wrongOrder = (key > getElementKey(elementIndex * 2)) || (key > getElementKey(Math.min(elementIndex * 2, minHeap.size()))); + // Swaps two elements in the heap + private void swap(int index1, int index2) { + HeapElement temporaryElement = minHeap.get(index1 - 1); + minHeap.set(index1 - 1, minHeap.get(index2 - 1)); + minHeap.set(index2 - 1, temporaryElement); + } - } + // Toggle an element up to its right place as long as its key is lower than its parent's + private void toggleUp(int elementIndex) { + double key = minHeap.get(elementIndex - 1).getKey(); + while (getElementKey((int) Math.floor(elementIndex / 2.0)) > key) { + swap(elementIndex, (int) Math.floor(elementIndex / 2.0)); + elementIndex = (int) Math.floor(elementIndex / 2.0); } + } - private HeapElement extractMin() { - HeapElement result = minHeap.get(0); - deleteElement(0); - return result; + // Toggle an element down to its right place as long as its key is higher + // than any of its children's + private void toggleDown(int elementIndex) { + double key = minHeap.get(elementIndex - 1).getKey(); + boolean wrongOrder = + (key > getElementKey(elementIndex * 2)) + || (key > getElementKey(Math.min(elementIndex * 2, minHeap.size()))); + while ((2 * elementIndex <= minHeap.size()) && wrongOrder) { + // Check whether it shall swap the element with its left child or its right one if any. + if ((2 * elementIndex < minHeap.size()) + && (getElementKey(elementIndex * 2 + 1) < getElementKey(elementIndex * 2))) { + swap(elementIndex, 2 * elementIndex + 1); + elementIndex = 2 * elementIndex + 1; + } else { + swap(elementIndex, 2 * elementIndex); + elementIndex = 2 * elementIndex; + } + wrongOrder = + (key > getElementKey(elementIndex * 2)) + || (key > getElementKey(Math.min(elementIndex * 2, minHeap.size()))); } + } - @Override - public void insertElement(HeapElement element) { - minHeap.add(element); - toggleUp(minHeap.size()); + private HeapElement extractMin() { + HeapElement result = minHeap.get(0); + deleteElement(0); + return result; + } - } + @Override + public void insertElement(HeapElement element) { + minHeap.add(element); + toggleUp(minHeap.size()); + } - @Override - public void deleteElement(int elementIndex) { - if (minHeap.isEmpty()) - try { - throw new EmptyHeapException("Attempt to delete an element from an empty heap"); - } catch (EmptyHeapException e) { - e.printStackTrace(); - } - if ((elementIndex > minHeap.size()) || (elementIndex <= 0)) - throw new IndexOutOfBoundsException("Index out of heap range"); - // The last element in heap replaces the one to be deleted - minHeap.set(elementIndex - 1, getElement(minHeap.size())); - minHeap.remove(minHeap.size()); - // Shall the new element be moved up... - if (getElementKey(elementIndex) < getElementKey((int)Math.floor(elementIndex / 2.0))) toggleUp(elementIndex); - // ... or down ? - else if (((2 * elementIndex <= minHeap.size()) && (getElementKey(elementIndex) > getElementKey(elementIndex * 2))) || - ((2 * elementIndex < minHeap.size()) && (getElementKey(elementIndex) > getElementKey(elementIndex * 2)))) - toggleDown(elementIndex); - } + @Override + public void deleteElement(int elementIndex) { + if (minHeap.isEmpty()) + try { + throw new EmptyHeapException("Attempt to delete an element from an empty heap"); + } catch (EmptyHeapException e) { + e.printStackTrace(); + } + if ((elementIndex > minHeap.size()) || (elementIndex <= 0)) + throw new IndexOutOfBoundsException("Index out of heap range"); + // The last element in heap replaces the one to be deleted + minHeap.set(elementIndex - 1, getElement(minHeap.size())); + minHeap.remove(minHeap.size()); + // Shall the new element be moved up... + if (getElementKey(elementIndex) < getElementKey((int) Math.floor(elementIndex / 2.0))) + toggleUp(elementIndex); + // ... or down ? + else if (((2 * elementIndex <= minHeap.size()) + && (getElementKey(elementIndex) > getElementKey(elementIndex * 2))) + || ((2 * elementIndex < minHeap.size()) + && (getElementKey(elementIndex) > getElementKey(elementIndex * 2)))) + toggleDown(elementIndex); + } - @Override - public HeapElement getElement() throws EmptyHeapException { - try { - return extractMin(); - } catch (Exception e) { - throw new EmptyHeapException("Heap is empty. Error retrieving element"); - } + @Override + public HeapElement getElement() throws EmptyHeapException { + try { + return extractMin(); + } catch (Exception e) { + throw new EmptyHeapException("Heap is empty. Error retrieving element"); } -} \ No newline at end of file + } +} diff --git a/DataStructures/Heaps/MinPriorityQueue.java b/DataStructures/Heaps/MinPriorityQueue.java index 52e475abf4be..82950d22e700 100644 --- a/DataStructures/Heaps/MinPriorityQueue.java +++ b/DataStructures/Heaps/MinPriorityQueue.java @@ -1,133 +1,125 @@ package DataStructures.Heaps; /** - * Minimum Priority Queue - * It is a part of heap data structure - * A heap is a specific tree based data structure - * in which all the nodes of tree are in a specific order. - * that is the children are arranged in some - * respect of their parents, can either be greater - * or less than the parent. This makes it a min priority queue - * or max priority queue. + * Minimum Priority Queue It is a part of heap data structure A heap is a specific tree based data + * structure in which all the nodes of tree are in a specific order. that is the children are + * arranged in some respect of their parents, can either be greater or less than the parent. This + * makes it a min priority queue or max priority queue. + * *

- *

- * Functions: insert, delete, peek, isEmpty, print, heapSort, sink + * + *

Functions: insert, delete, peek, isEmpty, print, heapSort, sink */ public class MinPriorityQueue { - private int[] heap; - private int capacity; - private int size; + private int[] heap; + private int capacity; + private int size; - // calss the constructor and initializes the capacity - MinPriorityQueue(int c) { - this.capacity = c; - this.size = 0; - this.heap = new int[c + 1]; - } + // calss the constructor and initializes the capacity + MinPriorityQueue(int c) { + this.capacity = c; + this.size = 0; + this.heap = new int[c + 1]; + } - // inserts the key at the end and rearranges it - // so that the binary heap is in appropriate order - public void insert(int key) { - if (this.isFull()) - return; - this.heap[this.size + 1] = key; - int k = this.size + 1; - while (k > 1) { - if (this.heap[k] < this.heap[k / 2]) { - int temp = this.heap[k]; - this.heap[k] = this.heap[k / 2]; - this.heap[k / 2] = temp; - } - k = k / 2; - } - this.size++; + // inserts the key at the end and rearranges it + // so that the binary heap is in appropriate order + public void insert(int key) { + if (this.isFull()) return; + this.heap[this.size + 1] = key; + int k = this.size + 1; + while (k > 1) { + if (this.heap[k] < this.heap[k / 2]) { + int temp = this.heap[k]; + this.heap[k] = this.heap[k / 2]; + this.heap[k / 2] = temp; + } + k = k / 2; } + this.size++; + } - // returns the highest priority value - public int peek() { - return this.heap[1]; - } + // returns the highest priority value + public int peek() { + return this.heap[1]; + } - // returns boolean value whether the heap is empty or not - public boolean isEmpty() { - if (0 == this.size) - return true; - return false; - } + // returns boolean value whether the heap is empty or not + public boolean isEmpty() { + if (0 == this.size) return true; + return false; + } - // returns boolean value whether the heap is full or not - public boolean isFull() { - if (this.size == this.capacity) - return true; - return false; - } + // returns boolean value whether the heap is full or not + public boolean isFull() { + if (this.size == this.capacity) return true; + return false; + } - // prints the heap - public void print() { - for (int i = 1; i <= this.capacity; i++) - System.out.print(this.heap[i] + " "); - System.out.println(); - } + // prints the heap + public void print() { + for (int i = 1; i <= this.capacity; i++) System.out.print(this.heap[i] + " "); + System.out.println(); + } - // heap sorting can be done by performing - // delete function to the number of times of the size of the heap - // it returns reverse sort because it is a min priority queue - public void heapSort() { - for (int i = 1; i < this.capacity; i++) - this.delete(); - } + // heap sorting can be done by performing + // delete function to the number of times of the size of the heap + // it returns reverse sort because it is a min priority queue + public void heapSort() { + for (int i = 1; i < this.capacity; i++) this.delete(); + } - // this function reorders the heap after every delete function - private void sink() { - int k = 1; - while (2 * k <= this.size || 2 * k + 1 <= this.size) { - int minIndex; - if (this.heap[2 * k] >= this.heap[k]) { - if (2 * k + 1 <= this.size && this.heap[2 * k + 1] >= this.heap[k]) { - break; - } else if (2 * k + 1 > this.size) { - break; - } - } - if (2 * k + 1 > this.size) { - minIndex = this.heap[2 * k] < this.heap[k] ? 2 * k : k; - } else { - if (this.heap[k] > this.heap[2 * k] || this.heap[k] > this.heap[2 * k + 1]) { - minIndex = this.heap[2 * k] < this.heap[2 * k + 1] ? 2 * k : 2 * k + 1; - } else { - minIndex = k; - } - } - int temp = this.heap[k]; - this.heap[k] = this.heap[minIndex]; - this.heap[minIndex] = temp; - k = minIndex; + // this function reorders the heap after every delete function + private void sink() { + int k = 1; + while (2 * k <= this.size || 2 * k + 1 <= this.size) { + int minIndex; + if (this.heap[2 * k] >= this.heap[k]) { + if (2 * k + 1 <= this.size && this.heap[2 * k + 1] >= this.heap[k]) { + break; + } else if (2 * k + 1 > this.size) { + break; + } + } + if (2 * k + 1 > this.size) { + minIndex = this.heap[2 * k] < this.heap[k] ? 2 * k : k; + } else { + if (this.heap[k] > this.heap[2 * k] || this.heap[k] > this.heap[2 * k + 1]) { + minIndex = this.heap[2 * k] < this.heap[2 * k + 1] ? 2 * k : 2 * k + 1; + } else { + minIndex = k; } + } + int temp = this.heap[k]; + this.heap[k] = this.heap[minIndex]; + this.heap[minIndex] = temp; + k = minIndex; } + } - // deletes the highest priority value from the heap - public int delete() { - int min = this.heap[1]; - this.heap[1] = this.heap[this.size]; - this.heap[this.size] = min; - this.size--; - this.sink(); - return min; - } + // deletes the highest priority value from the heap + public int delete() { + int min = this.heap[1]; + this.heap[1] = this.heap[this.size]; + this.heap[this.size] = min; + this.size--; + this.sink(); + return min; + } - public static void main(String[] args) { - // testing - MinPriorityQueue q = new MinPriorityQueue(8); - q.insert(5); - q.insert(2); - q.insert(4); - q.insert(1); - q.insert(7); - q.insert(6); - q.insert(3); - q.insert(8); - q.print(); // [ 1, 2, 3, 5, 7, 6, 4, 8 ] - q.heapSort(); - q.print(); // [ 8, 7, 6, 5, 4, 3, 2, 1 ] - } -} \ No newline at end of file + public static void main(String[] args) { + // testing + MinPriorityQueue q = new MinPriorityQueue(8); + q.insert(5); + q.insert(2); + q.insert(4); + q.insert(1); + q.insert(7); + q.insert(6); + q.insert(3); + q.insert(8); + q.print(); // [ 1, 2, 3, 5, 7, 6, 4, 8 ] + q.heapSort(); + q.print(); // [ 8, 7, 6, 5, 4, 3, 2, 1 ] + } +} diff --git a/DataStructures/Lists/CircleLinkedList.java b/DataStructures/Lists/CircleLinkedList.java index b46441a1fa47..b1f9ec77d738 100644 --- a/DataStructures/Lists/CircleLinkedList.java +++ b/DataStructures/Lists/CircleLinkedList.java @@ -1,63 +1,65 @@ package DataStructures.Lists; public class CircleLinkedList { - private static class Node { - Node next; - E value; + private static class Node { + Node next; + E value; - private Node(E value, Node next) { - this.value = value; - this.next = next; - } + private Node(E value, Node next) { + this.value = value; + this.next = next; } + } - //For better O.O design this should be private allows for better black box design - private int size; - //this will point to dummy node; - private Node head = null; + // For better O.O design this should be private allows for better black box design + private int size; + // this will point to dummy node; + private Node head = null; - //constructer for class.. here we will make a dummy node for circly linked list implementation with reduced error catching as our list will never be empty; - public CircleLinkedList() { - //creation of the dummy node - head = new Node(null, head); - size = 0; - } + // constructer for class.. here we will make a dummy node for circly linked list implementation + // with reduced error catching as our list will never be empty; + public CircleLinkedList() { + // creation of the dummy node + head = new Node(null, head); + size = 0; + } - // getter for the size... needed because size is private. - public int getSize() { - return size; - } + // getter for the size... needed because size is private. + public int getSize() { + return size; + } - // for the sake of simplistiy this class will only contain the append function or addLast other add functions can be implemented however this is the basses of them all really. - public void append(E value) { - if (value == null) { - // we do not want to add null elements to the list. - throw new NullPointerException("Cannot add null element to the list"); - } - //head.next points to the last element; - head.next = new Node(value, head); - size++; + // for the sake of simplistiy this class will only contain the append function or addLast other + // add functions can be implemented however this is the basses of them all really. + public void append(E value) { + if (value == null) { + // we do not want to add null elements to the list. + throw new NullPointerException("Cannot add null element to the list"); } + // head.next points to the last element; + head.next = new Node(value, head); + size++; + } - public E remove(int pos) { - if (pos > size || pos < 0) { - //catching errors - throw new IndexOutOfBoundsException("position cannot be greater than size or negative"); - } - //we need to keep track of the element before the element we want to remove we can see why bellow. - Node before = head; - for (int i = 1; i <= pos; i++) { - before = before.next; - } - Node destroy = before.next; - E saved = destroy.value; - // assigning the next reference to the the element following the element we want to remove... the last element will be assigned to the head. - before.next = before.next.next; - // scrubbing - destroy = null; - size--; - return saved; - + public E remove(int pos) { + if (pos > size || pos < 0) { + // catching errors + throw new IndexOutOfBoundsException("position cannot be greater than size or negative"); } - + // we need to keep track of the element before the element we want to remove we can see why + // bellow. + Node before = head; + for (int i = 1; i <= pos; i++) { + before = before.next; + } + Node destroy = before.next; + E saved = destroy.value; + // assigning the next reference to the the element following the element we want to remove... + // the last element will be assigned to the head. + before.next = before.next.next; + // scrubbing + destroy = null; + size--; + return saved; + } } diff --git a/DataStructures/Lists/CountSinglyLinkedListRecursion.java b/DataStructures/Lists/CountSinglyLinkedListRecursion.java index 652791be4542..00fc1d90b1ac 100644 --- a/DataStructures/Lists/CountSinglyLinkedListRecursion.java +++ b/DataStructures/Lists/CountSinglyLinkedListRecursion.java @@ -1,26 +1,26 @@ package DataStructures.Lists; public class CountSinglyLinkedListRecursion extends SinglyLinkedList { - public static void main(String[] args) { - CountSinglyLinkedListRecursion list = new CountSinglyLinkedListRecursion(); - for (int i = 1; i <= 5; ++i) { - list.insert(i); - } - assert list.count() == 5; + public static void main(String[] args) { + CountSinglyLinkedListRecursion list = new CountSinglyLinkedListRecursion(); + for (int i = 1; i <= 5; ++i) { + list.insert(i); } + assert list.count() == 5; + } - /** - * Calculate the count of the list manually using recursion. - * - * @param head head of the list. - * @return count of the list. - */ - private int countRecursion(Node head) { - return head == null ? 0 : 1 + countRecursion(head.next); - } + /** + * Calculate the count of the list manually using recursion. + * + * @param head head of the list. + * @return count of the list. + */ + private int countRecursion(Node head) { + return head == null ? 0 : 1 + countRecursion(head.next); + } - @Override - public int count() { - return countRecursion(getHead()); - } + @Override + public int count() { + return countRecursion(getHead()); + } } diff --git a/DataStructures/Lists/CursorLinkedList.java b/DataStructures/Lists/CursorLinkedList.java index b12794fd1067..aa9a1aeea2cb 100644 --- a/DataStructures/Lists/CursorLinkedList.java +++ b/DataStructures/Lists/CursorLinkedList.java @@ -4,213 +4,185 @@ public class CursorLinkedList { - - private static class Node { + private static class Node { - T element; - int next; + T element; + int next; - Node(T element, int next) { - this.element = element; - this.next = next; - } - } - - private final int os; - private int head; - private final Node[] cursorSpace; - private int count; - private final static int CURSOR_SPACE_SIZE = 100; - - - - { - // init at loading time - cursorSpace = new Node[CURSOR_SPACE_SIZE]; - for (int i = 0; i < CURSOR_SPACE_SIZE; i++) { - cursorSpace[i] = new Node<>(null, i + 1); - } - cursorSpace[CURSOR_SPACE_SIZE - 1].next = 0; + Node(T element, int next) { + this.element = element; + this.next = next; } - - - public CursorLinkedList() { - os = 0; - count = 0; - head = -1; + } + + private final int os; + private int head; + private final Node[] cursorSpace; + private int count; + private static final int CURSOR_SPACE_SIZE = 100; + + { + // init at loading time + cursorSpace = new Node[CURSOR_SPACE_SIZE]; + for (int i = 0; i < CURSOR_SPACE_SIZE; i++) { + cursorSpace[i] = new Node<>(null, i + 1); } + cursorSpace[CURSOR_SPACE_SIZE - 1].next = 0; + } - public void printList() { + public CursorLinkedList() { + os = 0; + count = 0; + head = -1; + } - if (head != -1) { + public void printList() { + if (head != -1) { - int start = head; - while (start != -1) { - - T element = cursorSpace[start].element; - System.out.println(element.toString()); - start = cursorSpace[start].next; - } - } + int start = head; + while (start != -1) { + T element = cursorSpace[start].element; + System.out.println(element.toString()); + start = cursorSpace[start].next; + } } - - - /** - * @return the logical index of the element within the list , not the actual - * index of the [cursorSpace] array - */ - public int indexOf(T element) { - - - Objects.requireNonNull(element); - Node iterator = cursorSpace[head]; - for (int i = 0; i < count; i++) { - if (iterator.element.equals(element)) { - return i; - } - iterator = cursorSpace[iterator.next]; - } - - - return -1; + } + + /** + * @return the logical index of the element within the list , not the actual index of the + * [cursorSpace] array + */ + public int indexOf(T element) { + + Objects.requireNonNull(element); + Node iterator = cursorSpace[head]; + for (int i = 0; i < count; i++) { + if (iterator.element.equals(element)) { + return i; + } + iterator = cursorSpace[iterator.next]; } + return -1; + } - /** - * @param position , the logical index of the element , not the actual one - * within the [cursorSpace] array . - * this method should be used to get the index give by indexOf() method. - * @return - */ - - public T get(int position) { - - if (position >= 0 && position < count) { - - int start = head; - int counter = 0; - while (start != -1) { + /** + * @param position , the logical index of the element , not the actual one within the + * [cursorSpace] array . this method should be used to get the index give by indexOf() method. + * @return + */ + public T get(int position) { - T element = cursorSpace[start].element; - if (counter == position) { - return element; - } + if (position >= 0 && position < count) { - start = cursorSpace[start].next; - counter++; - } + int start = head; + int counter = 0; + while (start != -1) { + T element = cursorSpace[start].element; + if (counter == position) { + return element; } - return null; + start = cursorSpace[start].next; + counter++; + } } + return null; + } - public void removeByIndex(int index) { + public void removeByIndex(int index) { - if (index >= 0 && index < count) { - - T element = get(index); - remove(element); - } + if (index >= 0 && index < count) { + T element = get(index); + remove(element); } + } - public void remove(T element) { - - - Objects.requireNonNull(element); - - // case element is in the head - T temp_element = cursorSpace[head].element; - int temp_next = cursorSpace[head].next; - if (temp_element.equals(element)) { - free(head); - head = temp_next; - } else { // otherwise cases + public void remove(T element) { - int prev_index = head; - int current_index = cursorSpace[prev_index].next; + Objects.requireNonNull(element); - while (current_index != -1) { + // case element is in the head + T temp_element = cursorSpace[head].element; + int temp_next = cursorSpace[head].next; + if (temp_element.equals(element)) { + free(head); + head = temp_next; + } else { // otherwise cases - T current_element = cursorSpace[current_index].element; - if (current_element.equals(element)) { - cursorSpace[prev_index].next = cursorSpace[current_index].next; - free(current_index); - break; - } + int prev_index = head; + int current_index = cursorSpace[prev_index].next; - prev_index = current_index; - current_index = cursorSpace[prev_index].next; - } + while (current_index != -1) { + T current_element = cursorSpace[current_index].element; + if (current_element.equals(element)) { + cursorSpace[prev_index].next = cursorSpace[current_index].next; + free(current_index); + break; } - - count--; - - } - - private void free(int index) { - - Node os_node = cursorSpace[os]; - int os_next = os_node.next; - cursorSpace[os].next = index; - cursorSpace[index].element = null; - cursorSpace[index].next = os_next; - + prev_index = current_index; + current_index = cursorSpace[prev_index].next; + } } + count--; + } - public void append(T element) { - - Objects.requireNonNull(element); - int availableIndex = alloc(); - cursorSpace[availableIndex].element = element; + private void free(int index) { - if (head == -1) { - head = availableIndex; - } - - int iterator = head; - while (cursorSpace[iterator].next != -1) { - iterator = cursorSpace[iterator].next; - } + Node os_node = cursorSpace[os]; + int os_next = os_node.next; + cursorSpace[os].next = index; + cursorSpace[index].element = null; + cursorSpace[index].next = os_next; + } - cursorSpace[iterator].next = availableIndex; - cursorSpace[availableIndex].next = -1; + public void append(T element) { + Objects.requireNonNull(element); + int availableIndex = alloc(); + cursorSpace[availableIndex].element = element; - count++; + if (head == -1) { + head = availableIndex; } - /** - * @return the index of the next available node - */ - private int alloc() { - + int iterator = head; + while (cursorSpace[iterator].next != -1) { + iterator = cursorSpace[iterator].next; + } - //1- get the index at which the os is pointing - int availableNodeIndex = cursorSpace[os].next; + cursorSpace[iterator].next = availableIndex; + cursorSpace[availableIndex].next = -1; - if (availableNodeIndex == 0) { - throw new OutOfMemoryError(); - } + count++; + } - //2- make the os point to the next of the @var{availableNodeIndex} - int availableNext = cursorSpace[availableNodeIndex].next; - cursorSpace[os].next = availableNext; + /** @return the index of the next available node */ + private int alloc() { - // this to indicate an end of the list , helpful at testing since any err - // would throw an outOfBoundException - cursorSpace[availableNodeIndex].next = -1; - - return availableNodeIndex; + // 1- get the index at which the os is pointing + int availableNodeIndex = cursorSpace[os].next; + if (availableNodeIndex == 0) { + throw new OutOfMemoryError(); } + // 2- make the os point to the next of the @var{availableNodeIndex} + int availableNext = cursorSpace[availableNodeIndex].next; + cursorSpace[os].next = availableNext; + + // this to indicate an end of the list , helpful at testing since any err + // would throw an outOfBoundException + cursorSpace[availableNodeIndex].next = -1; + return availableNodeIndex; + } } diff --git a/DataStructures/Lists/DoublyLinkedList.java b/DataStructures/Lists/DoublyLinkedList.java index c1250b754003..5b22d68c4827 100644 --- a/DataStructures/Lists/DoublyLinkedList.java +++ b/DataStructures/Lists/DoublyLinkedList.java @@ -1,343 +1,307 @@ package DataStructures.Lists; /** - * This class implements a DoublyLinkedList. This is done using the classes - * LinkedList and Link. - *

- * A linked list is similar to an array, it holds values. However, - * links in a linked list do not have indexes. With a linked list - * you do not need to predetermine it's size as it grows and shrinks - * as it is edited. This is an example of a double ended, doubly - * linked list. Each link references the next link and the previous - * one. + * This class implements a DoublyLinkedList. This is done using the classes LinkedList and Link. + * + *

A linked list is similar to an array, it holds values. However, links in a linked list do not + * have indexes. With a linked list you do not need to predetermine it's size as it grows and + * shrinks as it is edited. This is an example of a double ended, doubly linked list. Each link + * references the next link and the previous one. * * @author Unknown */ - public class DoublyLinkedList { - /** - * Head refers to the front of the list - */ - private Link head; - /** - * Tail refers to the back of the list - */ - private Link tail; - - /** - * Size refers to the number of elements present in the list - */ - private int size; - - /** - * Default Constructor - */ - public DoublyLinkedList() { - head = null; - tail = null; - size = 0; - } - - /** - * Constructs a list containing the elements of the array - * - * @param array the array whose elements are to be placed into this list - * @throws NullPointerException if the specified collection is null - */ - public DoublyLinkedList(int[] array) { - if (array == null) throw new NullPointerException(); - for (int i : array) { - insertTail(i); - } - size = array.length; + /** Head refers to the front of the list */ + private Link head; + /** Tail refers to the back of the list */ + private Link tail; + + /** Size refers to the number of elements present in the list */ + private int size; + + /** Default Constructor */ + public DoublyLinkedList() { + head = null; + tail = null; + size = 0; + } + + /** + * Constructs a list containing the elements of the array + * + * @param array the array whose elements are to be placed into this list + * @throws NullPointerException if the specified collection is null + */ + public DoublyLinkedList(int[] array) { + if (array == null) throw new NullPointerException(); + for (int i : array) { + insertTail(i); } - - /** - * Insert an element at the head - * - * @param x Element to be inserted - */ - public void insertHead(int x) { - Link newLink = new Link(x); // Create a new link with a value attached to it - if (isEmpty()) // Set the first element added to be the tail - tail = newLink; - else - head.previous = newLink; // newLink <-- currenthead(head) - newLink.next = head; // newLink <--> currenthead(head) - head = newLink; // newLink(head) <--> oldhead - ++size; + size = array.length; + } + + /** + * Insert an element at the head + * + * @param x Element to be inserted + */ + public void insertHead(int x) { + Link newLink = new Link(x); // Create a new link with a value attached to it + if (isEmpty()) // Set the first element added to be the tail + tail = newLink; + else head.previous = newLink; // newLink <-- currenthead(head) + newLink.next = head; // newLink <--> currenthead(head) + head = newLink; // newLink(head) <--> oldhead + ++size; + } + + /** + * Insert an element at the tail + * + * @param x Element to be inserted + */ + public void insertTail(int x) { + Link newLink = new Link(x); + newLink.next = null; // currentTail(tail) newlink --> + if (isEmpty()) { // Check if there are no elements in list then it adds first element + tail = newLink; + head = tail; + } else { + tail.next = newLink; // currentTail(tail) --> newLink --> + newLink.previous = tail; // currentTail(tail) <--> newLink --> + tail = newLink; // oldTail <--> newLink(tail) --> } - - /** - * Insert an element at the tail - * - * @param x Element to be inserted - */ - public void insertTail(int x) { + ++size; + } + + /** + * Insert an element at the index + * + * @param x Element to be inserted + * @param index Index(from start) at which the element x to be inserted + */ + public void insertElementByIndex(int x, int index) { + if (index > size) throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); + if (index == 0) { + insertHead(x); + } else { + if (index == size) { + insertTail(x); + } else { Link newLink = new Link(x); - newLink.next = null; // currentTail(tail) newlink --> - if (isEmpty()) { // Check if there are no elements in list then it adds first element - tail = newLink; - head = tail; - } else { - tail.next = newLink; // currentTail(tail) --> newLink --> - newLink.previous = tail; // currentTail(tail) <--> newLink --> - tail = newLink; // oldTail <--> newLink(tail) --> + Link previousLink = head; // + for (int i = 1; i < index; i++) { // Loop to reach the index + previousLink = previousLink.next; } - ++size; + // previousLink is the Link at index - 1 from start + previousLink.next.previous = newLink; + newLink.next = previousLink.next; + newLink.previous = previousLink; + previousLink.next = newLink; + } } - - /** - * Insert an element at the index - * - * @param x Element to be inserted - * @param index Index(from start) at which the element x to be inserted - * - */ - public void insertElementByIndex(int x,int index){ - if(index > size) throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); - if(index == 0){ - insertHead(x); - }else{ - if(index == size){ - insertTail(x); - }else{ - Link newLink = new Link(x); - Link previousLink = head; // - for(int i = 1; i < index; i++){ //Loop to reach the index - previousLink = previousLink.next; - } - // previousLink is the Link at index - 1 from start - previousLink.next.previous = newLink; - newLink.next = previousLink.next; - newLink.previous = previousLink; - previousLink.next = newLink; - } - } - ++size; - + ++size; + } + + /** + * Delete the element at the head + * + * @return The new head + */ + public Link deleteHead() { + Link temp = head; + head = head.next; // oldHead <--> 2ndElement(head) + + if (head == null) { + tail = null; + } else { + head.previous = + null; // oldHead --> 2ndElement(head) nothing pointing at old head so will be removed } - - /** - * Delete the element at the head - * - * @return The new head - */ - public Link deleteHead() { - Link temp = head; - head = head.next; // oldHead <--> 2ndElement(head) - - if (head == null) { - tail = null; - } else { - head.previous = null; // oldHead --> 2ndElement(head) nothing pointing at old head so will be removed - } - --size; - return temp; + --size; + return temp; + } + + /** + * Delete the element at the tail + * + * @return The new tail + */ + public Link deleteTail() { + Link temp = tail; + tail = tail.previous; // 2ndLast(tail) <--> oldTail --> null + + if (tail == null) { + head = null; + } else { + tail.next = null; // 2ndLast(tail) --> null } - - /** - * Delete the element at the tail - * - * @return The new tail - */ - public Link deleteTail() { - Link temp = tail; - tail = tail.previous; // 2ndLast(tail) <--> oldTail --> null - - if (tail == null) { - head = null; - } else{ - tail.next = null; // 2ndLast(tail) --> null - } - --size; - return temp; + --size; + return temp; + } + + /** + * Delete the element from somewhere in the list + * + * @param x element to be deleted + * @return Link deleted + */ + public void delete(int x) { + Link current = head; + + while (current.value != x) { // Find the position to delete + if (current != tail) { + current = current.next; + } else { // If we reach the tail and the element is still not found + throw new RuntimeException("The element to be deleted does not exist!"); + } } - /** - * Delete the element from somewhere in the list - * - * @param x element to be deleted - * @return Link deleted - */ - public void delete(int x) { - Link current = head; - - while (current.value != x) {// Find the position to delete - if (current != tail) { - current = current.next; - } else {// If we reach the tail and the element is still not found - throw new RuntimeException("The element to be deleted does not exist!"); - } - } - - if (current == head) - deleteHead(); - - else if (current == tail) - deleteTail(); - - else { // Before: 1 <--> 2(current) <--> 3 - current.previous.next = current.next; // 1 --> 3 - current.next.previous = current.previous; // 1 <--> 3 - } - --size; + if (current == head) deleteHead(); + else if (current == tail) deleteTail(); + else { // Before: 1 <--> 2(current) <--> 3 + current.previous.next = current.next; // 1 --> 3 + current.next.previous = current.previous; // 1 <--> 3 } - - /** - * Inserts element and reorders - * - * @param x Element to be added - */ - public void insertOrdered(int x) { - Link newLink = new Link(x); - Link current = head; - while (current != null && x > current.value) // Find the position to insert - current = current.next; - - if (current == head) - insertHead(x); - - else if (current == null) - insertTail(x); - - else { // Before: 1 <--> 2(current) <--> 3 - newLink.previous = current.previous; // 1 <-- newLink - current.previous.next = newLink; // 1 <--> newLink - newLink.next = current; // 1 <--> newLink --> 2(current) <--> 3 - current.previous = newLink; // 1 <--> newLink <--> 2(current) <--> 3 - } - ++size; + --size; + } + + /** + * Inserts element and reorders + * + * @param x Element to be added + */ + public void insertOrdered(int x) { + Link newLink = new Link(x); + Link current = head; + while (current != null && x > current.value) // Find the position to insert + current = current.next; + + if (current == head) insertHead(x); + else if (current == null) insertTail(x); + else { // Before: 1 <--> 2(current) <--> 3 + newLink.previous = current.previous; // 1 <-- newLink + current.previous.next = newLink; // 1 <--> newLink + newLink.next = current; // 1 <--> newLink --> 2(current) <--> 3 + current.previous = newLink; // 1 <--> newLink <--> 2(current) <--> 3 } - - /** - * Deletes the passed node from the current list - * - * @param z Element to be deleted - */ - public void deleteNode(Link z) { - if(z.next == null){ - deleteTail(); - } else if(z == head){ - deleteHead(); - } else{ //before <-- 1 <--> 2(z) <--> 3 --> - z.previous.next = z.next; // 1 --> 3 - z.next.previous = z.previous; // 1 <--> 3 - } - --size; + ++size; + } + + /** + * Deletes the passed node from the current list + * + * @param z Element to be deleted + */ + public void deleteNode(Link z) { + if (z.next == null) { + deleteTail(); + } else if (z == head) { + deleteHead(); + } else { // before <-- 1 <--> 2(z) <--> 3 --> + z.previous.next = z.next; // 1 --> 3 + z.next.previous = z.previous; // 1 <--> 3 } - - public static void removeDuplicates(DoublyLinkedList l ) { - Link linkOne = l.head ; - while(linkOne.next != null) { // list is present - Link linkTwo = linkOne.next; // second link for comparison - while(linkTwo.next!= null) { - if(linkOne.value == linkTwo.value) // if there are duplicates values then - l.delete(linkTwo.value); // delete the link - linkTwo = linkTwo.next ; // go to next link - } - linkOne = linkOne.next; // go to link link to iterate the whole list again - } + --size; + } + + public static void removeDuplicates(DoublyLinkedList l) { + Link linkOne = l.head; + while (linkOne.next != null) { // list is present + Link linkTwo = linkOne.next; // second link for comparison + while (linkTwo.next != null) { + if (linkOne.value == linkTwo.value) // if there are duplicates values then + l.delete(linkTwo.value); // delete the link + linkTwo = linkTwo.next; // go to next link + } + linkOne = linkOne.next; // go to link link to iterate the whole list again } - - /** - * Clears List - * - */ - public void clearList(){ - head = null; - tail = null; - size = 0; - } - - /** - * Returns true if list is empty - * - * @return true if list is empty - */ - public boolean isEmpty() { - return (head == null); - } - - /** - * Prints contents of the list - */ - public void display() { // Prints contents of the list - Link current = head; - while (current != null) { - current.displayLink(); - current = current.next; - } - System.out.println(); + } + + /** Clears List */ + public void clearList() { + head = null; + tail = null; + size = 0; + } + + /** + * Returns true if list is empty + * + * @return true if list is empty + */ + public boolean isEmpty() { + return (head == null); + } + + /** Prints contents of the list */ + public void display() { // Prints contents of the list + Link current = head; + while (current != null) { + current.displayLink(); + current = current.next; } + System.out.println(); + } } /** - * This class is used to implement the nodes of the - * linked list. + * This class is used to implement the nodes of the linked list. * * @author Unknown */ class Link { - /** - * Value of node - */ - public int value; - /** - * This points to the link in front of the new link - */ - public Link next; - /** - * This points to the link behind the new link - */ - public Link previous; - - /** - * Constructor - * - * @param value Value of node - */ - public Link(int value) { - this.value = value; - } - - /** - * Displays the node - */ - public void displayLink() { - System.out.print(value + " "); - } - - /** - * Main Method - * - * @param args Command line arguments - */ - public static void main(String args[]) { - DoublyLinkedList myList = new DoublyLinkedList(); - myList.insertHead(13); - myList.insertHead(7); - myList.insertHead(10); - myList.display(); // <-- 10(head) <--> 7 <--> 13(tail) --> - - myList.insertTail(11); - myList.display(); // <-- 10(head) <--> 7 <--> 13 <--> 11(tail) --> - - myList.deleteTail(); - myList.display(); // <-- 10(head) <--> 7 <--> 13(tail) --> - - myList.delete(7); - myList.display(); // <-- 10(head) <--> 13(tail) --> - - myList.insertOrdered(23); - myList.insertOrdered(67); - myList.insertOrdered(3); - myList.display(); // <-- 3(head) <--> 10 <--> 13 <--> 23 <--> 67(tail) --> - myList.insertElementByIndex(5, 1); - myList.display(); // <-- 3(head) <--> 5 <--> 10 <--> 13 <--> 23 <--> 67(tail) --> - myList.clearList(); - myList.display(); - myList.insertHead(20); - myList.display(); - } + /** Value of node */ + public int value; + /** This points to the link in front of the new link */ + public Link next; + /** This points to the link behind the new link */ + public Link previous; + + /** + * Constructor + * + * @param value Value of node + */ + public Link(int value) { + this.value = value; + } + + /** Displays the node */ + public void displayLink() { + System.out.print(value + " "); + } + + /** + * Main Method + * + * @param args Command line arguments + */ + public static void main(String args[]) { + DoublyLinkedList myList = new DoublyLinkedList(); + myList.insertHead(13); + myList.insertHead(7); + myList.insertHead(10); + myList.display(); // <-- 10(head) <--> 7 <--> 13(tail) --> + + myList.insertTail(11); + myList.display(); // <-- 10(head) <--> 7 <--> 13 <--> 11(tail) --> + + myList.deleteTail(); + myList.display(); // <-- 10(head) <--> 7 <--> 13(tail) --> + + myList.delete(7); + myList.display(); // <-- 10(head) <--> 13(tail) --> + + myList.insertOrdered(23); + myList.insertOrdered(67); + myList.insertOrdered(3); + myList.display(); // <-- 3(head) <--> 10 <--> 13 <--> 23 <--> 67(tail) --> + myList.insertElementByIndex(5, 1); + myList.display(); // <-- 3(head) <--> 5 <--> 10 <--> 13 <--> 23 <--> 67(tail) --> + myList.clearList(); + myList.display(); + myList.insertHead(20); + myList.display(); + } } diff --git a/DataStructures/Lists/MergeSortedArrayList.java b/DataStructures/Lists/MergeSortedArrayList.java index ea32e031f7dc..45f30f66c4fd 100644 --- a/DataStructures/Lists/MergeSortedArrayList.java +++ b/DataStructures/Lists/MergeSortedArrayList.java @@ -3,58 +3,54 @@ import java.util.ArrayList; import java.util.List; -/** - * @author https://github.com/shellhub - */ - +/** @author https://github.com/shellhub */ public class MergeSortedArrayList { - public static void main(String[] args) { - List listA = new ArrayList<>(); - List listB = new ArrayList<>(); - List listC = new ArrayList<>(); - - /* init ListA and List B */ - for (int i = 1; i <= 10; i += 2) { - listA.add(i); /* listA: [1, 3, 5, 7, 9] */ - listB.add(i + 1); /* listB: [2, 4, 6, 8, 10] */ - } - - /* merge listA and listB to listC */ - merge(listA, listB, listC); - - System.out.println("listA: " + listA); - System.out.println("listB: " + listB); - System.out.println("listC: " + listC); + public static void main(String[] args) { + List listA = new ArrayList<>(); + List listB = new ArrayList<>(); + List listC = new ArrayList<>(); + + /* init ListA and List B */ + for (int i = 1; i <= 10; i += 2) { + listA.add(i); /* listA: [1, 3, 5, 7, 9] */ + listB.add(i + 1); /* listB: [2, 4, 6, 8, 10] */ + } + + /* merge listA and listB to listC */ + merge(listA, listB, listC); + + System.out.println("listA: " + listA); + System.out.println("listB: " + listB); + System.out.println("listC: " + listC); + } + + /** + * merge two sorted ArrayList + * + * @param listA the first list to merge + * @param listB the second list to merge + * @param listC the result list after merging + */ + public static void merge(List listA, List listB, List listC) { + int pa = 0; /* the index of listA */ + int pb = 0; /* the index of listB */ + + while (pa < listA.size() && pb < listB.size()) { + if (listA.get(pa) <= listB.get(pb)) { + listC.add(listA.get(pa++)); + } else { + listC.add(listB.get(pb++)); + } } - /** - * merge two sorted ArrayList - * - * @param listA the first list to merge - * @param listB the second list to merge - * @param listC the result list after merging - */ - public static void merge(List listA, List listB, List listC) { - int pa = 0; /* the index of listA */ - int pb = 0; /* the index of listB */ - - while (pa < listA.size() && pb < listB.size()) { - if (listA.get(pa) <= listB.get(pb)) { - listC.add(listA.get(pa++)); - } else { - listC.add(listB.get(pb++)); - } - } - - /* copy left element of listA to listC */ - while (pa < listA.size()) { - listC.add(listA.get(pa++)); - } - - /* copy left element of listB to listC */ - while (pb < listB.size()) { - listC.add(listB.get(pb++)); - } + /* copy left element of listA to listC */ + while (pa < listA.size()) { + listC.add(listA.get(pa++)); } + /* copy left element of listB to listC */ + while (pb < listB.size()) { + listC.add(listB.get(pb++)); + } + } } diff --git a/DataStructures/Lists/MergeSortedSinglyLinkedList.java b/DataStructures/Lists/MergeSortedSinglyLinkedList.java index 2daae0d70574..526a539ce41e 100644 --- a/DataStructures/Lists/MergeSortedSinglyLinkedList.java +++ b/DataStructures/Lists/MergeSortedSinglyLinkedList.java @@ -2,50 +2,50 @@ public class MergeSortedSinglyLinkedList extends SinglyLinkedList { - public static void main(String[] args) { - SinglyLinkedList listA = new SinglyLinkedList(); - SinglyLinkedList listB = new SinglyLinkedList(); + public static void main(String[] args) { + SinglyLinkedList listA = new SinglyLinkedList(); + SinglyLinkedList listB = new SinglyLinkedList(); - for (int i = 2; i <= 10; i += 2) { - listA.insert(i); - listB.insert(i - 1); - } - assert listA.toString().equals("2->4->6->8->10"); - assert listB.toString().equals("1->3->5->7->9"); - assert merge(listA, listB).toString().equals("1->2->3->4->5->6->7->8->9->10"); + for (int i = 2; i <= 10; i += 2) { + listA.insert(i); + listB.insert(i - 1); } + assert listA.toString().equals("2->4->6->8->10"); + assert listB.toString().equals("1->3->5->7->9"); + assert merge(listA, listB).toString().equals("1->2->3->4->5->6->7->8->9->10"); + } - /** - * Merge two sorted SingleLinkedList - * - * @param listA the first sorted list - * @param listB the second sored list - * @return merged sorted list - */ - public static SinglyLinkedList merge(SinglyLinkedList listA, SinglyLinkedList listB) { - Node headA = listA.getHead(); - Node headB = listB.getHead(); + /** + * Merge two sorted SingleLinkedList + * + * @param listA the first sorted list + * @param listB the second sored list + * @return merged sorted list + */ + public static SinglyLinkedList merge(SinglyLinkedList listA, SinglyLinkedList listB) { + Node headA = listA.getHead(); + Node headB = listB.getHead(); - int size = listA.size() + listB.size(); + int size = listA.size() + listB.size(); - Node head = new Node(); - Node tail = head; - while (headA != null && headB != null) { - if (headA.value <= headB.value) { - tail.next = headA; - headA = headA.next; - } else { - tail.next = headB; - headB = headB.next; - } - tail = tail.next; - } - if (headA == null) { - tail.next = headB; - } - if (headB == null) { - tail.next = headA; - } - return new SinglyLinkedList(head.next, size); + Node head = new Node(); + Node tail = head; + while (headA != null && headB != null) { + if (headA.value <= headB.value) { + tail.next = headA; + headA = headA.next; + } else { + tail.next = headB; + headB = headB.next; + } + tail = tail.next; } + if (headA == null) { + tail.next = headB; + } + if (headB == null) { + tail.next = headA; + } + return new SinglyLinkedList(head.next, size); + } } diff --git a/DataStructures/Lists/Merge_K_SortedLinkedlist.java b/DataStructures/Lists/Merge_K_SortedLinkedlist.java index bdee79f8f5f7..61d3a90525ea 100644 --- a/DataStructures/Lists/Merge_K_SortedLinkedlist.java +++ b/DataStructures/Lists/Merge_K_SortedLinkedlist.java @@ -4,53 +4,51 @@ import java.util.Comparator; import java.util.PriorityQueue; -/** - * @author Arun Pandey (https://github.com/pandeyarun709) - */ +/** @author Arun Pandey (https://github.com/pandeyarun709) */ public class Merge_K_SortedLinkedlist { - /** - * This function merge K sorted LinkedList - * - * @param a array of LinkedList - * @param N size of array - * @return node - */ - Node mergeKList(Node[] a, int N) { - // Min Heap - PriorityQueue min = new PriorityQueue<>(Comparator.comparingInt(x -> x.data)); - - // adding head of all linkedList in min heap - min.addAll(Arrays.asList(a).subList(0, N)); - - // Make new head among smallest heads in K linkedList - Node head = min.poll(); - min.add(head.next); - Node curr = head; - - // merging LinkedList - while (!min.isEmpty()) { - - Node temp = min.poll(); - curr.next = temp; - curr = temp; - - // Add Node in min Heap only if temp.next is not null - if (temp.next != null) { - min.add(temp.next); - } - } - - return head; + /** + * This function merge K sorted LinkedList + * + * @param a array of LinkedList + * @param N size of array + * @return node + */ + Node mergeKList(Node[] a, int N) { + // Min Heap + PriorityQueue min = new PriorityQueue<>(Comparator.comparingInt(x -> x.data)); + + // adding head of all linkedList in min heap + min.addAll(Arrays.asList(a).subList(0, N)); + + // Make new head among smallest heads in K linkedList + Node head = min.poll(); + min.add(head.next); + Node curr = head; + + // merging LinkedList + while (!min.isEmpty()) { + + Node temp = min.poll(); + curr.next = temp; + curr = temp; + + // Add Node in min Heap only if temp.next is not null + if (temp.next != null) { + min.add(temp.next); + } } - private class Node { - private int data; - private Node next; + return head; + } - public Node(int d) { - this.data = d; - next = null; - } + private class Node { + private int data; + private Node next; + + public Node(int d) { + this.data = d; + next = null; } + } } diff --git a/DataStructures/Lists/SearchSinglyLinkedListRecursion.java b/DataStructures/Lists/SearchSinglyLinkedListRecursion.java index 10755c0b84ae..2f5cd4b18ca6 100644 --- a/DataStructures/Lists/SearchSinglyLinkedListRecursion.java +++ b/DataStructures/Lists/SearchSinglyLinkedListRecursion.java @@ -1,32 +1,31 @@ package DataStructures.Lists; public class SearchSinglyLinkedListRecursion extends SinglyLinkedList { - public static void main(String[] args) { - SearchSinglyLinkedListRecursion list = new SearchSinglyLinkedListRecursion(); - for (int i = 1; i <= 10; ++i) { - list.insert(i); - } - - for (int i = 1; i <= 10; ++i) { - assert list.search(i); - } - assert !list.search(-1) - && !list.search(100); + public static void main(String[] args) { + SearchSinglyLinkedListRecursion list = new SearchSinglyLinkedListRecursion(); + for (int i = 1; i <= 10; ++i) { + list.insert(i); } - /** - * Test if the value key is present in the list using recursion. - * - * @param node the head node. - * @param key the value to be searched. - * @return {@code true} if key is present in the list, otherwise {@code false}. - */ - private boolean searchRecursion(Node node, int key) { - return node != null && (node.value == key || searchRecursion(node.next, key)); + for (int i = 1; i <= 10; ++i) { + assert list.search(i); } + assert !list.search(-1) && !list.search(100); + } - @Override - public boolean search(int key) { - return searchRecursion(getHead(), key); - } + /** + * Test if the value key is present in the list using recursion. + * + * @param node the head node. + * @param key the value to be searched. + * @return {@code true} if key is present in the list, otherwise {@code false}. + */ + private boolean searchRecursion(Node node, int key) { + return node != null && (node.value == key || searchRecursion(node.next, key)); + } + + @Override + public boolean search(int key) { + return searchRecursion(getHead(), key); + } } diff --git a/DataStructures/Lists/SinglyLinkedList.java b/DataStructures/Lists/SinglyLinkedList.java index 2e7c5d37b75b..d6b0beba76a6 100644 --- a/DataStructures/Lists/SinglyLinkedList.java +++ b/DataStructures/Lists/SinglyLinkedList.java @@ -1,333 +1,301 @@ package DataStructures.Lists; /** - * This class implements a SinglyLinked List. This is done - * using SinglyLinkedList class and a LinkForLinkedList Class. - *

- * A linked list is similar to an array, it hold values. - * However, links in a linked list do not have indexes. With - * a linked list you do not need to predetermine it's size as - * it grows and shrinks as it is edited. This is an example of - * a singly linked list. Elements can only be added/removed - * at the head/front of the list. + * This class implements a SinglyLinked List. This is done using SinglyLinkedList class and a + * LinkForLinkedList Class. + * + *

A linked list is similar to an array, it hold values. However, links in a linked list do not + * have indexes. With a linked list you do not need to predetermine it's size as it grows and + * shrinks as it is edited. This is an example of a singly linked list. Elements can only be + * added/removed at the head/front of the list. */ public class SinglyLinkedList { - /** - * Head refer to the front of the list - */ - private Node head; - - /** - * Size of SinglyLinkedList - */ - private int size; - - /** - * Init SinglyLinkedList - */ - public SinglyLinkedList() { - head = null; - size = 0; + /** Head refer to the front of the list */ + private Node head; + + /** Size of SinglyLinkedList */ + private int size; + + /** Init SinglyLinkedList */ + public SinglyLinkedList() { + head = null; + size = 0; + } + + /** + * Init SinglyLinkedList with specified head node and size + * + * @param head the head node of list + * @param size the size of list + */ + public SinglyLinkedList(Node head, int size) { + this.head = head; + this.size = size; + } + + /** + * Inserts an element at the head of the list + * + * @param x element to be added + */ + public void insertHead(int x) { + insertNth(x, 0); + } + + /** + * Insert an element at the tail of the list + * + * @param data element to be added + */ + public void insert(int data) { + insertNth(data, size); + } + + /** + * Inserts a new node at a specified position of the list + * + * @param data data to be stored in a new node + * @param position position at which a new node is to be inserted + */ + public void insertNth(int data, int position) { + checkBounds(position, 0, size); + Node newNode = new Node(data); + if (head == null) { + /* the list is empty */ + head = newNode; + size++; + return; + } else if (position == 0) { + /* insert at the head of the list */ + newNode.next = head; + head = newNode; + size++; + return; } - - /** - * Init SinglyLinkedList with specified head node and size - * - * @param head the head node of list - * @param size the size of list - */ - public SinglyLinkedList(Node head, int size) { - this.head = head; - this.size = size; - } - - /** - * Inserts an element at the head of the list - * - * @param x element to be added - */ - public void insertHead(int x) { - insertNth(x, 0); - } - - /** - * Insert an element at the tail of the list - * - * @param data element to be added - */ - public void insert(int data) { - insertNth(data, size); - } - - /** - * Inserts a new node at a specified position of the list - * - * @param data data to be stored in a new node - * @param position position at which a new node is to be inserted - */ - public void insertNth(int data, int position) { - checkBounds(position, 0, size); - Node newNode = new Node(data); - if (head == null) { /* the list is empty */ - head = newNode; - size++; - return; - } else if (position == 0) { /* insert at the head of the list */ - newNode.next = head; - head = newNode; - size++; - return; - } - Node cur = head; - for (int i = 0; i < position - 1; ++i) { - cur = cur.next; - } - newNode.next = cur.next; - cur.next = newNode; - size++; - } - - - /** - * Deletes a node at the head - */ - public void deleteHead() { - deleteNth(0); - } - - /** - * Deletes an element at the tail - */ - public void delete() { - deleteNth(size - 1); + Node cur = head; + for (int i = 0; i < position - 1; ++i) { + cur = cur.next; } - - /** - * Deletes an element at Nth position - */ - public void deleteNth(int position) { - checkBounds(position, 0, size - 1); - if (position == 0) { - Node destroy = head; - head = head.next; - destroy = null; /* clear to let GC do its work */ - size--; - return; - } - Node cur = head; - for (int i = 0; i < position - 1; ++i) { - cur = cur.next; - } - - Node destroy = cur.next; - cur.next = cur.next.next; - destroy = null; // clear to let GC do its work - - size--; - } - - /** - * @param position to check position - * @param low low index - * @param high high index - * @throws IndexOutOfBoundsException if {@code position} not in range {@code low} to {@code high} - */ - public void checkBounds(int position, int low, int high) { - if (position > high || position < low) { - throw new IndexOutOfBoundsException(position + ""); - } + newNode.next = cur.next; + cur.next = newNode; + size++; + } + + /** Deletes a node at the head */ + public void deleteHead() { + deleteNth(0); + } + + /** Deletes an element at the tail */ + public void delete() { + deleteNth(size - 1); + } + + /** Deletes an element at Nth position */ + public void deleteNth(int position) { + checkBounds(position, 0, size - 1); + if (position == 0) { + Node destroy = head; + head = head.next; + destroy = null; /* clear to let GC do its work */ + size--; + return; } - - /** - * Clear all nodes in the list - */ - public void clear() { - Node cur = head; - while (cur != null) { - Node prev = cur; - cur = cur.next; - prev = null; // clear to let GC do its work - } - head = null; - size = 0; + Node cur = head; + for (int i = 0; i < position - 1; ++i) { + cur = cur.next; } - /** - * Checks if the list is empty - * - * @return {@code true} if list is empty, otherwise {@code false}. - */ - public boolean isEmpty() { - return size == 0; + Node destroy = cur.next; + cur.next = cur.next.next; + destroy = null; // clear to let GC do its work + + size--; + } + + /** + * @param position to check position + * @param low low index + * @param high high index + * @throws IndexOutOfBoundsException if {@code position} not in range {@code low} to {@code high} + */ + public void checkBounds(int position, int low, int high) { + if (position > high || position < low) { + throw new IndexOutOfBoundsException(position + ""); } - - /** - * Returns the size of the linked list. - * - * @return the size of the list. - */ - public int size() { - return size; + } + + /** Clear all nodes in the list */ + public void clear() { + Node cur = head; + while (cur != null) { + Node prev = cur; + cur = cur.next; + prev = null; // clear to let GC do its work } - - /** - * Get head of the list. - * - * @return head of the list. - */ - public Node getHead() { - return head; + head = null; + size = 0; + } + + /** + * Checks if the list is empty + * + * @return {@code true} if list is empty, otherwise {@code false}. + */ + public boolean isEmpty() { + return size == 0; + } + + /** + * Returns the size of the linked list. + * + * @return the size of the list. + */ + public int size() { + return size; + } + + /** + * Get head of the list. + * + * @return head of the list. + */ + public Node getHead() { + return head; + } + + /** + * Calculate the count of the list manually + * + * @return count of the list + */ + public int count() { + int count = 0; + Node cur = head; + while (cur != null) { + cur = cur.next; + count++; } - - /** - * Calculate the count of the list manually - * - * @return count of the list - */ - public int count() { - int count = 0; - Node cur = head; - while (cur != null) { - cur = cur.next; - count++; - } - return count; + return count; + } + + /** + * Test if the value key is present in the list. + * + * @param key the value to be searched. + * @return {@code true} if key is present in the list, otherwise {@code false}. + */ + public boolean search(int key) { + Node cur = head; + while (cur != null) { + if (cur.value == key) { + return true; + } + cur = cur.next; } - - /** - * Test if the value key is present in the list. - * - * @param key the value to be searched. - * @return {@code true} if key is present in the list, otherwise {@code false}. - */ - public boolean search(int key) { - Node cur = head; - while (cur != null) { - if (cur.value == key) { - return true; - } - cur = cur.next; - } - return false; + return false; + } + + /** + * Return element at special index. + * + * @param index given index of element + * @return element at special index. + */ + public int getNth(int index) { + checkBounds(index, 0, size - 1); + Node cur = head; + for (int i = 0; i < index; ++i) { + cur = cur.next; } + return cur.value; + } - /** - * Return element at special index. - * - * @param index given index of element - * @return element at special index. - */ - public int getNth(int index) { - checkBounds(index, 0, size - 1); - Node cur = head; - for (int i = 0; i < index; ++i) { - cur = cur.next; - } - return cur.value; + @Override + public String toString() { + if (size == 0) { + return ""; } - - - @Override - public String toString() { - if (size == 0) { - return ""; - } - StringBuilder builder = new StringBuilder(); - Node cur = head; - while (cur != null) { - builder.append(cur.value).append("->"); - cur = cur.next; - } - return builder.replace(builder.length() - 2, builder.length(), "").toString(); + StringBuilder builder = new StringBuilder(); + Node cur = head; + while (cur != null) { + builder.append(cur.value).append("->"); + cur = cur.next; } - - - /** - * Driver Code - */ - public static void main(String[] arg) { - SinglyLinkedList list = new SinglyLinkedList(); - assert list.isEmpty(); - assert list.size() == 0 - && list.count() == 0; - assert list.toString().equals(""); - - /* Test insert function */ - list.insertHead(5); - list.insertHead(7); - list.insertHead(10); - list.insert(3); - list.insertNth(1, 4); - assert list.toString().equals("10->7->5->3->1"); - - /* Test search function */ - assert list.search(10) - && list.search(5) - && list.search(1) - && !list.search(100); - - /* Test get function */ - assert list.getNth(0) == 10 - && list.getNth(2) == 5 - && list.getNth(4) == 1; - - /* Test delete function */ - list.deleteHead(); - list.deleteNth(1); - list.delete(); - assert list.toString().equals("7->3"); - - assert list.size == 2 - && list.size() == list.count(); - - list.clear(); - assert list.isEmpty(); - - try { - list.delete(); - assert false; /* this should not happen */ - } catch (Exception e) { - assert true; /* this should happen */ - } + return builder.replace(builder.length() - 2, builder.length(), "").toString(); + } + + /** Driver Code */ + public static void main(String[] arg) { + SinglyLinkedList list = new SinglyLinkedList(); + assert list.isEmpty(); + assert list.size() == 0 && list.count() == 0; + assert list.toString().equals(""); + + /* Test insert function */ + list.insertHead(5); + list.insertHead(7); + list.insertHead(10); + list.insert(3); + list.insertNth(1, 4); + assert list.toString().equals("10->7->5->3->1"); + + /* Test search function */ + assert list.search(10) && list.search(5) && list.search(1) && !list.search(100); + + /* Test get function */ + assert list.getNth(0) == 10 && list.getNth(2) == 5 && list.getNth(4) == 1; + + /* Test delete function */ + list.deleteHead(); + list.deleteNth(1); + list.delete(); + assert list.toString().equals("7->3"); + + assert list.size == 2 && list.size() == list.count(); + + list.clear(); + assert list.isEmpty(); + + try { + list.delete(); + assert false; /* this should not happen */ + } catch (Exception e) { + assert true; /* this should happen */ } + } } /** - * This class is the nodes of the SinglyLinked List. - * They consist of a value and a pointer to the node - * after them. + * This class is the nodes of the SinglyLinked List. They consist of a value and a pointer to the + * node after them. */ class Node { - /** - * The value of the node - */ - int value; - - /** - * Point to the next node - */ - Node next; - - Node() { - - } - - /** - * Constructor - * - * @param value Value to be put in the node - */ - Node(int value) { - this(value, null); - } - - /** - * Constructor - * @param value Value to be put in the node - * @param next Reference to the next node - */ - Node(int value, Node next) { - this.value = value; - this.next = next; - } + /** The value of the node */ + int value; + + /** Point to the next node */ + Node next; + + Node() {} + + /** + * Constructor + * + * @param value Value to be put in the node + */ + Node(int value) { + this(value, null); + } + + /** + * Constructor + * + * @param value Value to be put in the node + * @param next Reference to the next node + */ + Node(int value, Node next) { + this.value = value; + this.next = next; + } } diff --git a/DataStructures/Queues/GenericArrayListQueue.java b/DataStructures/Queues/GenericArrayListQueue.java index 9c2f2658800d..cc37ab02eb53 100644 --- a/DataStructures/Queues/GenericArrayListQueue.java +++ b/DataStructures/Queues/GenericArrayListQueue.java @@ -4,80 +4,80 @@ /** * This class implements a GenericArrayListQueue. - *

- * A GenericArrayListQueue data structure functions the same as any specific-typed queue. - * The GenericArrayListQueue holds elemets of types to-be-specified at runtime. - * The elements that are added first are the first to be removed (FIFO) - * New elements are added to the back/rear of the queue. * + *

A GenericArrayListQueue data structure functions the same as any specific-typed queue. The + * GenericArrayListQueue holds elemets of types to-be-specified at runtime. The elements that are + * added first are the first to be removed (FIFO) New elements are added to the back/rear of the + * queue. */ public class GenericArrayListQueue { - /** - * The generic ArrayList for the queue - * T is the generic element - */ - ArrayList _queue = new ArrayList(); + /** The generic ArrayList for the queue T is the generic element */ + ArrayList _queue = new ArrayList(); - /** - * Checks if the queue has elements (not empty) - * - * @return True if the queue has elements. False otherwise. - */ - private boolean hasElements() { - return !_queue.isEmpty(); - } + /** + * Checks if the queue has elements (not empty) + * + * @return True if the queue has elements. False otherwise. + */ + private boolean hasElements() { + return !_queue.isEmpty(); + } - /** - * Checks what's at the front of the queue - * - * @return If queue is not empty, element at the front of the queue. Otherwise, null - */ - public T peek() { - T result = null; - if(this.hasElements()) { result = _queue.get(0); } - return result; + /** + * Checks what's at the front of the queue + * + * @return If queue is not empty, element at the front of the queue. Otherwise, null + */ + public T peek() { + T result = null; + if (this.hasElements()) { + result = _queue.get(0); } + return result; + } - /** - * Inserts an element of type T to the queue. - * - * @param element of type T to be added - * @return True if the element was added successfully - */ - public boolean add(T element) { - return _queue.add(element); - } + /** + * Inserts an element of type T to the queue. + * + * @param element of type T to be added + * @return True if the element was added successfully + */ + public boolean add(T element) { + return _queue.add(element); + } - /** - * Retrieve what's at the front of the queue - * - * @return If queue is not empty, element retrieved. Otherwise, null - */ - public T poll() { - T result = null; - if(this.hasElements()) { result = _queue.remove(0); } - return result; + /** + * Retrieve what's at the front of the queue + * + * @return If queue is not empty, element retrieved. Otherwise, null + */ + public T poll() { + T result = null; + if (this.hasElements()) { + result = _queue.remove(0); } + return result; + } - /** - * Main method - * - * @param args Command line arguments - */ - public static void main(String[] args) { - GenericArrayListQueue queue = new GenericArrayListQueue(); - System.out.println("Running..."); - assert queue.peek() == null; - assert queue.poll() == null; - assert queue.add(1) == true; - assert queue.peek() == 1; - assert queue.add(2) == true; - assert queue.peek() == 1; - assert queue.poll() == 1; - assert queue.peek() == 2; - assert queue.poll() == 2; - assert queue.peek() == null; - assert queue.poll() == null; - System.out.println("Finished."); - } + /** + * Main method + * + * @param args Command line arguments + */ + public static void main(String[] args) { + GenericArrayListQueue queue = new GenericArrayListQueue(); + System.out.println("Running..."); + assert queue.peek() == null; + assert queue.poll() == null; + assert queue.add(1) == true; + assert queue.peek() == 1; + assert queue.add(2) == true; + assert queue.peek() == 1; + assert queue.poll() == 1; + assert queue.peek() == 2; + assert queue.poll() == 2; + assert queue.peek() == null; + assert queue.poll() == null; + System.out.println("Finished."); + } } diff --git a/DataStructures/Queues/LinkedQueue.java b/DataStructures/Queues/LinkedQueue.java index dac13dcaaad6..b60cc4b47393 100644 --- a/DataStructures/Queues/LinkedQueue.java +++ b/DataStructures/Queues/LinkedQueue.java @@ -3,167 +3,157 @@ import java.util.NoSuchElementException; public class LinkedQueue { - class Node { - int data; - Node next; - - public Node() { - this(0); - } - - public Node(int data) { - this(data, null); - } - - public Node(int data, Node next) { - this.data = data; - this.next = next; - } - } + class Node { + int data; + Node next; - /** - * Front of Queue - */ - private Node front; - - /** - * Rear of Queue - */ - private Node rear; - - /** - * Size of Queue - */ - private int size; - - /** - * Init LinkedQueue - */ - public LinkedQueue() { - front = rear = new Node(); + public Node() { + this(0); } - /** - * Check if queue is empty - * - * @return true if queue is empty, otherwise false - */ - public boolean isEmpty() { - return size == 0; + public Node(int data) { + this(data, null); } - /** - * Add element to rear of queue - * - * @param data insert value - * @return true if add successfully - */ - public boolean enqueue(int data) { - Node newNode = new Node(data); - rear.next = newNode; - rear = newNode; /* make rear point at last node */ - size++; - return true; + public Node(int data, Node next) { + this.data = data; + this.next = next; } - - /** - * Remove element at the front of queue - * - * @return element at the front of queue - */ - public int dequeue() { - if (isEmpty()) { - throw new NoSuchElementException("queue is empty"); - } - Node destroy = front.next; - int retValue = destroy.data; - front.next = front.next.next; - destroy = null; /* clear let GC do it's work */ - size--; - - if (isEmpty()) { - front = rear; - } - - return retValue; + } + + /** Front of Queue */ + private Node front; + + /** Rear of Queue */ + private Node rear; + + /** Size of Queue */ + private int size; + + /** Init LinkedQueue */ + public LinkedQueue() { + front = rear = new Node(); + } + + /** + * Check if queue is empty + * + * @return true if queue is empty, otherwise false + */ + public boolean isEmpty() { + return size == 0; + } + + /** + * Add element to rear of queue + * + * @param data insert value + * @return true if add successfully + */ + public boolean enqueue(int data) { + Node newNode = new Node(data); + rear.next = newNode; + rear = newNode; /* make rear point at last node */ + size++; + return true; + } + + /** + * Remove element at the front of queue + * + * @return element at the front of queue + */ + public int dequeue() { + if (isEmpty()) { + throw new NoSuchElementException("queue is empty"); } - - /** - * Peek element at the front of queue without removing - * - * @return element at the front - */ - public int peekFront() { - if (isEmpty()) { - throw new NoSuchElementException("queue is empty"); - } - return front.next.data; + Node destroy = front.next; + int retValue = destroy.data; + front.next = front.next.next; + destroy = null; /* clear let GC do it's work */ + size--; + + if (isEmpty()) { + front = rear; } - /** - * Peek element at the rear of queue without removing - * - * @return element at the front - */ - public int peekRear() { - if (isEmpty()) { - throw new NoSuchElementException("queue is empty"); - } - return rear.data; + return retValue; + } + + /** + * Peek element at the front of queue without removing + * + * @return element at the front + */ + public int peekFront() { + if (isEmpty()) { + throw new NoSuchElementException("queue is empty"); } - - /** - * Return size of queue - * - * @return size of queue - */ - public int size() { - return size; + return front.next.data; + } + + /** + * Peek element at the rear of queue without removing + * + * @return element at the front + */ + public int peekRear() { + if (isEmpty()) { + throw new NoSuchElementException("queue is empty"); } - - /** - * Clear all nodes in queue - */ - public void clear() { - while (!isEmpty()) { - dequeue(); - } + return rear.data; + } + + /** + * Return size of queue + * + * @return size of queue + */ + public int size() { + return size; + } + + /** Clear all nodes in queue */ + public void clear() { + while (!isEmpty()) { + dequeue(); } + } - @Override - public String toString() { - if (isEmpty()) { - return "[]"; - } - StringBuilder builder = new StringBuilder(); - Node cur = front.next; - builder.append("["); - while (cur != null) { - builder.append(cur.data).append(", "); - cur = cur.next; - } - builder.replace(builder.length() - 2, builder.length(), "]"); - return builder.toString(); + @Override + public String toString() { + if (isEmpty()) { + return "[]"; } - - /* Driver Code */ - public static void main(String[] args) { - LinkedQueue queue = new LinkedQueue(); - assert queue.isEmpty(); - - queue.enqueue(1); /* 1 */ - queue.enqueue(2); /* 1 2 */ - queue.enqueue(3); /* 1 2 3 */ - System.out.println(queue); /* [1, 2, 3] */ - - assert queue.size() == 3; - assert queue.dequeue() == 1; - assert queue.peekFront() == 2; - assert queue.peekRear() == 3; - - queue.clear(); - assert queue.isEmpty(); - - System.out.println(queue); /* [] */ + StringBuilder builder = new StringBuilder(); + Node cur = front.next; + builder.append("["); + while (cur != null) { + builder.append(cur.data).append(", "); + cur = cur.next; } + builder.replace(builder.length() - 2, builder.length(), "]"); + return builder.toString(); + } + + /* Driver Code */ + public static void main(String[] args) { + LinkedQueue queue = new LinkedQueue(); + assert queue.isEmpty(); + + queue.enqueue(1); /* 1 */ + queue.enqueue(2); /* 1 2 */ + queue.enqueue(3); /* 1 2 3 */ + System.out.println(queue); /* [1, 2, 3] */ + + assert queue.size() == 3; + assert queue.dequeue() == 1; + assert queue.peekFront() == 2; + assert queue.peekRear() == 3; + + queue.clear(); + assert queue.isEmpty(); + + System.out.println(queue); /* [] */ + } } diff --git a/DataStructures/Queues/PriorityQueues.java b/DataStructures/Queues/PriorityQueues.java index b2b959113490..bcdfb2ec7426 100644 --- a/DataStructures/Queues/PriorityQueues.java +++ b/DataStructures/Queues/PriorityQueues.java @@ -2,101 +2,94 @@ /** * This class implements a PriorityQueue. - *

- * A priority queue adds elements into positions based on their priority. - * So the most important elements are placed at the front/on the top. - * In this example I give numbers that are bigger, a higher priority. - * Queues in theory have no fixed size but when using an array - * implementation it does. + * + *

A priority queue adds elements into positions based on their priority. So the most important + * elements are placed at the front/on the top. In this example I give numbers that are bigger, a + * higher priority. Queues in theory have no fixed size but when using an array implementation it + * does. */ class PriorityQueue { - /** - * The max size of the queue - */ - private int maxSize; - /** - * The array for the queue - */ - private int[] queueArray; - /** - * How many items are in the queue - */ - private int nItems; + /** The max size of the queue */ + private int maxSize; + /** The array for the queue */ + private int[] queueArray; + /** How many items are in the queue */ + private int nItems; - /** - * Constructor - * - * @param size Size of the queue - */ - public PriorityQueue(int size) { - maxSize = size; - queueArray = new int[size]; - nItems = 0; - } + /** + * Constructor + * + * @param size Size of the queue + */ + public PriorityQueue(int size) { + maxSize = size; + queueArray = new int[size]; + nItems = 0; + } - /** - * Inserts an element in it's appropriate place - * - * @param value Value to be inserted - */ - public void insert(int value) { - if (isFull()) { - throw new RuntimeException("Queue is full"); - } else { - int j = nItems - 1; // index of last element - while (j >= 0 && queueArray[j] > value) { - queueArray[j + 1] = queueArray[j]; // Shifts every element up to make room for insertion - j--; - } - queueArray[j + 1] = value; // Once the correct position is found the value is inserted - nItems++; - } + /** + * Inserts an element in it's appropriate place + * + * @param value Value to be inserted + */ + public void insert(int value) { + if (isFull()) { + throw new RuntimeException("Queue is full"); + } else { + int j = nItems - 1; // index of last element + while (j >= 0 && queueArray[j] > value) { + queueArray[j + 1] = queueArray[j]; // Shifts every element up to make room for insertion + j--; + } + queueArray[j + 1] = value; // Once the correct position is found the value is inserted + nItems++; } + } - /** - * Remove the element from the front of the queue - * - * @return The element removed - */ - public int remove() { - return queueArray[--nItems]; - } + /** + * Remove the element from the front of the queue + * + * @return The element removed + */ + public int remove() { + return queueArray[--nItems]; + } - /** - * Checks what's at the front of the queue - * - * @return element at the front of the queue - */ - public int peek() { - return queueArray[nItems - 1]; - } + /** + * Checks what's at the front of the queue + * + * @return element at the front of the queue + */ + public int peek() { + return queueArray[nItems - 1]; + } - /** - * Returns true if the queue is empty - * - * @return true if the queue is empty - */ - public boolean isEmpty() { - return (nItems == 0); - } + /** + * Returns true if the queue is empty + * + * @return true if the queue is empty + */ + public boolean isEmpty() { + return (nItems == 0); + } - /** - * Returns true if the queue is full - * - * @return true if the queue is full - */ - public boolean isFull() { - return (nItems == maxSize); - } + /** + * Returns true if the queue is full + * + * @return true if the queue is full + */ + public boolean isFull() { + return (nItems == maxSize); + } - /** - * Returns the number of elements in the queue - * - * @return number of elements in the queue - */ - public int getSize() { - return nItems; - } + /** + * Returns the number of elements in the queue + * + * @return number of elements in the queue + */ + public int getSize() { + return nItems; + } } /** @@ -105,22 +98,23 @@ public int getSize() { * @author Unknown */ public class PriorityQueues { - /** - * Main method - * - * @param args Command Line Arguments - */ - public static void main(String[] args) { - PriorityQueue myQueue = new PriorityQueue(4); - myQueue.insert(10); - myQueue.insert(2); - myQueue.insert(5); - myQueue.insert(3); - // [2, 3, 5, 10] Here higher numbers have higher priority, so they are on the top + /** + * Main method + * + * @param args Command Line Arguments + */ + public static void main(String[] args) { + PriorityQueue myQueue = new PriorityQueue(4); + myQueue.insert(10); + myQueue.insert(2); + myQueue.insert(5); + myQueue.insert(3); + // [2, 3, 5, 10] Here higher numbers have higher priority, so they are on the top - for (int i = 3; i >= 0; i--) - System.out.print(myQueue.remove() + " "); // will print the queue in reverse order [10, 5, 3, 2] + for (int i = 3; i >= 0; i--) + System.out.print( + myQueue.remove() + " "); // will print the queue in reverse order [10, 5, 3, 2] - // As you can see, a Priority Queue can be used as a sorting algotithm - } + // As you can see, a Priority Queue can be used as a sorting algotithm + } } diff --git a/DataStructures/Queues/Queues.java b/DataStructures/Queues/Queues.java index 2f820d70cf71..6bd5bdc484e9 100644 --- a/DataStructures/Queues/Queues.java +++ b/DataStructures/Queues/Queues.java @@ -2,148 +2,131 @@ /** * This implements Queues by using the class Queue. - *

- * 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. * + *

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. */ class Queue { - /** - * Default initial capacity. - */ - private static final int DEFAULT_CAPACITY = 10; - - /** - * Max size of the queue - */ - private int maxSize; - /** - * The array representing the queue - */ - private int[] queueArray; - /** - * Front of the queue - */ - private int front; - /** - * Rear of the queue - */ - private int rear; - /** - * How many items are in the queue - */ - private int nItems; - - /** - * init with DEFAULT_CAPACITY - */ - public Queue() { - this(DEFAULT_CAPACITY); + /** Default initial capacity. */ + private static final int DEFAULT_CAPACITY = 10; + + /** Max size of the queue */ + private int maxSize; + /** The array representing the queue */ + private int[] queueArray; + /** Front of the queue */ + private int front; + /** Rear of the queue */ + private int rear; + /** How many items are in the queue */ + private int nItems; + + /** init with DEFAULT_CAPACITY */ + public Queue() { + this(DEFAULT_CAPACITY); + } + + /** + * Constructor + * + * @param size Size of the new queue + */ + public Queue(int size) { + maxSize = size; + queueArray = new int[size]; + front = 0; + rear = -1; + nItems = 0; + } + + /** + * Inserts an element at the rear of the queue + * + * @param x element to be added + * @return True if the element was added successfully + */ + public boolean insert(int x) { + if (isFull()) return false; + // If the back of the queue is the end of the array wrap around to the front + rear = (rear + 1) % maxSize; + queueArray[rear] = x; + nItems++; + return true; + } + + /** + * Remove an element from the front of the queue + * + * @return the new front of the queue + */ + public int remove() { + if (isEmpty()) { + return -1; } - - /** - * Constructor - * - * @param size Size of the new queue - */ - public Queue(int size) { - maxSize = size; - queueArray = new int[size]; - front = 0; - rear = -1; - nItems = 0; - } - - /** - * Inserts an element at the rear of the queue - * - * @param x element to be added - * @return True if the element was added successfully - */ - public boolean insert(int x) { - if (isFull()) - return false; - // If the back of the queue is the end of the array wrap around to the front - rear = (rear + 1) % maxSize; - queueArray[rear] = x; - nItems++; - return true; - } - - /** - * Remove an element from the front of the queue - * - * @return the new front of the queue - */ - public int remove() { - if (isEmpty()) { - return -1; - } - int temp = queueArray[front]; - front = (front + 1) % maxSize; - nItems--; - return temp; - } - - /** - * Checks what's at the front of the queue - * - * @return element at the front of the queue - */ - public int peekFront() { - return queueArray[front]; - } - - /** - * Checks what's at the rear of the queue - * - * @return element at the rear of the queue - */ - public int peekRear() { - return queueArray[rear]; - } - - /** - * Returns true if the queue is empty - * - * @return true if the queue is empty - */ - public boolean isEmpty() { - return nItems == 0; - } - - /** - * Returns true if the queue is full - * - * @return true if the queue is full - */ - public boolean isFull() { - return nItems == maxSize; - } - - /** - * Returns the number of elements in the queue - * - * @return number of elements in the queue - */ - public int getSize() { - return nItems; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("["); - for (int i = front; ; i = ++i % maxSize) { - sb.append(queueArray[i]).append(", "); - if (i == rear) { - break; - } - } - sb.replace(sb.length() - 2, sb.length(), "]"); - return sb.toString(); + int temp = queueArray[front]; + front = (front + 1) % maxSize; + nItems--; + return temp; + } + + /** + * Checks what's at the front of the queue + * + * @return element at the front of the queue + */ + public int peekFront() { + return queueArray[front]; + } + + /** + * Checks what's at the rear of the queue + * + * @return element at the rear of the queue + */ + public int peekRear() { + return queueArray[rear]; + } + + /** + * Returns true if the queue is empty + * + * @return true if the queue is empty + */ + public boolean isEmpty() { + return nItems == 0; + } + + /** + * Returns true if the queue is full + * + * @return true if the queue is full + */ + public boolean isFull() { + return nItems == maxSize; + } + + /** + * Returns the number of elements in the queue + * + * @return number of elements in the queue + */ + public int getSize() { + return nItems; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("["); + for (int i = front; ; i = ++i % maxSize) { + sb.append(queueArray[i]).append(", "); + if (i == rear) { + break; + } } + sb.replace(sb.length() - 2, sb.length(), "]"); + return sb.toString(); + } } /** @@ -152,29 +135,29 @@ public String toString() { * @author Unknown */ public class Queues { - /** - * Main method - * - * @param args Command line arguments - */ - public static void main(String[] args) { - Queue myQueue = new Queue(4); - myQueue.insert(10); - myQueue.insert(2); - myQueue.insert(5); - myQueue.insert(3); - // [10(front), 2, 5, 3(rear)] - - System.out.println(myQueue.isFull()); // Will print true - - myQueue.remove(); // Will make 2 the new front, making 10 no longer part of the queue - // [10, 2(front), 5, 3(rear)] - - myQueue.insert(7); // Insert 7 at the rear which will be index 0 because of wrap around - // [7(rear), 2(front), 5, 3] - - System.out.println(myQueue.peekFront()); // Will print 2 - System.out.println(myQueue.peekRear()); // Will print 7 - System.out.println(myQueue.toString()); // Will print [2, 5, 3, 7] - } + /** + * Main method + * + * @param args Command line arguments + */ + public static void main(String[] args) { + Queue myQueue = new Queue(4); + myQueue.insert(10); + myQueue.insert(2); + myQueue.insert(5); + myQueue.insert(3); + // [10(front), 2, 5, 3(rear)] + + System.out.println(myQueue.isFull()); // Will print true + + myQueue.remove(); // Will make 2 the new front, making 10 no longer part of the queue + // [10, 2(front), 5, 3(rear)] + + myQueue.insert(7); // Insert 7 at the rear which will be index 0 because of wrap around + // [7(rear), 2(front), 5, 3] + + System.out.println(myQueue.peekFront()); // Will print 2 + System.out.println(myQueue.peekRear()); // Will print 7 + System.out.println(myQueue.toString()); // Will print [2, 5, 3, 7] + } } diff --git a/DataStructures/Stacks/BalancedBrackets.java b/DataStructures/Stacks/BalancedBrackets.java index d9f6aa0a1f2f..6b8efce6d7a2 100644 --- a/DataStructures/Stacks/BalancedBrackets.java +++ b/DataStructures/Stacks/BalancedBrackets.java @@ -3,14 +3,12 @@ import java.util.Stack; /** - * The nested brackets problem is a problem that determines if a sequence of - * brackets are properly nested. A sequence of brackets s is considered properly - * nested if any of the following conditions are true: - s is empty - s has the - * form (U) or [U] or {U} where U is a properly nested string - s has the form - * VW where V and W are properly nested strings For example, the string - * "()()[()]" is properly nested but "[(()]" is not. The function called - * is_balanced takes as input a string S which is a sequence of brackets and - * returns true if S is nested and false otherwise. + * The nested brackets problem is a problem that determines if a sequence of brackets are properly + * nested. A sequence of brackets s is considered properly nested if any of the following conditions + * are true: - s is empty - s has the form (U) or [U] or {U} where U is a properly nested string - s + * has the form VW where V and W are properly nested strings For example, the string "()()[()]" is + * properly nested but "[(()]" is not. The function called is_balanced takes as input a string S + * which is a sequence of brackets and returns true if S is nested and false otherwise. * * @author akshay sharma * @author khalil2535 @@ -18,64 +16,63 @@ */ class BalancedBrackets { - /** - * Check if {@code leftBracket} and {@code rightBracket} is paired or not - * - * @param leftBracket left bracket - * @param rightBracket right bracket - * @return {@code true} if {@code leftBracket} and {@code rightBracket} is paired, - * otherwise {@code false} - */ - public static boolean isPaired(char leftBracket, char rightBracket) { - char[][] pairedBrackets = { - {'(', ')'}, - {'[', ']'}, - {'{', '}'}, - {'<', '>'} - }; - for (char[] pairedBracket : pairedBrackets) { - if (pairedBracket[0] == leftBracket && pairedBracket[1] == rightBracket) { - return true; - } - } - return false; + /** + * Check if {@code leftBracket} and {@code rightBracket} is paired or not + * + * @param leftBracket left bracket + * @param rightBracket right bracket + * @return {@code true} if {@code leftBracket} and {@code rightBracket} is paired, otherwise + * {@code false} + */ + public static boolean isPaired(char leftBracket, char rightBracket) { + char[][] pairedBrackets = { + {'(', ')'}, + {'[', ']'}, + {'{', '}'}, + {'<', '>'} + }; + for (char[] pairedBracket : pairedBrackets) { + if (pairedBracket[0] == leftBracket && pairedBracket[1] == rightBracket) { + return true; + } } + return false; + } - /** - * Check if {@code brackets} is balanced - * - * @param brackets the brackets - * @return {@code true} if {@code brackets} is balanced, otherwise {@code false} - */ - public static boolean isBalanced(String brackets) { - if (brackets == null) { - throw new IllegalArgumentException("brackets is null"); - } - Stack bracketsStack = new Stack<>(); - for (char bracket : brackets.toCharArray()) { - switch (bracket) { - case '(': - case '[': - case '{': - bracketsStack.push(bracket); - break; - case ')': - case ']': - case '}': - if (bracketsStack.isEmpty() || !isPaired(bracketsStack.pop(), bracket)) { - return false; - } - break; - default: /* other character is invalid */ - return false; - } - } - return bracketsStack.isEmpty(); + /** + * Check if {@code brackets} is balanced + * + * @param brackets the brackets + * @return {@code true} if {@code brackets} is balanced, otherwise {@code false} + */ + public static boolean isBalanced(String brackets) { + if (brackets == null) { + throw new IllegalArgumentException("brackets is null"); } - - - public static void main(String[] args) { - assert isBalanced("[()]{}{[()()]()}"); - assert !isBalanced("[(])"); + Stack bracketsStack = new Stack<>(); + for (char bracket : brackets.toCharArray()) { + switch (bracket) { + case '(': + case '[': + case '{': + bracketsStack.push(bracket); + break; + case ')': + case ']': + case '}': + if (bracketsStack.isEmpty() || !isPaired(bracketsStack.pop(), bracket)) { + return false; + } + break; + default: /* other character is invalid */ + return false; + } } + return bracketsStack.isEmpty(); + } + + public static void main(String[] args) { + assert isBalanced("[()]{}{[()()]()}"); + assert !isBalanced("[(])"); + } } diff --git a/DataStructures/Stacks/DecimalToAnyUsingStack.java b/DataStructures/Stacks/DecimalToAnyUsingStack.java index 6e129c32c6d9..d0fa7d5ba93b 100644 --- a/DataStructures/Stacks/DecimalToAnyUsingStack.java +++ b/DataStructures/Stacks/DecimalToAnyUsingStack.java @@ -3,42 +3,40 @@ import java.util.Stack; public class DecimalToAnyUsingStack { - public static void main(String[] args) { - assert convert(0, 2).equals("0"); - assert convert(30, 2).equals("11110"); - assert convert(30, 8).equals("36"); - assert convert(30, 10).equals("30"); - assert convert(30, 16).equals("1E"); - } + public static void main(String[] args) { + assert convert(0, 2).equals("0"); + assert convert(30, 2).equals("11110"); + assert convert(30, 8).equals("36"); + assert convert(30, 10).equals("30"); + assert convert(30, 16).equals("1E"); + } - /** - * Convert decimal number to another radix - * - * @param number the number to be converted - * @param radix the radix - * @return another radix - * @throws ArithmeticException if number or radius is invalid - */ - private static String convert(int number, int radix) { - if (radix < 2 || radix > 16) { - throw new ArithmeticException( - String.format("Invalid input -> number:%d,radius:%d", number, radix)); - } - char[] tables = { - '0', '1', '2', '3', '4', - '5', '6', '7', '8', '9', - 'A', 'B', 'C', 'D', 'E', 'F' - }; - Stack bits = new Stack<>(); - do { - bits.push(tables[number % radix]); - number = number / radix; - } while (number != 0); + /** + * Convert decimal number to another radix + * + * @param number the number to be converted + * @param radix the radix + * @return another radix + * @throws ArithmeticException if number or radius is invalid + */ + private static String convert(int number, int radix) { + if (radix < 2 || radix > 16) { + throw new ArithmeticException( + String.format("Invalid input -> number:%d,radius:%d", number, radix)); + } + char[] tables = { + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' + }; + Stack bits = new Stack<>(); + do { + bits.push(tables[number % radix]); + number = number / radix; + } while (number != 0); - StringBuilder result = new StringBuilder(); - while (!bits.isEmpty()) { - result.append(bits.pop()); - } - return result.toString(); + StringBuilder result = new StringBuilder(); + while (!bits.isEmpty()) { + result.append(bits.pop()); } + return result.toString(); + } } diff --git a/DataStructures/Stacks/NodeStack.java b/DataStructures/Stacks/NodeStack.java index 0f1d58686b0d..623068dcb1e3 100644 --- a/DataStructures/Stacks/NodeStack.java +++ b/DataStructures/Stacks/NodeStack.java @@ -1,184 +1,171 @@ package DataStructures.Stacks; /** -* Implementation of a stack using nodes. -* Unlimited size, no arraylist. -* -* @author Kyler Smith, 2017 -*/ - - + * Implementation of a stack using nodes. Unlimited size, no arraylist. + * + * @author Kyler Smith, 2017 + */ public class NodeStack { - /** - * Entry point for the program. - */ - public static void main(String[] args) { - NodeStack Stack = new NodeStack(); - - Stack.push(3); - Stack.push(4); - Stack.push(5); - System.out.println("Testing :"); - Stack.print(); // prints : 5 4 3 - - Integer x = Stack.pop(); // x = 5 - Stack.push(1); - Stack.push(8); - Integer y = Stack.peek(); // y = 8 - System.out.println("Testing :"); - Stack.print(); // prints : 8 1 4 3 - - System.out.println("Testing :"); - System.out.println("x : " + x); - System.out.println("y : " + y); - } - - /** - * Information each node should contain. - * @value data : information of the value in the node - * @value head : the head of the stack - * @value next : the next value from this node - * @value previous : the last value from this node - * @value size : size of the stack - */ - private Item data; - private static NodeStack head; - private NodeStack next; - private NodeStack previous; - private static int size = 0; - - - /** - * Constructors for the NodeStack. - */ - public NodeStack() { - } - - private NodeStack(Item item) { - this.data = item; - } - - /** - * Put a value onto the stack. - * - * @param item : value to be put on the stack. - */ - public void push(Item item) { - - NodeStack newNs = new NodeStack(item); - - if(this.isEmpty()) { - NodeStack.setHead(new NodeStack<>(item)); - newNs.setNext(null); - newNs.setPrevious(null); - } else { - newNs.setPrevious(NodeStack.head); - NodeStack.head.setNext(newNs); - NodeStack.head.setHead(newNs); - } - - NodeStack.setSize(NodeStack.getSize() + 1); - } - - /** - * Value to be taken off the stack. - * - * @return item : value that is returned. - */ - public Item pop() { - - Item item = (Item) NodeStack.head.getData(); - - NodeStack.head.setHead(NodeStack.head.getPrevious()); - NodeStack.head.setNext(null); - - NodeStack.setSize(NodeStack.getSize() - 1); - - return item; - } - - /** - * Value that is next to be taken off the stack. - * - * @return item : the next value that would be popped off the stack. - */ - public Item peek() { - return (Item) NodeStack.head.getData(); - } - - /** - * If the stack is empty or there is a value in. - * - * @return boolean : whether or not the stack has anything in it. - */ - public boolean isEmpty() { - return NodeStack.getSize() == 0; + /** Entry point for the program. */ + public static void main(String[] args) { + NodeStack Stack = new NodeStack(); + + Stack.push(3); + Stack.push(4); + Stack.push(5); + System.out.println("Testing :"); + Stack.print(); // prints : 5 4 3 + + Integer x = Stack.pop(); // x = 5 + Stack.push(1); + Stack.push(8); + Integer y = Stack.peek(); // y = 8 + System.out.println("Testing :"); + Stack.print(); // prints : 8 1 4 3 + + System.out.println("Testing :"); + System.out.println("x : " + x); + System.out.println("y : " + y); + } + + /** + * Information each node should contain. + * + * @value data : information of the value in the node + * @value head : the head of the stack + * @value next : the next value from this node + * @value previous : the last value from this node + * @value size : size of the stack + */ + private Item data; + + private static NodeStack head; + private NodeStack next; + private NodeStack previous; + private static int size = 0; + + /** Constructors for the NodeStack. */ + public NodeStack() {} + + private NodeStack(Item item) { + this.data = item; + } + + /** + * Put a value onto the stack. + * + * @param item : value to be put on the stack. + */ + public void push(Item item) { + + NodeStack newNs = new NodeStack(item); + + if (this.isEmpty()) { + NodeStack.setHead(new NodeStack<>(item)); + newNs.setNext(null); + newNs.setPrevious(null); + } else { + newNs.setPrevious(NodeStack.head); + NodeStack.head.setNext(newNs); + NodeStack.head.setHead(newNs); } - /** - * Returns the size of the stack. - * - * @return int : number of values in the stack. - */ - public int size() { - return NodeStack.getSize(); + NodeStack.setSize(NodeStack.getSize() + 1); + } + + /** + * Value to be taken off the stack. + * + * @return item : value that is returned. + */ + public Item pop() { + + Item item = (Item) NodeStack.head.getData(); + + NodeStack.head.setHead(NodeStack.head.getPrevious()); + NodeStack.head.setNext(null); + + NodeStack.setSize(NodeStack.getSize() - 1); + + return item; + } + + /** + * Value that is next to be taken off the stack. + * + * @return item : the next value that would be popped off the stack. + */ + public Item peek() { + return (Item) NodeStack.head.getData(); + } + + /** + * If the stack is empty or there is a value in. + * + * @return boolean : whether or not the stack has anything in it. + */ + public boolean isEmpty() { + return NodeStack.getSize() == 0; + } + + /** + * Returns the size of the stack. + * + * @return int : number of values in the stack. + */ + public int size() { + return NodeStack.getSize(); + } + + /** + * Print the contents of the stack in the following format. + * + *

x <- head (next out) y z <- tail (first in) . . . + */ + public void print() { + for (NodeStack n = NodeStack.head; n != null; n = n.previous) { + System.out.println(n.getData().toString()); } + } - /** - * Print the contents of the stack in the following format. - * - * x <- head (next out) - * y - * z <- tail (first in) - * . - * . - * . - * - */ - public void print() { - for(NodeStack n = NodeStack.head; n != null; n = n.previous) { - System.out.println(n.getData().toString()); - } - } + /** Getters and setters (private) */ + private NodeStack getHead() { + return NodeStack.head; + } - /** Getters and setters (private) */ - private NodeStack getHead() { - return NodeStack.head; - } - - private static void setHead(NodeStack ns) { - NodeStack.head = ns; - } + private static void setHead(NodeStack ns) { + NodeStack.head = ns; + } - private NodeStack getNext() { - return next; - } + private NodeStack getNext() { + return next; + } - private void setNext(NodeStack next) { - this.next = next; - } + private void setNext(NodeStack next) { + this.next = next; + } - private NodeStack getPrevious() { - return previous; - } + private NodeStack getPrevious() { + return previous; + } - private void setPrevious(NodeStack previous) { - this.previous = previous; - } + private void setPrevious(NodeStack previous) { + this.previous = previous; + } - private static int getSize() { - return size; - } + private static int getSize() { + return size; + } - private static void setSize(int size) { - NodeStack.size = size; - } + private static void setSize(int size) { + NodeStack.size = size; + } - private Item getData() { - return this.data; - } + private Item getData() { + return this.data; + } - private void setData(Item item) { - this.data = item; - } + private void setData(Item item) { + this.data = item; + } } diff --git a/DataStructures/Stacks/StackArray.java b/DataStructures/Stacks/StackArray.java index eaad1d401b6b..77f65e493c6e 100644 --- a/DataStructures/Stacks/StackArray.java +++ b/DataStructures/Stacks/StackArray.java @@ -2,172 +2,157 @@ /** * This class implements a Stack using a regular array. - *

- * A stack is exactly what it sounds like. An element gets added to the top of - * the stack and only the element on the top may be removed. This is an example - * of an array implementation of a Stack. So an element can only be added/removed - * from the end of the array. In theory stack have no fixed size, but with an - * array implementation it does. + * + *

A stack is exactly what it sounds like. An element gets added to the top of the stack and only + * the element on the top may be removed. This is an example of an array implementation of a Stack. + * So an element can only be added/removed from the end of the array. In theory stack have no fixed + * size, but with an array implementation it does. */ public class StackArray { - /** - * Driver Code - */ - public static void main(String[] args) { - // Declare a stack of maximum size 4 - StackArray myStackArray = new StackArray(4); - - assert myStackArray.isEmpty(); - assert !myStackArray.isFull(); - - // Populate the stack - myStackArray.push(5); - myStackArray.push(8); - myStackArray.push(2); - myStackArray.push(9); - - assert !myStackArray.isEmpty(); - assert myStackArray.isFull(); - assert myStackArray.peek() == 9; - assert myStackArray.pop() == 9; - assert myStackArray.peek() == 2; - assert myStackArray.size() == 3; + /** Driver Code */ + public static void main(String[] args) { + // Declare a stack of maximum size 4 + StackArray myStackArray = new StackArray(4); + + assert myStackArray.isEmpty(); + assert !myStackArray.isFull(); + + // Populate the stack + myStackArray.push(5); + myStackArray.push(8); + myStackArray.push(2); + myStackArray.push(9); + + assert !myStackArray.isEmpty(); + assert myStackArray.isFull(); + assert myStackArray.peek() == 9; + assert myStackArray.pop() == 9; + assert myStackArray.peek() == 2; + assert myStackArray.size() == 3; + } + + /** Default initial capacity. */ + private static final int DEFAULT_CAPACITY = 10; + + /** The max size of the Stack */ + private int maxSize; + + /** The array representation of the Stack */ + private int[] stackArray; + + /** The top of the stack */ + private int top; + + /** init Stack with DEFAULT_CAPACITY */ + public StackArray() { + this(DEFAULT_CAPACITY); + } + + /** + * Constructor + * + * @param size Size of the Stack + */ + public StackArray(int size) { + maxSize = size; + stackArray = new int[maxSize]; + top = -1; + } + + /** + * Adds an element to the top of the stack + * + * @param value The element added + */ + public void push(int value) { + if (!isFull()) { // Checks for a full stack + top++; + stackArray[top] = value; + } else { + resize(maxSize * 2); + push(value); // don't forget push after resizing } - - /** - * Default initial capacity. - */ - private static final int DEFAULT_CAPACITY = 10; - - /** - * The max size of the Stack - */ - private int maxSize; - - /** - * The array representation of the Stack - */ - private int[] stackArray; - - /** - * The top of the stack - */ - private int top; - - /** - * init Stack with DEFAULT_CAPACITY - */ - public StackArray() { - this(DEFAULT_CAPACITY); - } - - /** - * Constructor - * - * @param size Size of the Stack - */ - public StackArray(int size) { - maxSize = size; - stackArray = new int[maxSize]; - top = -1; - } - - /** - * Adds an element to the top of the stack - * - * @param value The element added - */ - public void push(int value) { - if (!isFull()) { // Checks for a full stack - top++; - stackArray[top] = value; - } else { - resize(maxSize * 2); - push(value); // don't forget push after resizing - } - } - - /** - * Removes the top element of the stack and returns the value you've removed - * - * @return value popped off the Stack - */ - public int pop() { - if (!isEmpty()) { // Checks for an empty stack - return stackArray[top--]; - } - - if (top < maxSize / 4) { - resize(maxSize / 2); - return pop();// don't forget pop after resizing - } else { - System.out.println("The stack is already empty"); - return -1; - } + } + + /** + * Removes the top element of the stack and returns the value you've removed + * + * @return value popped off the Stack + */ + public int pop() { + if (!isEmpty()) { // Checks for an empty stack + return stackArray[top--]; } - /** - * Returns the element at the top of the stack - * - * @return element at the top of the stack - */ - public int peek() { - if (!isEmpty()) { // Checks for an empty stack - return stackArray[top]; - } else { - System.out.println("The stack is empty, cant peek"); - return -1; - } + if (top < maxSize / 4) { + resize(maxSize / 2); + return pop(); // don't forget pop after resizing + } else { + System.out.println("The stack is already empty"); + return -1; } - - private void resize(int newSize) { - int[] transferArray = new int[newSize]; - - for (int i = 0; i < stackArray.length; i++) { - transferArray[i] = stackArray[i]; - } - // This reference change might be nice in here - stackArray = transferArray; - maxSize = newSize; - } - - /** - * Returns true if the stack is empty - * - * @return true if the stack is empty - */ - public boolean isEmpty() { - return (top == -1); + } + + /** + * Returns the element at the top of the stack + * + * @return element at the top of the stack + */ + public int peek() { + if (!isEmpty()) { // Checks for an empty stack + return stackArray[top]; + } else { + System.out.println("The stack is empty, cant peek"); + return -1; } + } - /** - * Returns true if the stack is full - * - * @return true if the stack is full - */ - public boolean isFull() { - return (top + 1 == maxSize); - } - - /** - * Deletes everything in the Stack - *

- * Doesn't delete elements in the array - * but if you call push method after calling - * makeEmpty it will overwrite previous - * values - */ - public void makeEmpty() { // Doesn't delete elements in the array but if you call - top = -1; // push method after calling makeEmpty it will overwrite previous values - } + private void resize(int newSize) { + int[] transferArray = new int[newSize]; - /** - * Return size of stack - * - * @return size of stack - */ - public int size() { - return top + 1; + for (int i = 0; i < stackArray.length; i++) { + transferArray[i] = stackArray[i]; } + // This reference change might be nice in here + stackArray = transferArray; + maxSize = newSize; + } + + /** + * Returns true if the stack is empty + * + * @return true if the stack is empty + */ + public boolean isEmpty() { + return (top == -1); + } + + /** + * Returns true if the stack is full + * + * @return true if the stack is full + */ + public boolean isFull() { + return (top + 1 == maxSize); + } + + /** + * Deletes everything in the Stack + * + *

Doesn't delete elements in the array but if you call push method after calling makeEmpty it + * will overwrite previous values + */ + public void makeEmpty() { // Doesn't delete elements in the array but if you call + top = -1; // push method after calling makeEmpty it will overwrite previous values + } + + /** + * Return size of stack + * + * @return size of stack + */ + public int size() { + return top + 1; + } } diff --git a/DataStructures/Stacks/StackArrayList.java b/DataStructures/Stacks/StackArrayList.java index 5f7168c63bba..c9b31d625dd9 100644 --- a/DataStructures/Stacks/StackArrayList.java +++ b/DataStructures/Stacks/StackArrayList.java @@ -5,109 +5,101 @@ /** * This class implements a Stack using an ArrayList. - *

- * A stack is exactly what it sounds like. An element gets added to the top of - * the stack and only the element on the top may be removed. - *

- * This is an ArrayList Implementation of a stack, where size is not - * a problem we can extend the stack as much as we want. + * + *

A stack is exactly what it sounds like. An element gets added to the top of the stack and only + * the element on the top may be removed. + * + *

This is an ArrayList Implementation of a stack, where size is not a problem we can extend the + * stack as much as we want. */ public class StackArrayList { - /** - * Driver Code - */ - public static void main(String[] args) { - StackArrayList stack = new StackArrayList(); - assert stack.isEmpty(); + /** Driver Code */ + public static void main(String[] args) { + StackArrayList stack = new StackArrayList(); + assert stack.isEmpty(); - for (int i = 1; i <= 5; ++i) { - stack.push(i); - assert stack.size() == i; - } - - assert stack.size() == 5; - assert stack.peek() == 5 && stack.pop() == 5 && stack.peek() == 4; - - /* pop elements at the top of this stack one by one */ - while (!stack.isEmpty()) { - stack.pop(); - } - assert stack.isEmpty(); - - try { - stack.pop(); - assert false; /* this should not happen */ - } catch (EmptyStackException e) { - assert true; /* this should happen */ - } - - } - - /** - * ArrayList representation of the stack - */ - private ArrayList stack; - - /** - * Constructor - */ - public StackArrayList() { - stack = new ArrayList<>(); + for (int i = 1; i <= 5; ++i) { + stack.push(i); + assert stack.size() == i; } - /** - * Adds value to the end of list which - * is the top for stack - * - * @param value value to be added - */ - public void push(int value) { - stack.add(value); - } + assert stack.size() == 5; + assert stack.peek() == 5 && stack.pop() == 5 && stack.peek() == 4; - /** - * Removes the element at the top of this stack and returns - * - * @return Element popped - * @throws EmptyStackException if the stack is empty. - */ - public int pop() { - if (isEmpty()) { - throw new EmptyStackException(); - } - - /* remove the element on the top of the stack */ - return stack.remove(stack.size() - 1); + /* pop elements at the top of this stack one by one */ + while (!stack.isEmpty()) { + stack.pop(); } + assert stack.isEmpty(); - /** - * Test if the stack is empty. - * - * @return {@code true} if this stack is empty, {@code false} otherwise. - */ - public boolean isEmpty() { - return stack.isEmpty(); + try { + stack.pop(); + assert false; /* this should not happen */ + } catch (EmptyStackException e) { + assert true; /* this should happen */ } - - /** - * Return the element at the top of this stack without removing it from the stack. - * - * @return the element at the top of this stack. - */ - public int peek() { - if (isEmpty()) { - throw new EmptyStackException(); - } - return stack.get(stack.size() - 1); + } + + /** ArrayList representation of the stack */ + private ArrayList stack; + + /** Constructor */ + public StackArrayList() { + stack = new ArrayList<>(); + } + + /** + * Adds value to the end of list which is the top for stack + * + * @param value value to be added + */ + public void push(int value) { + stack.add(value); + } + + /** + * Removes the element at the top of this stack and returns + * + * @return Element popped + * @throws EmptyStackException if the stack is empty. + */ + public int pop() { + if (isEmpty()) { + throw new EmptyStackException(); } - /** - * Return size of this stack. - * - * @return size of this stack. - */ - public int size() { - return stack.size(); + /* remove the element on the top of the stack */ + return stack.remove(stack.size() - 1); + } + + /** + * Test if the stack is empty. + * + * @return {@code true} if this stack is empty, {@code false} otherwise. + */ + public boolean isEmpty() { + return stack.isEmpty(); + } + + /** + * Return the element at the top of this stack without removing it from the stack. + * + * @return the element at the top of this stack. + */ + public int peek() { + if (isEmpty()) { + throw new EmptyStackException(); } -} \ No newline at end of file + return stack.get(stack.size() - 1); + } + + /** + * Return size of this stack. + * + * @return size of this stack. + */ + public int size() { + return stack.size(); + } +} diff --git a/DataStructures/Stacks/StackOfLinkedList.java b/DataStructures/Stacks/StackOfLinkedList.java index 60d8a1b0f7a0..39e1f5275161 100644 --- a/DataStructures/Stacks/StackOfLinkedList.java +++ b/DataStructures/Stacks/StackOfLinkedList.java @@ -2,143 +2,134 @@ import java.util.NoSuchElementException; -/** - * @author Varun Upadhyay (https://github.com/varunu28) - */ +/** @author Varun Upadhyay (https://github.com/varunu28) */ // An implementation of a Stack using a Linked List class StackOfLinkedList { - public static void main(String[] args) { + public static void main(String[] args) { - LinkedListStack stack = new LinkedListStack(); - stack.push(1); - stack.push(2); - stack.push(3); - stack.push(4); - stack.push(5); + LinkedListStack stack = new LinkedListStack(); + stack.push(1); + stack.push(2); + stack.push(3); + stack.push(4); + stack.push(5); - System.out.println(stack); + System.out.println(stack); - System.out.println("Size of stack currently is: " + stack.getSize()); + System.out.println("Size of stack currently is: " + stack.getSize()); - assert stack.pop() == 5; - assert stack.pop() == 4; + assert stack.pop() == 5; + assert stack.pop() == 4; - System.out.println("Top element of stack currently is: " + stack.peek()); - } + System.out.println("Top element of stack currently is: " + stack.peek()); + } } // A node class class Node { - public int data; - public Node next; + public int data; + public Node next; - public Node(int data) { - this.data = data; - this.next = null; - } + 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 - **/ - + * + *

Contains all the stack methods : push, pop, printStack, isEmpty + */ class LinkedListStack { - /** - * Top of stack - */ - Node head; - - /** - * Size of stack - */ - private int size; - - /** - * Init properties - */ - public LinkedListStack() { - head = null; - size = 0; - } - - /** - * Add element at top - * - * @param x to be added - * @return true if add successfully - */ - public boolean push(int x) { - Node newNode = new Node(x); - newNode.next = head; - head = newNode; - size++; - return true; + /** Top of stack */ + Node head; + + /** Size of stack */ + private int size; + + /** Init properties */ + public LinkedListStack() { + head = null; + size = 0; + } + + /** + * Add element at top + * + * @param x to be added + * @return true if add successfully + */ + public boolean push(int x) { + Node newNode = new Node(x); + newNode.next = head; + head = newNode; + size++; + return true; + } + + /** + * Pop element at top of stack + * + * @return element at top of stack + * @throws NoSuchElementException if stack is empty + */ + public int pop() { + if (size == 0) { + throw new NoSuchElementException("Empty stack. Nothing to pop"); } - - /** - * Pop element at top of stack - * - * @return element at top of stack - * @throws NoSuchElementException if stack is empty - */ - public int pop() { - if (size == 0) { - throw new NoSuchElementException("Empty stack. Nothing to pop"); - } - Node destroy = head; - head = head.next; - int retValue = destroy.data; - destroy = null; // clear to let GC do it's work - size--; - return retValue; - } - - /** - * Peek element at top of stack - * - * @return element at top of stack - * @throws NoSuchElementException if stack is empty - */ - public int peek() { - if (size == 0) { - throw new NoSuchElementException("Empty stack. Nothing to pop"); - } - return head.data; - } - - @Override - public String toString() { - Node cur = head; - StringBuilder builder = new StringBuilder(); - while (cur != null) { - builder.append(cur.data).append("->"); - cur = cur.next; - } - return builder.replace(builder.length() - 2, builder.length(), "").toString(); - } - - /** - * Check if stack is empty - * - * @return true if stack is empty, otherwise false - */ - public boolean isEmpty() { - return size == 0; + Node destroy = head; + head = head.next; + int retValue = destroy.data; + destroy = null; // clear to let GC do it's work + size--; + return retValue; + } + + /** + * Peek element at top of stack + * + * @return element at top of stack + * @throws NoSuchElementException if stack is empty + */ + public int peek() { + if (size == 0) { + throw new NoSuchElementException("Empty stack. Nothing to pop"); } - - /** - * Return size of stack - * - * @return size of stack - */ - public int getSize() { - return size; + return head.data; + } + + @Override + public String toString() { + Node cur = head; + StringBuilder builder = new StringBuilder(); + while (cur != null) { + builder.append(cur.data).append("->"); + cur = cur.next; } + return builder.replace(builder.length() - 2, builder.length(), "").toString(); + } + + /** + * Check if stack is empty + * + * @return true if stack is empty, otherwise false + */ + public boolean isEmpty() { + return size == 0; + } + + /** + * Return size of stack + * + * @return size of stack + */ + public int getSize() { + return size; + } } diff --git a/DataStructures/Trees/AVLTree.java b/DataStructures/Trees/AVLTree.java index fb9e2cb34df9..52121a56a5ca 100644 --- a/DataStructures/Trees/AVLTree.java +++ b/DataStructures/Trees/AVLTree.java @@ -2,237 +2,223 @@ public class AVLTree { - private Node root; - - private class Node { - private int key; - private int balance; - private int height; - private Node left, right, parent; - - Node(int k, Node p) { - key = k; - parent = p; + private Node root; + + private class Node { + private int key; + private int balance; + private int height; + private Node left, right, parent; + + Node(int k, Node p) { + key = k; + parent = p; + } + } + + public boolean insert(int key) { + if (root == null) root = new Node(key, null); + else { + Node n = root; + Node parent; + while (true) { + if (n.key == key) return false; + + parent = n; + + boolean goLeft = n.key > key; + n = goLeft ? n.left : n.right; + + if (n == null) { + if (goLeft) { + parent.left = new Node(key, parent); + } else { + parent.right = new Node(key, parent); + } + rebalance(parent); + break; } + } } + return true; + } - public boolean insert(int key) { - if (root == null) - root = new Node(key, null); - else { - Node n = root; - Node parent; - while (true) { - if (n.key == key) - return false; - - parent = n; - - boolean goLeft = n.key > key; - n = goLeft ? n.left : n.right; - - if (n == null) { - if (goLeft) { - parent.left = new Node(key, parent); - } else { - parent.right = new Node(key, parent); - } - rebalance(parent); - break; - } - } - } - return true; + private void delete(Node node) { + if (node.left == null && node.right == null) { + if (node.parent == null) root = null; + else { + Node parent = node.parent; + if (parent.left == node) { + parent.left = null; + } else parent.right = null; + rebalance(parent); + } + return; + } + if (node.left != null) { + Node child = node.left; + while (child.right != null) child = child.right; + node.key = child.key; + delete(child); + } else { + Node child = node.right; + while (child.left != null) child = child.left; + node.key = child.key; + delete(child); } + } - private void delete(Node node) { - if (node.left == null && node.right == null) { - if (node.parent == null) root = null; - else { - Node parent = node.parent; - if (parent.left == node) { - parent.left = null; - } else parent.right = null; - rebalance(parent); - } - return; - } - if (node.left != null) { - Node child = node.left; - while (child.right != null) child = child.right; - node.key = child.key; - delete(child); - } else { - Node child = node.right; - while (child.left != null) child = child.left; - node.key = child.key; - delete(child); - } + public void delete(int delKey) { + if (root == null) return; + Node node = root; + Node child = root; + + while (child != null) { + node = child; + child = delKey >= node.key ? node.right : node.left; + if (delKey == node.key) { + delete(node); + return; + } } + } - public void delete(int delKey) { - if (root == null) - return; - Node node = root; - Node child = root; - - while (child != null) { - node = child; - child = delKey >= node.key ? node.right : node.left; - if (delKey == node.key) { - delete(node); - return; - } - } + private void rebalance(Node n) { + setBalance(n); + + if (n.balance == -2) { + if (height(n.left.left) >= height(n.left.right)) n = rotateRight(n); + else n = rotateLeftThenRight(n); + + } else if (n.balance == 2) { + if (height(n.right.right) >= height(n.right.left)) n = rotateLeft(n); + else n = rotateRightThenLeft(n); } - private void rebalance(Node n) { - setBalance(n); + if (n.parent != null) { + rebalance(n.parent); + } else { + root = n; + } + } - if (n.balance == -2) { - if (height(n.left.left) >= height(n.left.right)) - n = rotateRight(n); - else - n = rotateLeftThenRight(n); + private Node rotateLeft(Node a) { - } else if (n.balance == 2) { - if (height(n.right.right) >= height(n.right.left)) - n = rotateLeft(n); - else - n = rotateRightThenLeft(n); - } + Node b = a.right; + b.parent = a.parent; - if (n.parent != null) { - rebalance(n.parent); - } else { - root = n; - } + a.right = b.left; + + if (a.right != null) a.right.parent = a; + + b.left = a; + a.parent = b; + + if (b.parent != null) { + if (b.parent.right == a) { + b.parent.right = b; + } else { + b.parent.left = b; + } } - private Node rotateLeft(Node a) { + setBalance(a, b); - Node b = a.right; - b.parent = a.parent; + return b; + } - a.right = b.left; + private Node rotateRight(Node a) { - if (a.right != null) - a.right.parent = a; + Node b = a.left; + b.parent = a.parent; - b.left = a; - a.parent = b; + a.left = b.right; - if (b.parent != null) { - if (b.parent.right == a) { - b.parent.right = b; - } else { - b.parent.left = b; - } - } + if (a.left != null) a.left.parent = a; - setBalance(a, b); + b.right = a; + a.parent = b; - return b; + if (b.parent != null) { + if (b.parent.right == a) { + b.parent.right = b; + } else { + b.parent.left = b; + } } - private Node rotateRight(Node a) { + setBalance(a, b); - Node b = a.left; - b.parent = a.parent; + return b; + } - a.left = b.right; + private Node rotateLeftThenRight(Node n) { + n.left = rotateLeft(n.left); + return rotateRight(n); + } - if (a.left != null) - a.left.parent = a; + private Node rotateRightThenLeft(Node n) { + n.right = rotateRight(n.right); + return rotateLeft(n); + } - b.right = a; - a.parent = b; + private int height(Node n) { + if (n == null) return -1; + return n.height; + } - if (b.parent != null) { - if (b.parent.right == a) { - b.parent.right = b; - } else { - b.parent.left = b; - } - } + private void setBalance(Node... nodes) { + for (Node n : nodes) { + reheight(n); + n.balance = height(n.right) - height(n.left); + } + } - setBalance(a, b); + public void printBalance() { + printBalance(root); + } - return b; + private void printBalance(Node n) { + if (n != null) { + printBalance(n.left); + System.out.printf("%s ", n.balance); + printBalance(n.right); } + } - private Node rotateLeftThenRight(Node n) { - n.left = rotateLeft(n.left); - return rotateRight(n); + private void reheight(Node node) { + if (node != null) { + node.height = 1 + Math.max(height(node.left), height(node.right)); } + } - private Node rotateRightThenLeft(Node n) { - n.right = rotateRight(n.right); - return rotateLeft(n); - } + public boolean search(int key) { + Node result = searchHelper(this.root, key); + if (result != null) return true; - private int height(Node n) { - if (n == null) - return -1; - return n.height; - } + return false; + } - private void setBalance(Node... nodes) { - for (Node n : nodes) { - reheight(n); - n.balance = height(n.right) - height(n.left); - } - } + private Node searchHelper(Node root, int key) { + // root is null or key is present at root + if (root == null || root.key == key) return root; - public void printBalance() { - printBalance(root); - } + // key is greater than root's key + if (root.key > key) + return searchHelper(root.left, key); // call the function on the node's left child - private void printBalance(Node n) { - if (n != null) { - printBalance(n.left); - System.out.printf("%s ", n.balance); - printBalance(n.right); - } - } + // key is less than root's key then + // call the function on the node's right child as it is greater + return searchHelper(root.right, key); + } - private void reheight(Node node) { - if (node != null) { - node.height = 1 + Math.max(height(node.left), height(node.right)); - } - } + public static void main(String[] args) { + AVLTree tree = new AVLTree(); - public boolean search(int key) { - Node result = searchHelper(this.root,key); - if(result != null) - return true ; - - return false ; - } - - private Node searchHelper(Node root, int key) - { - //root is null or key is present at root - if (root==null || root.key==key) - return root; - - // key is greater than root's key - if (root.key > key) - return searchHelper(root.left, key); // call the function on the node's left child - - // key is less than root's key then - //call the function on the node's right child as it is greater - return searchHelper(root.right, key); - } - - public static void main(String[] args) { - AVLTree tree = new AVLTree(); - - System.out.println("Inserting values 1 to 10"); - for (int i = 1; i < 10; i++) - tree.insert(i); - - System.out.print("Printing balance: "); - tree.printBalance(); - } + System.out.println("Inserting values 1 to 10"); + for (int i = 1; i < 10; i++) tree.insert(i); + + System.out.print("Printing balance: "); + tree.printBalance(); + } } diff --git a/DataStructures/Trees/BinaryTree.java b/DataStructures/Trees/BinaryTree.java index 6ef4b5ada325..9afbf6f0271b 100644 --- a/DataStructures/Trees/BinaryTree.java +++ b/DataStructures/Trees/BinaryTree.java @@ -1,282 +1,259 @@ package DataStructures.Trees; /** - * This entire class is used to build a Binary Tree data structure. - * There is the Node Class and the Tree Class, both explained below. + * This entire class is used to build a Binary Tree data structure. There is the Node Class and the + * Tree Class, both explained below. */ - /** - * A binary tree is a data structure in which an element - * has two successors(children). The left child is usually - * smaller than the parent, and the right child is usually - * bigger. + * A binary tree is a data structure in which an element has two successors(children). The left + * child is usually smaller than the parent, and the right child is usually bigger. * * @author Unknown - * */ public class BinaryTree { + /** + * This class implements the nodes that will go on the Binary Tree. They consist of the data in + * them, the node to the left, the node to the right, and the parent from which they came from. + * + * @author Unknown + */ + class Node { + /** Data for the node */ + public int data; + /** The Node to the left of this one */ + public Node left; + /** The Node to the right of this one */ + public Node right; + /** The parent of this node */ + public Node parent; + /** - * This class implements the nodes that will go on the Binary Tree. - * They consist of the data in them, the node to the left, the node - * to the right, and the parent from which they came from. - * - * @author Unknown + * Constructor of Node * + * @param value Value to put in the node */ - class Node { - /** Data for the node */ - public int data; - /** The Node to the left of this one */ - public Node left; - /** The Node to the right of this one */ - public Node right; - /** The parent of this node */ - public Node parent; - - /** - * Constructor of Node - * - * @param value Value to put in the node - */ - public Node(int value) { - data = value; - left = null; - right = null; - parent = null; - } + public Node(int value) { + data = value; + left = null; + right = null; + parent = null; } + } + /** The root of the Binary Tree */ + private Node root; - /** The root of the Binary Tree */ - private Node root; + /** Constructor */ + public BinaryTree() { + root = null; + } - /** - * Constructor - */ - public BinaryTree() { - root = null; - } - - /** - * Method to find a Node with a certain value - * - * @param key Value being looked for - * @return The node if it finds it, otherwise returns the parent - */ - public Node find(int key) { - Node current = root; - while (current != null) { - if (key < current.data) { - if (current.left == null) - return current; //The key isn't exist, returns the parent - current = current.left; - } else if (key > current.data) { - if (current.right == null) - return current; - current = current.right; - } else { // If you find the value return it - return current; - } - } - return null; + /** + * Method to find a Node with a certain value + * + * @param key Value being looked for + * @return The node if it finds it, otherwise returns the parent + */ + public Node find(int key) { + Node current = root; + while (current != null) { + if (key < current.data) { + if (current.left == null) return current; // The key isn't exist, returns the parent + current = current.left; + } else if (key > current.data) { + if (current.right == null) return current; + current = current.right; + } else { // If you find the value return it + return current; + } } + return null; + } - /** - * Inserts certain value into the Binary Tree - * - * @param value Value to be inserted - */ - public void put(int value) { - Node newNode = new Node(value); - if (root == null) - root = newNode; - else { - //This will return the soon to be parent of the value you're inserting - Node parent = find(value); + /** + * Inserts certain value into the Binary Tree + * + * @param value Value to be inserted + */ + public void put(int value) { + Node newNode = new Node(value); + if (root == null) root = newNode; + else { + // This will return the soon to be parent of the value you're inserting + Node parent = find(value); - //This if/else assigns the new node to be either the left or right child of the parent - if (value < parent.data) { - parent.left = newNode; - parent.left.parent = parent; - return; - } else { - parent.right = newNode; - parent.right.parent = parent; - return; - } - } + // This if/else assigns the new node to be either the left or right child of the parent + if (value < parent.data) { + parent.left = newNode; + parent.left.parent = parent; + return; + } else { + parent.right = newNode; + parent.right.parent = parent; + return; + } } + } - /** - * Deletes a given value from the Binary Tree - * - * @param value Value to be deleted - * @return If the value was deleted - */ - public boolean remove(int value) { - //temp is the node to be deleted - Node temp = find(value); + /** + * Deletes a given value from the Binary Tree + * + * @param value Value to be deleted + * @return If the value was deleted + */ + public boolean remove(int value) { + // temp is the node to be deleted + Node temp = find(value); - //If the value doesn't exist - if (temp.data != value) - return false; + // If the value doesn't exist + if (temp.data != value) return false; - //No children - if (temp.right == null && temp.left == null) { - if (temp == root) - root = null; + // No children + if (temp.right == null && temp.left == null) { + if (temp == root) root = null; - //This if/else assigns the new node to be either the left or right child of the parent - else if (temp.parent.data < temp.data) - temp.parent.right = null; - else - temp.parent.left = null; - return true; - } + // This if/else assigns the new node to be either the left or right child of the parent + else if (temp.parent.data < temp.data) temp.parent.right = null; + else temp.parent.left = null; + return true; + } - //Two children - else if (temp.left != null && temp.right != null) { - Node successor = findSuccessor(temp); + // Two children + else if (temp.left != null && temp.right != null) { + Node successor = findSuccessor(temp); - //The left tree of temp is made the left tree of the successor - successor.left = temp.left; - successor.left.parent = successor; + // The left tree of temp is made the left tree of the successor + successor.left = temp.left; + successor.left.parent = successor; - //If the successor has a right child, the child's grandparent is it's new parent - if(successor.parent!=temp){ - if(successor.right!=null){ - successor.right.parent = successor.parent; - successor.parent.left = successor.right; - successor.right = temp.right; - successor.right.parent = successor; - }else{ - successor.parent.left=null; - successor.right=temp.right; - successor.right.parent=successor; - } - } + // If the successor has a right child, the child's grandparent is it's new parent + if (successor.parent != temp) { + if (successor.right != null) { + successor.right.parent = successor.parent; + successor.parent.left = successor.right; + successor.right = temp.right; + successor.right.parent = successor; + } else { + successor.parent.left = null; + successor.right = temp.right; + successor.right.parent = successor; + } + } - if (temp == root) { - successor.parent = null; - root = successor; - return true; - } + if (temp == root) { + successor.parent = null; + root = successor; + return true; + } - //If you're not deleting the root - else { - successor.parent = temp.parent; + // If you're not deleting the root + else { + successor.parent = temp.parent; - //This if/else assigns the new node to be either the left or right child of the parent - if (temp.parent.data < temp.data) - temp.parent.right = successor; - else - temp.parent.left = successor; - return true; - } + // This if/else assigns the new node to be either the left or right child of the parent + if (temp.parent.data < temp.data) temp.parent.right = successor; + else temp.parent.left = successor; + return true; + } + } + // One child + else { + // If it has a right child + if (temp.right != null) { + if (temp == root) { + root = temp.right; + return true; } - //One child - else { - //If it has a right child - if (temp.right != null) { - if (temp == root) { - root = temp.right; - return true; - } - temp.right.parent = temp.parent; + temp.right.parent = temp.parent; - //Assigns temp to left or right child - if (temp.data < temp.parent.data) - temp.parent.left = temp.right; - else - temp.parent.right = temp.right; - return true; - } - //If it has a left child - else { - if (temp == root) { - root = temp.left; - return true; - } + // Assigns temp to left or right child + if (temp.data < temp.parent.data) temp.parent.left = temp.right; + else temp.parent.right = temp.right; + return true; + } + // If it has a left child + else { + if (temp == root) { + root = temp.left; + return true; + } - temp.left.parent = temp.parent; + temp.left.parent = temp.parent; - //Assigns temp to left or right side - if (temp.data < temp.parent.data) - temp.parent.left = temp.left; - else - temp.parent.right = temp.left; - return true; - } - } + // Assigns temp to left or right side + if (temp.data < temp.parent.data) temp.parent.left = temp.left; + else temp.parent.right = temp.left; + return true; + } } + } - /** - * This method finds the Successor to the Node given. - * Move right once and go left down the tree as far as you can - * - * @param n Node that you want to find the Successor of - * @return The Successor of the node - */ - public Node findSuccessor(Node n) { - if (n.right == null) - return n; - Node current = n.right; - Node parent = n.right; - while (current != null) { - parent = current; - current = current.left; - } - return parent; + /** + * This method finds the Successor to the Node given. Move right once and go left down the tree as + * far as you can + * + * @param n Node that you want to find the Successor of + * @return The Successor of the node + */ + public Node findSuccessor(Node n) { + if (n.right == null) return n; + Node current = n.right; + Node parent = n.right; + while (current != null) { + parent = current; + current = current.left; } + return parent; + } - /** - * Returns the root of the Binary Tree - * - * @return the root of the Binary Tree - */ - public Node getRoot() { - return root; - } + /** + * Returns the root of the Binary Tree + * + * @return the root of the Binary Tree + */ + public Node getRoot() { + return root; + } - /** - * Prints leftChild - root - rightChild - * - * @param localRoot The local root of the binary tree - */ - public void inOrder(Node localRoot) { - if (localRoot != null) { - inOrder(localRoot.left); - System.out.print(localRoot.data + " "); - inOrder(localRoot.right); - } + /** + * Prints leftChild - root - rightChild + * + * @param localRoot The local root of the binary tree + */ + public void inOrder(Node localRoot) { + if (localRoot != null) { + inOrder(localRoot.left); + System.out.print(localRoot.data + " "); + inOrder(localRoot.right); } + } - /** - * Prints root - leftChild - rightChild - * - * @param localRoot The local root of the binary tree - */ - public void preOrder(Node localRoot) { - if (localRoot != null) { - System.out.print(localRoot.data + " "); - preOrder(localRoot.left); - preOrder(localRoot.right); - } + /** + * Prints root - leftChild - rightChild + * + * @param localRoot The local root of the binary tree + */ + public void preOrder(Node localRoot) { + if (localRoot != null) { + System.out.print(localRoot.data + " "); + preOrder(localRoot.left); + preOrder(localRoot.right); } + } - /** - * Prints rightChild - leftChild - root - * - * @param localRoot The local root of the binary tree - */ - public void postOrder(Node localRoot) { - if (localRoot != null) { - postOrder(localRoot.left); - postOrder(localRoot.right); - System.out.print(localRoot.data + " "); - } + /** + * Prints rightChild - leftChild - root + * + * @param localRoot The local root of the binary tree + */ + public void postOrder(Node localRoot) { + if (localRoot != null) { + postOrder(localRoot.left); + postOrder(localRoot.right); + System.out.print(localRoot.data + " "); } + } } diff --git a/DataStructures/Trees/GenericTree.java b/DataStructures/Trees/GenericTree.java index 107a072cf965..cb30c4f452a2 100644 --- a/DataStructures/Trees/GenericTree.java +++ b/DataStructures/Trees/GenericTree.java @@ -5,230 +5,208 @@ import java.util.Scanner; /** - * A generic tree is a tree which can have as many children as it can be - * It might be possible that every node present is directly connected to - * root node. - *

- * In this code - * Every function has two copies: one function is helper function which can be called from - * main and from that function a private function is called which will do the actual work. - * I have done this, while calling from main one have to give minimum parameters. + * A generic tree is a tree which can have as many children as it can be It might be possible that + * every node present is directly connected to root node. + * + *

In this code Every function has two copies: one function is helper function which can be + * called from main and from that function a private function is called which will do the actual + * work. I have done this, while calling from main one have to give minimum parameters. */ public class GenericTree { - private class Node { - int data; - ArrayList child = new ArrayList<>(); - } - - private Node root; - private int size; - - public GenericTree() { //Constructor - Scanner scn = new Scanner(System.in); - root = create_treeG(null, 0, scn); - } - - private Node create_treeG(Node node, int childindx, Scanner scn) { - // display - if (node == null) { - System.out.println("Enter root's data"); - } else { - System.out.println("Enter data of parent of index " + node.data + " " + childindx); - } - // input - node = new Node(); - node.data = scn.nextInt(); - System.out.println("number of children"); - int number = scn.nextInt(); - for (int i = 0; i < number; i++) { - Node child = create_treeG(node, i, scn); - size++; - node.child.add(child); - } - return node; - } - - /** - * Function to display the generic tree - */ - public void display() { //Helper function - display_1(root); - } - - private void display_1(Node parent) { - System.out.print(parent.data + "=>"); - for (int i = 0; i < parent.child.size(); i++) { - System.out.print(parent.child.get(i).data + " "); - } - System.out.println("."); - for (int i = 0; i < parent.child.size(); i++) { - display_1(parent.child.get(i)); - } - } - - /** - * One call store the size directly but if you are asked compute size this function to calculate - * size goes as follows - * - * @return size - */ - public int size2call() { - return size2(root); - } - - public int size2(Node roott) { - int sz = 0; - for (int i = 0; i < roott.child.size(); i++) { - sz += size2(roott.child.get(i)); - } - return sz + 1; - } - - /** - * Function to compute maximum value in the generic tree - * - * @return maximum value - */ - public int maxcall() { - int maxi = root.data; - return max(root, maxi); - } - - private int max(Node roott, int maxi) { - if (maxi < roott.data) - maxi = roott.data; - for (int i = 0; i < roott.child.size(); i++) { - maxi = max(roott.child.get(i), maxi); - } - - return maxi; - } - - /** - * Function to compute HEIGHT of the generic tree - * - * @return height - */ - public int heightcall() { - return height(root) - 1; - } - - private int height(Node node) { - int h = 0; - for (int i = 0; i < node.child.size(); i++) { - int k = height(node.child.get(i)); - if (k > h) - h = k; - } - return h + 1; - } - - /** - * Function to find whether a number is present in the generic tree or not - * - * @param info number - * @return present or not - */ - public boolean findcall(int info) { - return find(root, info); - } - - private boolean find(Node node, int info) { - if (node.data == info) - return true; - for (int i = 0; i < node.child.size(); i++) { - if (find(node.child.get(i), info)) - return true; - } - return false; - } - - - /** - * Function to calculate depth of generic tree - * - * @param dep depth - */ - public void depthcaller(int dep) { - depth(root, dep); - } - - public void depth(Node node, int dep) { - if (dep == 0) { - System.out.println(node.data); - return; - } - for (int i = 0; i < node.child.size(); i++) - depth(node.child.get(i), dep - 1); - return; - } - - /** - * Function to print generic tree in pre-order - */ - public void preordercall() { - preorder(root); - System.out.println("."); - } - - private void preorder(Node node) { - System.out.print(node.data + " "); - for (int i = 0; i < node.child.size(); i++) - preorder(node.child.get(i)); - } - - /** - * Function to print generic tree in post-order - */ - public void postordercall() { - postorder(root); - System.out.println("."); - } - - private void postorder(Node node) { - for (int i = 0; i < node.child.size(); i++) - postorder(node.child.get(i)); - System.out.print(node.data + " "); - } - - /** - * Function to print generic tree in level-order - */ - public void levelorder() { - LinkedList q = new LinkedList<>(); - q.addLast(root); - while (!q.isEmpty()) { - int k = q.getFirst().data; - System.out.print(k + " "); - - for (int i = 0; i < q.getFirst().child.size(); i++) { - q.addLast(q.getFirst().child.get(i)); - } - q.removeFirst(); - } - System.out.println("."); - } - - /** - * Function to remove all leaves of generic tree - */ - public void removeleavescall() { - removeleaves(root); - } - - private void removeleaves(Node node) { - ArrayList arr = new ArrayList<>(); - for (int i = 0; i < node.child.size(); i++) { - if (node.child.get(i).child.size() == 0) { - arr.add(i); - // node.child.remove(i); - // i--; - } else - removeleaves(node.child.get(i)); - } - for (int i = arr.size() - 1; i >= 0; i--) { - node.child.remove(arr.get(i) + 0); - } - } - + private class Node { + int data; + ArrayList child = new ArrayList<>(); + } + + private Node root; + private int size; + + public GenericTree() { // Constructor + Scanner scn = new Scanner(System.in); + root = create_treeG(null, 0, scn); + } + + private Node create_treeG(Node node, int childindx, Scanner scn) { + // display + if (node == null) { + System.out.println("Enter root's data"); + } else { + System.out.println("Enter data of parent of index " + node.data + " " + childindx); + } + // input + node = new Node(); + node.data = scn.nextInt(); + System.out.println("number of children"); + int number = scn.nextInt(); + for (int i = 0; i < number; i++) { + Node child = create_treeG(node, i, scn); + size++; + node.child.add(child); + } + return node; + } + + /** Function to display the generic tree */ + public void display() { // Helper function + display_1(root); + } + + private void display_1(Node parent) { + System.out.print(parent.data + "=>"); + for (int i = 0; i < parent.child.size(); i++) { + System.out.print(parent.child.get(i).data + " "); + } + System.out.println("."); + for (int i = 0; i < parent.child.size(); i++) { + display_1(parent.child.get(i)); + } + } + + /** + * One call store the size directly but if you are asked compute size this function to calculate + * size goes as follows + * + * @return size + */ + public int size2call() { + return size2(root); + } + + public int size2(Node roott) { + int sz = 0; + for (int i = 0; i < roott.child.size(); i++) { + sz += size2(roott.child.get(i)); + } + return sz + 1; + } + + /** + * Function to compute maximum value in the generic tree + * + * @return maximum value + */ + public int maxcall() { + int maxi = root.data; + return max(root, maxi); + } + + private int max(Node roott, int maxi) { + if (maxi < roott.data) maxi = roott.data; + for (int i = 0; i < roott.child.size(); i++) { + maxi = max(roott.child.get(i), maxi); + } + + return maxi; + } + + /** + * Function to compute HEIGHT of the generic tree + * + * @return height + */ + public int heightcall() { + return height(root) - 1; + } + + private int height(Node node) { + int h = 0; + for (int i = 0; i < node.child.size(); i++) { + int k = height(node.child.get(i)); + if (k > h) h = k; + } + return h + 1; + } + + /** + * Function to find whether a number is present in the generic tree or not + * + * @param info number + * @return present or not + */ + public boolean findcall(int info) { + return find(root, info); + } + + private boolean find(Node node, int info) { + if (node.data == info) return true; + for (int i = 0; i < node.child.size(); i++) { + if (find(node.child.get(i), info)) return true; + } + return false; + } + + /** + * Function to calculate depth of generic tree + * + * @param dep depth + */ + public void depthcaller(int dep) { + depth(root, dep); + } + + public void depth(Node node, int dep) { + if (dep == 0) { + System.out.println(node.data); + return; + } + for (int i = 0; i < node.child.size(); i++) depth(node.child.get(i), dep - 1); + return; + } + + /** Function to print generic tree in pre-order */ + public void preordercall() { + preorder(root); + System.out.println("."); + } + + private void preorder(Node node) { + System.out.print(node.data + " "); + for (int i = 0; i < node.child.size(); i++) preorder(node.child.get(i)); + } + + /** Function to print generic tree in post-order */ + public void postordercall() { + postorder(root); + System.out.println("."); + } + + private void postorder(Node node) { + for (int i = 0; i < node.child.size(); i++) postorder(node.child.get(i)); + System.out.print(node.data + " "); + } + + /** Function to print generic tree in level-order */ + public void levelorder() { + LinkedList q = new LinkedList<>(); + q.addLast(root); + while (!q.isEmpty()) { + int k = q.getFirst().data; + System.out.print(k + " "); + + for (int i = 0; i < q.getFirst().child.size(); i++) { + q.addLast(q.getFirst().child.get(i)); + } + q.removeFirst(); + } + System.out.println("."); + } + + /** Function to remove all leaves of generic tree */ + public void removeleavescall() { + removeleaves(root); + } + + private void removeleaves(Node node) { + ArrayList arr = new ArrayList<>(); + for (int i = 0; i < node.child.size(); i++) { + if (node.child.get(i).child.size() == 0) { + arr.add(i); + // node.child.remove(i); + // i--; + } else removeleaves(node.child.get(i)); + } + for (int i = arr.size() - 1; i >= 0; i--) { + node.child.remove(arr.get(i) + 0); + } + } } diff --git a/DataStructures/Trees/LevelOrderTraversal.java b/DataStructures/Trees/LevelOrderTraversal.java index 69e65fe64089..07ae57041419 100644 --- a/DataStructures/Trees/LevelOrderTraversal.java +++ b/DataStructures/Trees/LevelOrderTraversal.java @@ -2,54 +2,48 @@ public class LevelOrderTraversal { - class Node { - int data; - Node left, right; - - public Node(int item) { - data = item; - left = right = null; - } - } - - // Root of the Binary Tree - Node root; - - public LevelOrderTraversal( Node root) { - this.root = root; - } + class Node { + int data; + Node left, right; - /* 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); + public Node(int item) { + data = item; + left = right = null; } - - /* 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 { - /** - * Return the height of larger subtree - */ - return Math.max(height(root.left), height(root.right)) + 1; - } + } + + // Root of the Binary Tree + Node root; + + public LevelOrderTraversal(Node root) { + this.root = root; + } + + /* 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 { + /** Return the height of larger subtree */ + return Math.max(height(root.left), height(root.right)) + 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); - } + } + + /* 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); } + } } diff --git a/DataStructures/Trees/LevelOrderTraversalQueue.java b/DataStructures/Trees/LevelOrderTraversalQueue.java index 5f85f987d673..58f48eba6bc5 100644 --- a/DataStructures/Trees/LevelOrderTraversalQueue.java +++ b/DataStructures/Trees/LevelOrderTraversalQueue.java @@ -1,46 +1,45 @@ package DataStructures.Trees; -import java.util.Queue; import java.util.LinkedList; - +import java.util.Queue; /* Class to print Level Order Traversal */ public class LevelOrderTraversalQueue { - /* Class to represent Tree node */ - class Node { - int data; - Node left, right; + /* Class to represent Tree node */ + class Node { + int data; + Node left, right; - public Node(int item) { - data = item; - left = null; - right = null; - } + public Node(int item) { + data = item; + left = null; + right = null; } - - /* Given a binary tree. Print its nodes in level order - using array for implementing queue */ - void printLevelOrder(Node root) { - 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); - } - } + } + + /* Given a binary tree. Print its nodes in level order + using array for implementing queue */ + void printLevelOrder(Node root) { + 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); + } } -} \ No newline at end of file + } +} diff --git a/DataStructures/Trees/PrintTopViewofTree.java b/DataStructures/Trees/PrintTopViewofTree.java index 58f611305c51..78626f46ba7d 100644 --- a/DataStructures/Trees/PrintTopViewofTree.java +++ b/DataStructures/Trees/PrintTopViewofTree.java @@ -1,4 +1,4 @@ -package DataStructures.Trees;// Java program to print top view of Binary tree +package DataStructures.Trees; // Java program to print top view of Binary tree import java.util.HashSet; import java.util.LinkedList; @@ -6,101 +6,99 @@ // Class for a tree node class TreeNode { - // Members - int key; - TreeNode left, right; + // Members + int key; + TreeNode left, right; - // Constructor - public TreeNode(int key) { - this.key = key; - left = right = null; - } + // 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; + TreeNode node; + int hd; - public QItem(TreeNode n, int h) { - node = n; - hd = h; - } + public QItem(TreeNode n, int h) { + node = n; + hd = h; + } } // Class for a Binary Tree class Tree { - TreeNode root; + TreeNode root; - // Constructors - public Tree() { - root = null; - } + // Constructors + public Tree() { + root = null; + } - public Tree(TreeNode n) { - root = n; - } + 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; - } + // 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<>(); + // 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 + // 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; + // 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 + " "); - } + // 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)); - } + // 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 PrintTopViewofTree { - 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 + 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(); + } +} diff --git a/DataStructures/Trees/RedBlackBST.java b/DataStructures/Trees/RedBlackBST.java index 45501fd290e3..f8c7b640d6c1 100644 --- a/DataStructures/Trees/RedBlackBST.java +++ b/DataStructures/Trees/RedBlackBST.java @@ -2,334 +2,330 @@ import java.util.Scanner; -/** - * @author jack870131 - */ +/** @author jack870131 */ public class RedBlackBST { - private final int R = 0; - private final int B = 1; + private final int R = 0; + private final int B = 1; - private class Node { + private class Node { - int key = -1, color = B; - Node left = nil, right = nil, p = nil; + int key = -1, color = B; + Node left = nil, right = nil, p = nil; - Node(int key) { - this.key = key; - } + Node(int key) { + this.key = key; } + } - private final Node nil = new Node(-1); - private Node root = nil; + private final Node nil = new Node(-1); + private Node root = nil; - public void printTree(Node node) { - if (node == nil) { - return; - } - printTree(node.left); - System.out.print(((node.color == R) ? " R " : " B ") + "Key: " + node.key + " Parent: " + node.p.key + "\n"); - printTree(node.right); + public void printTree(Node node) { + if (node == nil) { + return; } + printTree(node.left); + System.out.print( + ((node.color == R) ? " R " : " B ") + "Key: " + node.key + " Parent: " + node.p.key + "\n"); + printTree(node.right); + } - public void printTreepre(Node node) { - if (node == nil) { - return; - } - System.out.print(((node.color == R) ? " R " : " B ") + "Key: " + node.key + " Parent: " + node.p.key + "\n"); - printTree(node.left); - printTree(node.right); + public void printTreepre(Node node) { + if (node == nil) { + return; } + System.out.print( + ((node.color == R) ? " R " : " B ") + "Key: " + node.key + " Parent: " + node.p.key + "\n"); + printTree(node.left); + printTree(node.right); + } - private Node findNode(Node findNode, Node node) { - if (root == nil) { - return null; - } - if (findNode.key < node.key) { - if (node.left != nil) { - return findNode(findNode, node.left); - } - } else if (findNode.key > node.key) { - if (node.right != nil) { - return findNode(findNode, node.right); - } - } else if (findNode.key == node.key) { - return node; - } - return null; + private Node findNode(Node findNode, Node node) { + if (root == nil) { + return null; + } + if (findNode.key < node.key) { + if (node.left != nil) { + return findNode(findNode, node.left); + } + } else if (findNode.key > node.key) { + if (node.right != nil) { + return findNode(findNode, node.right); + } + } else if (findNode.key == node.key) { + return node; } + return null; + } - private void insert(Node node) { - Node temp = root; - if (root == nil) { - root = node; - node.color = B; - node.p = nil; - } else { - node.color = R; - while (true) { - if (node.key < temp.key) { - if (temp.left == nil) { - temp.left = node; - node.p = temp; - break; - } else { - temp = temp.left; - } - } else if (node.key >= temp.key) { - if (temp.right == nil) { - temp.right = node; - node.p = temp; - break; - } else { - temp = temp.right; - } - } - } - fixTree(node); + private void insert(Node node) { + Node temp = root; + if (root == nil) { + root = node; + node.color = B; + node.p = nil; + } else { + node.color = R; + while (true) { + if (node.key < temp.key) { + if (temp.left == nil) { + temp.left = node; + node.p = temp; + break; + } else { + temp = temp.left; + } + } else if (node.key >= temp.key) { + if (temp.right == nil) { + temp.right = node; + node.p = temp; + break; + } else { + temp = temp.right; + } } + } + fixTree(node); } + } - private void fixTree(Node node) { - while (node.p.color == R) { - Node y = nil; - if (node.p == node.p.p.left) { - y = node.p.p.right; + private void fixTree(Node node) { + while (node.p.color == R) { + Node y = nil; + if (node.p == node.p.p.left) { + y = node.p.p.right; - if (y != nil && y.color == R) { - node.p.color = B; - y.color = B; - node.p.p.color = R; - node = node.p.p; - continue; - } - if (node == node.p.right) { - node = node.p; - rotateLeft(node); - } - node.p.color = B; - node.p.p.color = R; - rotateRight(node.p.p); - } else { - y = node.p.p.left; - if (y != nil && y.color == R) { - node.p.color = B; - y.color = B; - node.p.p.color = R; - node = node.p.p; - continue; - } - if (node == node.p.left) { - node = node.p; - rotateRight(node); - } - node.p.color = B; - node.p.p.color = R; - rotateLeft(node.p.p); - } + if (y != nil && y.color == R) { + node.p.color = B; + y.color = B; + node.p.p.color = R; + node = node.p.p; + continue; } - root.color = B; + if (node == node.p.right) { + node = node.p; + rotateLeft(node); + } + node.p.color = B; + node.p.p.color = R; + rotateRight(node.p.p); + } else { + y = node.p.p.left; + if (y != nil && y.color == R) { + node.p.color = B; + y.color = B; + node.p.p.color = R; + node = node.p.p; + continue; + } + if (node == node.p.left) { + node = node.p; + rotateRight(node); + } + node.p.color = B; + node.p.p.color = R; + rotateLeft(node.p.p); + } } + root.color = B; + } - void rotateLeft(Node node) { - if (node.p != nil) { - if (node == node.p.left) { - node.p.left = node.right; - } else { - node.p.right = node.right; - } - node.right.p = node.p; - node.p = node.right; - if (node.right.left != nil) { - node.right.left.p = node; - } - node.right = node.right.left; - node.p.left = node; - } else { - Node right = root.right; - root.right = right.left; - right.left.p = root; - root.p = right; - right.left = root; - right.p = nil; - root = right; - } + void rotateLeft(Node node) { + if (node.p != nil) { + if (node == node.p.left) { + node.p.left = node.right; + } else { + node.p.right = node.right; + } + node.right.p = node.p; + node.p = node.right; + if (node.right.left != nil) { + node.right.left.p = node; + } + node.right = node.right.left; + node.p.left = node; + } else { + Node right = root.right; + root.right = right.left; + right.left.p = root; + root.p = right; + right.left = root; + right.p = nil; + root = right; } + } - void rotateRight(Node node) { - if (node.p != nil) { - if (node == node.p.left) { - node.p.left = node.left; - } else { - node.p.right = node.left; - } + void rotateRight(Node node) { + if (node.p != nil) { + if (node == node.p.left) { + node.p.left = node.left; + } else { + node.p.right = node.left; + } - node.left.p = node.p; - node.p = node.left; - if (node.left.right != nil) { - node.left.right.p = node; - } - node.left = node.left.right; - node.p.right = node; - } else { - Node left = root.left; - root.left = root.left.right; - left.right.p = root; - root.p = left; - left.right = root; - left.p = nil; - root = left; - } + node.left.p = node.p; + node.p = node.left; + if (node.left.right != nil) { + node.left.right.p = node; + } + node.left = node.left.right; + node.p.right = node; + } else { + Node left = root.left; + root.left = root.left.right; + left.right.p = root; + root.p = left; + left.right = root; + left.p = nil; + root = left; } + } - void transplant(Node target, Node with) { - if (target.p == nil) { - root = with; - } else if (target == target.p.left) { - target.p.left = with; - } else - target.p.right = with; - with.p = target.p; - } + void transplant(Node target, Node with) { + if (target.p == nil) { + root = with; + } else if (target == target.p.left) { + target.p.left = with; + } else target.p.right = with; + with.p = target.p; + } - Node treeMinimum(Node subTreeRoot) { - while (subTreeRoot.left != nil) { - subTreeRoot = subTreeRoot.left; - } - return subTreeRoot; + Node treeMinimum(Node subTreeRoot) { + while (subTreeRoot.left != nil) { + subTreeRoot = subTreeRoot.left; } + return subTreeRoot; + } - boolean delete(Node z) { - if ((z = findNode(z, root)) == null) - return false; - Node x; - Node y = z; - int yorigcolor = y.color; + boolean delete(Node z) { + if ((z = findNode(z, root)) == null) return false; + Node x; + Node y = z; + int yorigcolor = y.color; - if (z.left == nil) { - x = z.right; - transplant(z, z.right); - } else if (z.right == nil) { - x = z.left; - transplant(z, z.left); - } else { - y = treeMinimum(z.right); - yorigcolor = y.color; - x = y.right; - if (y.p == z) - x.p = y; - else { - transplant(y, y.right); - y.right = z.right; - y.right.p = y; - } - transplant(z, y); - y.left = z.left; - y.left.p = y; - y.color = z.color; - } - if (yorigcolor == B) - deleteFixup(x); - return true; + if (z.left == nil) { + x = z.right; + transplant(z, z.right); + } else if (z.right == nil) { + x = z.left; + transplant(z, z.left); + } else { + y = treeMinimum(z.right); + yorigcolor = y.color; + x = y.right; + if (y.p == z) x.p = y; + else { + transplant(y, y.right); + y.right = z.right; + y.right.p = y; + } + transplant(z, y); + y.left = z.left; + y.left.p = y; + y.color = z.color; } + if (yorigcolor == B) deleteFixup(x); + return true; + } - void deleteFixup(Node x) { - while (x != root && x.color == B) { - if (x == x.p.left) { - Node w = x.p.right; - if (w.color == R) { - w.color = B; - x.p.color = R; - rotateLeft(x.p); - w = x.p.right; - } - if (w.left.color == B && w.right.color == B) { - w.color = R; - x = x.p; - continue; - } else if (w.right.color == B) { - w.left.color = B; - w.color = R; - rotateRight(w); - w = x.p.right; - } - if (w.right.color == R) { - w.color = x.p.color; - x.p.color = B; - w.right.color = B; - rotateLeft(x.p); - x = root; - } - } else { - Node w = x.p.left; - if (w.color == R) { - w.color = B; - x.p.color = R; - rotateRight(x.p); - w = x.p.left; - } - if (w.right.color == B && w.left.color == B) { - w.color = R; - x = x.p; - continue; - } else if (w.left.color == B) { - w.right.color = B; - w.color = R; - rotateLeft(w); - w = x.p.left; - } - if (w.left.color == R) { - w.color = x.p.color; - x.p.color = B; - w.left.color = B; - rotateRight(x.p); - x = root; - } - } + void deleteFixup(Node x) { + while (x != root && x.color == B) { + if (x == x.p.left) { + Node w = x.p.right; + if (w.color == R) { + w.color = B; + x.p.color = R; + rotateLeft(x.p); + w = x.p.right; + } + if (w.left.color == B && w.right.color == B) { + w.color = R; + x = x.p; + continue; + } else if (w.right.color == B) { + w.left.color = B; + w.color = R; + rotateRight(w); + w = x.p.right; + } + if (w.right.color == R) { + w.color = x.p.color; + x.p.color = B; + w.right.color = B; + rotateLeft(x.p); + x = root; + } + } else { + Node w = x.p.left; + if (w.color == R) { + w.color = B; + x.p.color = R; + rotateRight(x.p); + w = x.p.left; } - x.color = B; + if (w.right.color == B && w.left.color == B) { + w.color = R; + x = x.p; + continue; + } else if (w.left.color == B) { + w.right.color = B; + w.color = R; + rotateLeft(w); + w = x.p.left; + } + if (w.left.color == R) { + w.color = x.p.color; + x.p.color = B; + w.left.color = B; + rotateRight(x.p); + x = root; + } + } } + x.color = B; + } - public void insertDemo() { - Scanner scan = new Scanner(System.in); - while (true) { - System.out.println("Add items"); + public void insertDemo() { + Scanner scan = new Scanner(System.in); + while (true) { + System.out.println("Add items"); - int item; - Node node; + int item; + Node node; - item = scan.nextInt(); - while (item != -999) { - node = new Node(item); - insert(node); - item = scan.nextInt(); - } - printTree(root); - System.out.println("Pre order"); - printTreepre(root); - break; - } - scan.close(); - } - - public void deleteDemo() { - Scanner scan = new Scanner(System.in); - System.out.println("Delete items"); - int item; - Node node; - item = scan.nextInt(); + item = scan.nextInt(); + while (item != -999) { node = new Node(item); - System.out.print("Deleting item " + item); - if (delete(node)) { - System.out.print(": deleted!"); - } else { - System.out.print(": does not exist!"); - } + insert(node); + item = scan.nextInt(); + } + printTree(root); + System.out.println("Pre order"); + printTreepre(root); + break; + } + scan.close(); + } - System.out.println(); - printTree(root); - System.out.println("Pre order"); - printTreepre(root); - scan.close(); + public void deleteDemo() { + Scanner scan = new Scanner(System.in); + System.out.println("Delete items"); + int item; + Node node; + item = scan.nextInt(); + node = new Node(item); + System.out.print("Deleting item " + item); + if (delete(node)) { + System.out.print(": deleted!"); + } else { + System.out.print(": does not exist!"); } -} \ No newline at end of file + + System.out.println(); + printTree(root); + System.out.println("Pre order"); + printTreepre(root); + scan.close(); + } +} diff --git a/DataStructures/Trees/TreeTraversal.java b/DataStructures/Trees/TreeTraversal.java index 1c5f8a43715b..e9cca1ccdd6b 100644 --- a/DataStructures/Trees/TreeTraversal.java +++ b/DataStructures/Trees/TreeTraversal.java @@ -2,120 +2,112 @@ import java.util.LinkedList; -/** - * @author Varun Upadhyay (https://github.com/varunu28) - */ - +/** @author Varun Upadhyay (https://github.com/varunu28) */ // Driver Program 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); + 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 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(); - } + // 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(); + } } /** - * The Node class which initializes a Node of a tree - * Consists of all 4 traversal methods: printInOrder, printPostOrder, printPreOrder & printLevelOrder - * printInOrder: LEFT -> ROOT -> RIGHT - * printPreOrder: ROOT -> LEFT -> RIGHT - * printPostOrder: LEFT -> RIGHT -> ROOT - * printLevelOrder: Prints by level (starting at root), from left to right. + * The Node class which initializes a Node of a tree Consists of all 4 traversal methods: + * printInOrder, printPostOrder, printPreOrder & printLevelOrder 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; + Node left, right; + int data; - public Node(int data) { - this.data = 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 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 printInOrder() { - if (left != null) { - left.printInOrder(); - } - System.out.print(data + " "); - if (right != null) { - right.printInOrder(); - } + public void printInOrder() { + if (left != null) { + left.printInOrder(); + } + System.out.print(data + " "); + if (right != null) { + right.printInOrder(); } + } - public void printPreOrder() { - System.out.print(data + " "); - if (left != null) { - left.printPreOrder(); - } - if (right != null) { - right.printPreOrder(); - } + public void printPreOrder() { + System.out.print(data + " "); + if (left != null) { + left.printPreOrder(); } + if (right != null) { + right.printPreOrder(); + } + } - public void printPostOrder() { - if (left != null) { - left.printPostOrder(); - } - if (right != null) { - right.printPostOrder(); - } - System.out.print(data + " "); + public void printPostOrder() { + if (left != null) { + left.printPostOrder(); + } + if (right != null) { + right.printPostOrder(); } + 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 + " "); - // 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); - } - } + /** 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 + " "); + // 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); + } } + } } diff --git a/DataStructures/Trees/TrieImp.java b/DataStructures/Trees/TrieImp.java index 24450f16c2cb..3c3ddc5d35ee 100644 --- a/DataStructures/Trees/TrieImp.java +++ b/DataStructures/Trees/TrieImp.java @@ -5,137 +5,125 @@ * * @author Dheeraj Kumar Barnwal (https://github.com/dheeraj92) */ - import java.util.Scanner; public class TrieImp { - public class TrieNode { - TrieNode[] child; - boolean end; + public class TrieNode { + TrieNode[] child; + boolean end; - public TrieNode() { - child = new TrieNode[26]; - end = false; - } + public TrieNode() { + child = new TrieNode[26]; + end = false; } + } - private final TrieNode root; + private final TrieNode root; - public TrieImp() { - root = new TrieNode(); - } + public TrieImp() { + root = new TrieNode(); + } - public void insert(String word) { - TrieNode currentNode = root; - for (int i = 0; i < word.length(); i++) { - TrieNode node = currentNode.child[word.charAt(i) - 'a']; - if (node == null) { - node = new TrieNode(); - currentNode.child[word.charAt(i) - 'a'] = node; - } - currentNode = node; - } - currentNode.end = true; + public void insert(String word) { + TrieNode currentNode = root; + for (int i = 0; i < word.length(); i++) { + TrieNode node = currentNode.child[word.charAt(i) - 'a']; + if (node == null) { + node = new TrieNode(); + currentNode.child[word.charAt(i) - 'a'] = node; + } + currentNode = node; } + currentNode.end = true; + } - public boolean search(String word) { - TrieNode currentNode = root; - for (int i = 0; i < word.length(); i++) { - char ch = word.charAt(i); - TrieNode node = currentNode.child[ch - 'a']; - if (node == null) { - return false; - } - currentNode = node; - } - return currentNode.end; + public boolean search(String word) { + TrieNode currentNode = root; + for (int i = 0; i < word.length(); i++) { + char ch = word.charAt(i); + TrieNode node = currentNode.child[ch - 'a']; + if (node == null) { + return false; + } + currentNode = node; } + return currentNode.end; + } - public boolean delete(String word) { - TrieNode currentNode = root; - for (int i = 0; i < word.length(); i++) { - char ch = word.charAt(i); - TrieNode node = currentNode.child[ch - 'a']; - if (node == null) { - return false; - } - currentNode = node; - } - if (currentNode.end == true) { - currentNode.end = false; - return true; - } + public boolean delete(String word) { + TrieNode currentNode = root; + for (int i = 0; i < word.length(); i++) { + char ch = word.charAt(i); + TrieNode node = currentNode.child[ch - 'a']; + if (node == null) { return false; + } + currentNode = node; } - - public static void sop(String print) { - System.out.println(print); + if (currentNode.end == true) { + currentNode.end = false; + return true; } + return false; + } - /** - * Regex to check if word contains only a-z character - */ - public static boolean isValid(String word) { - return word.matches("^[a-z]+$"); - } + public static void sop(String print) { + System.out.println(print); + } + + /** Regex to check if word contains only a-z character */ + public static boolean isValid(String word) { + return word.matches("^[a-z]+$"); + } - public static void main(String[] args) { - TrieImp obj = new TrieImp(); - String word; - @SuppressWarnings("resource") - Scanner scan = new Scanner(System.in); - sop("string should contain only a-z character for all operation"); - while (true) { - sop("1. Insert\n2. Search\n3. Delete\n4. Quit"); - try { - int t = scan.nextInt(); - switch (t) { - case 1: - word = scan.next(); - if (isValid(word)) - obj.insert(word); - else - sop("Invalid string: allowed only a-z"); - break; - case 2: - word = scan.next(); - boolean resS = false; - if (isValid(word)) - resS = obj.search(word); - else - sop("Invalid string: allowed only a-z"); - if (resS) - sop("word found"); - else - sop("word not found"); - break; - case 3: - word = scan.next(); - boolean resD = false; - if (isValid(word)) - resD = obj.delete(word); - else - sop("Invalid string: allowed only a-z"); - if (resD) { - sop("word got deleted successfully"); - } else { - sop("word not found"); - } - break; - case 4: - sop("Quit successfully"); - System.exit(1); - break; - default: - sop("Input int from 1-4"); - break; - } - } catch (Exception e) { - String badInput = scan.next(); - sop("This is bad input: " + badInput); + public static void main(String[] args) { + TrieImp obj = new TrieImp(); + String word; + @SuppressWarnings("resource") + Scanner scan = new Scanner(System.in); + sop("string should contain only a-z character for all operation"); + while (true) { + sop("1. Insert\n2. Search\n3. Delete\n4. Quit"); + try { + int t = scan.nextInt(); + switch (t) { + case 1: + word = scan.next(); + if (isValid(word)) obj.insert(word); + else sop("Invalid string: allowed only a-z"); + break; + case 2: + word = scan.next(); + boolean resS = false; + if (isValid(word)) resS = obj.search(word); + else sop("Invalid string: allowed only a-z"); + if (resS) sop("word found"); + else sop("word not found"); + break; + case 3: + word = scan.next(); + boolean resD = false; + if (isValid(word)) resD = obj.delete(word); + else sop("Invalid string: allowed only a-z"); + if (resD) { + sop("word got deleted successfully"); + } else { + sop("word not found"); } + break; + case 4: + sop("Quit successfully"); + System.exit(1); + break; + default: + sop("Input int from 1-4"); + break; } + } catch (Exception e) { + String badInput = scan.next(); + sop("This is bad input: " + badInput); + } } - + } } diff --git a/DataStructures/Trees/ValidBSTOrNot.java b/DataStructures/Trees/ValidBSTOrNot.java index ba50c079eac4..3b3d626286c9 100644 --- a/DataStructures/Trees/ValidBSTOrNot.java +++ b/DataStructures/Trees/ValidBSTOrNot.java @@ -2,43 +2,39 @@ public class ValidBSTOrNot { - class Node { - int data; - Node left, right; - - public Node(int item) { - data = item; - left = right = null; - } + class Node { + int data; + Node left, right; + + public Node(int item) { + data = item; + left = right = null; } + } - //Root of the Binary Tree - - /* can give min and max value according to your code or - can write a function to find min and max value of tree. */ + // Root of the Binary Tree - /* returns true if given search tree is binary - search tree (efficient version) */ - boolean isBST(Node root) { - return isBSTUtil(root, Integer.MIN_VALUE, - Integer.MAX_VALUE); - } + /* 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 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)); - } -} \ No newline at end of file + /* returns true if given search tree is binary + search tree (efficient version) */ + boolean isBST(Node root) { + 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)); + } +} diff --git a/DynamicProgramming/BoardPath.java b/DynamicProgramming/BoardPath.java index 5ca14d1fab9b..89f5c805b577 100644 --- a/DynamicProgramming/BoardPath.java +++ b/DynamicProgramming/BoardPath.java @@ -1,8 +1,8 @@ package DynamicProgramming; /* -* this is an important Algo in which -* we have starting and ending of board and we have to reach -* we have to count no. of ways +* this is an important Algo in which +* we have starting and ending of board and we have to reach +* we have to count no. of ways * that help to reach end point i.e number by rolling dice * which have 1 to 6 digits @@ -20,58 +20,56 @@ startAlgo(); System.out.println(bpIS(0,n,strg)); System.out.println(endAlgo()+"ms"); - + */ public class BoardPath { - public static long startTime; - public static long endTime; - public static void startAlgo() { - startTime=System.currentTimeMillis(); - } - public static long endAlgo() { - endTime=System.currentTimeMillis(); - return endTime-startTime; - } - public static int bpR(int start,int end){ - if(start==end) { - return 1; - } - else if(start>end) - return 0; - int count=0; - for(int dice=1;dice<=6;dice++) { - count+=bpR(start+dice,end); - } - return count; - } - public static int bpRS(int curr,int end,int strg[]){ - if(curr==end) { - return 1; - } - else if(curr>end) - return 0; - if(strg[curr]!=0) - return strg[curr]; - int count=0; - for(int dice=1;dice<=6;dice++) { - count+=bpRS(curr+dice,end,strg); - } - strg[curr]=count; - return count; - } - public static int bpIS(int curr,int end,int[]strg){ - strg[end]=1; - for(int i=end-1;i>=0;i--) { - int count=0; - for(int dice=1;dice<=6&&dice+i end) return 0; + int count = 0; + for (int dice = 1; dice <= 6; dice++) { + count += bpR(start + dice, end); + } + return count; + } + public static int bpRS(int curr, int end, int strg[]) { + if (curr == end) { + return 1; + } else if (curr > end) return 0; + if (strg[curr] != 0) return strg[curr]; + int count = 0; + for (int dice = 1; dice <= 6; dice++) { + count += bpRS(curr + dice, end, strg); + } + strg[curr] = count; + return count; + } + public static int bpIS(int curr, int end, int[] strg) { + strg[end] = 1; + for (int i = end - 1; i >= 0; i--) { + int count = 0; + for (int dice = 1; dice <= 6 && dice + i < strg.length; dice++) { + count += strg[i + dice]; + } + strg[i] = count; + } + return strg[0]; + } } diff --git a/DynamicProgramming/CoinChange.java b/DynamicProgramming/CoinChange.java index 7e4e6181ccc9..f6d4f8f574c2 100644 --- a/DynamicProgramming/CoinChange.java +++ b/DynamicProgramming/CoinChange.java @@ -1,79 +1,82 @@ package DynamicProgramming; -/** - * @author Varun Upadhyay (https://github.com/varunu28) - */ +/** @author Varun Upadhyay (https://github.com/varunu28) */ public class CoinChange { - // Driver Program - public static void main(String[] args) { + // Driver Program + public static void main(String[] args) { - int amount = 12; - int[] coins = {2, 4, 5}; + int amount = 12; + int[] coins = {2, 4, 5}; - System.out.println("Number of combinations of getting change for " + amount + " is: " + change(coins, amount)); - System.out.println("Minimum number of coins required for amount :" + amount + " is: " + minimumCoins(coins, amount)); + System.out.println( + "Number of combinations of getting change for " + amount + " is: " + change(coins, amount)); + System.out.println( + "Minimum number of coins required for amount :" + + amount + + " is: " + + minimumCoins(coins, amount)); + } - } - - /** - * This method finds the number of combinations of getting change for a given amount and change coins - * - * @param coins The list of coins - * @param amount The amount for which we need to find the change - * Finds the number of combinations of change - **/ - public static int change(int[] coins, int amount) { + /** + * This method finds the number of combinations of getting change for a given amount and change + * coins + * + * @param coins The list of coins + * @param amount The amount for which we need to find the change Finds the number of combinations + * of change + */ + public static int change(int[] coins, int amount) { - int[] combinations = new int[amount + 1]; - combinations[0] = 1; - - for (int coin : coins) { - for (int i = coin; i < amount + 1; i++) { - combinations[i] += combinations[i - coin]; - } - // Uncomment the below line to see the state of combinations for each coin - // printAmount(combinations); - } + int[] combinations = new int[amount + 1]; + combinations[0] = 1; - return combinations[amount]; + for (int coin : coins) { + for (int i = coin; i < amount + 1; i++) { + combinations[i] += combinations[i - coin]; + } + // Uncomment the below line to see the state of combinations for each coin + // printAmount(combinations); } - /** - * This method finds the minimum number of coins needed for a given amount. - * - * @param coins The list of coins - * @param amount The amount for which we need to find the minimum number of coins. - * Finds the the minimum number of coins that make a given value. - **/ - public static int minimumCoins(int[] coins, int amount) { - //minimumCoins[i] will store the minimum coins needed for amount i - int[] minimumCoins = new int[amount + 1]; + return combinations[amount]; + } - minimumCoins[0] = 0; + /** + * This method finds the minimum number of coins needed for a given amount. + * + * @param coins The list of coins + * @param amount The amount for which we need to find the minimum number of coins. Finds the the + * minimum number of coins that make a given value. + */ + public static int minimumCoins(int[] coins, int amount) { + // minimumCoins[i] will store the minimum coins needed for amount i + int[] minimumCoins = new int[amount + 1]; - for (int i = 1; i <= amount; i++) { - minimumCoins[i] = Integer.MAX_VALUE; - } - for (int i = 1; i <= amount; i++) { - for (int coin : coins) { - if (coin <= i) { - int sub_res = minimumCoins[i - coin]; - if (sub_res != Integer.MAX_VALUE && sub_res + 1 < minimumCoins[i]) - minimumCoins[i] = sub_res + 1; - } - } + minimumCoins[0] = 0; + + for (int i = 1; i <= amount; i++) { + minimumCoins[i] = Integer.MAX_VALUE; + } + for (int i = 1; i <= amount; i++) { + for (int coin : coins) { + if (coin <= i) { + int sub_res = minimumCoins[i - coin]; + if (sub_res != Integer.MAX_VALUE && sub_res + 1 < minimumCoins[i]) + minimumCoins[i] = sub_res + 1; } - // Uncomment the below line to see the state of combinations for each coin - //printAmount(minimumCoins); - return minimumCoins[amount]; + } } + // Uncomment the below line to see the state of combinations for each coin + // printAmount(minimumCoins); + return minimumCoins[amount]; + } - // A basic print method which prints all the contents of the array - public static void printAmount(int[] arr) { - for (int i = 0; i < arr.length; i++) { - System.out.print(arr[i] + " "); - } - System.out.println(); + // A basic print method which prints all the contents of the array + public static void printAmount(int[] arr) { + for (int i = 0; i < arr.length; i++) { + System.out.print(arr[i] + " "); } -} \ No newline at end of file + System.out.println(); + } +} diff --git a/DynamicProgramming/EditDistance.java b/DynamicProgramming/EditDistance.java index 20cb8803a754..7a70db326250 100644 --- a/DynamicProgramming/EditDistance.java +++ b/DynamicProgramming/EditDistance.java @@ -1,79 +1,80 @@ package DynamicProgramming; /** - * A DynamicProgramming based solution for Edit Distance problem In Java - * Description of Edit Distance with an Example: - *

- * Edit distance is a way of quantifying how dissimilar two strings (e.g., words) are to one another, - * by counting the minimum number of operations required to transform one string into the other. The - * distance operations are the removal, insertion, or substitution of a character in the string. - *

- *

- * The Distance between "kitten" and "sitting" is 3. A minimal edit script that transforms the former into the latter is: + * A DynamicProgramming based solution for Edit Distance problem In Java Description of Edit + * Distance with an Example: + * + *

Edit distance is a way of quantifying how dissimilar two strings (e.g., words) are to one + * another, by counting the minimum number of operations required to transform one string into the + * other. The distance operations are the removal, insertion, or substitution of a character in the + * string. + * *

- * kitten → sitten (substitution of "s" for "k") - * sitten → sittin (substitution of "i" for "e") + * + *

The Distance between "kitten" and "sitting" is 3. A minimal edit script that transforms the + * former into the latter is: + * + *

kitten → sitten (substitution of "s" for "k") sitten → sittin (substitution of "i" for "e") * sittin → sitting (insertion of "g" at the end). * * @author SUBHAM SANGHAI - **/ - + */ import java.util.Scanner; public class EditDistance { - public static int minDistance(String word1, String word2) { - int len1 = word1.length(); - int len2 = word2.length(); - // len1+1, len2+1, because finally return dp[len1][len2] - int[][] dp = new int[len1 + 1][len2 + 1]; - /* If second string is empty, the only option is to - insert all characters of first string into second*/ - for (int i = 0; i <= len1; i++) { - dp[i][0] = i; - } - /* If first string is empty, the only option is to - insert all characters of second string into first*/ - for (int j = 0; j <= len2; j++) { - dp[0][j] = j; - } - //iterate though, and check last char - for (int i = 0; i < len1; i++) { - char c1 = word1.charAt(i); - for (int j = 0; j < len2; j++) { - char c2 = word2.charAt(j); - //if last two chars equal - if (c1 == c2) { - //update dp value for +1 length - dp[i + 1][j + 1] = dp[i][j]; - } else { - /* if two characters are different , - then take the minimum of the various operations(i.e insertion,removal,substitution)*/ - int replace = dp[i][j] + 1; - int insert = dp[i][j + 1] + 1; - int delete = dp[i + 1][j] + 1; + public static int minDistance(String word1, String word2) { + int len1 = word1.length(); + int len2 = word2.length(); + // len1+1, len2+1, because finally return dp[len1][len2] + int[][] dp = new int[len1 + 1][len2 + 1]; + /* If second string is empty, the only option is to + insert all characters of first string into second*/ + for (int i = 0; i <= len1; i++) { + dp[i][0] = i; + } + /* If first string is empty, the only option is to + insert all characters of second string into first*/ + for (int j = 0; j <= len2; j++) { + dp[0][j] = j; + } + // iterate though, and check last char + for (int i = 0; i < len1; i++) { + char c1 = word1.charAt(i); + for (int j = 0; j < len2; j++) { + char c2 = word2.charAt(j); + // if last two chars equal + if (c1 == c2) { + // update dp value for +1 length + dp[i + 1][j + 1] = dp[i][j]; + } else { + /* if two characters are different , + then take the minimum of the various operations(i.e insertion,removal,substitution)*/ + int replace = dp[i][j] + 1; + int insert = dp[i][j + 1] + 1; + int delete = dp[i + 1][j] + 1; - int min = replace > insert ? insert : replace; - min = delete > min ? min : delete; - dp[i + 1][j + 1] = min; - } - } + int min = replace > insert ? insert : replace; + min = delete > min ? min : delete; + dp[i + 1][j + 1] = min; } - /* return the final answer , after traversing through both the strings*/ - return dp[len1][len2]; + } } + /* return the final answer , after traversing through both the strings*/ + return dp[len1][len2]; + } - - public static void main(String[] args) { - Scanner input = new Scanner(System.in); - String s1, s2; - System.out.println("Enter the First String"); - s1 = input.nextLine(); - System.out.println("Enter the Second String"); - s2 = input.nextLine(); - //ans stores the final Edit Distance between the two strings - int ans = minDistance(s1, s2); - System.out.println("The minimum Edit Distance between \"" + s1 + "\" and \"" + s2 + "\" is " + ans); - input.close(); - } + public static void main(String[] args) { + Scanner input = new Scanner(System.in); + String s1, s2; + System.out.println("Enter the First String"); + s1 = input.nextLine(); + System.out.println("Enter the Second String"); + s2 = input.nextLine(); + // ans stores the final Edit Distance between the two strings + int ans = minDistance(s1, s2); + System.out.println( + "The minimum Edit Distance between \"" + s1 + "\" and \"" + s2 + "\" is " + ans); + input.close(); + } } diff --git a/DynamicProgramming/EggDropping.java b/DynamicProgramming/EggDropping.java index f53712bd9304..cd2bf82a49cf 100644 --- a/DynamicProgramming/EggDropping.java +++ b/DynamicProgramming/EggDropping.java @@ -1,49 +1,45 @@ package DynamicProgramming; -/** - * DynamicProgramming solution for the Egg Dropping Puzzle - */ +/** DynamicProgramming solution for the Egg Dropping Puzzle */ public class EggDropping { - // min trials with n eggs and m floors + // min trials with n eggs and m floors - private static int minTrials(int n, int m) { + private static int minTrials(int n, int m) { - int[][] eggFloor = new int[n + 1][m + 1]; - int result, x; + int[][] eggFloor = new int[n + 1][m + 1]; + int result, x; - for (int i = 1; i <= n; i++) { - eggFloor[i][0] = 0; // Zero trial for zero floor. - eggFloor[i][1] = 1; // One trial for one floor - } + for (int i = 1; i <= n; i++) { + eggFloor[i][0] = 0; // Zero trial for zero floor. + eggFloor[i][1] = 1; // One trial for one floor + } - // j trials for only 1 egg + // j trials for only 1 egg - for (int j = 1; j <= m; j++) - eggFloor[1][j] = j; + for (int j = 1; j <= m; j++) eggFloor[1][j] = j; - // Using bottom-up approach in DP + // Using bottom-up approach in DP - for (int i = 2; i <= n; i++) { - for (int j = 2; j <= m; j++) { - eggFloor[i][j] = Integer.MAX_VALUE; - for (x = 1; x <= j; x++) { - result = 1 + Math.max(eggFloor[i - 1][x - 1], eggFloor[i][j - x]); + for (int i = 2; i <= n; i++) { + for (int j = 2; j <= m; j++) { + eggFloor[i][j] = Integer.MAX_VALUE; + for (x = 1; x <= j; x++) { + result = 1 + Math.max(eggFloor[i - 1][x - 1], eggFloor[i][j - x]); - // choose min of all values for particular x - if (result < eggFloor[i][j]) - eggFloor[i][j] = result; - } - } + // choose min of all values for particular x + if (result < eggFloor[i][j]) eggFloor[i][j] = result; } - - return eggFloor[n][m]; + } } - public static void main(String args[]) { - int n = 2, m = 4; - // result outputs min no. of trials in worst case for n eggs and m floors - int result = minTrials(n, m); - System.out.println(result); - } + return eggFloor[n][m]; + } + + public static void main(String args[]) { + int n = 2, m = 4; + // result outputs min no. of trials in worst case for n eggs and m floors + int result = minTrials(n, m); + System.out.println(result); + } } diff --git a/DynamicProgramming/Fibonacci.java b/DynamicProgramming/Fibonacci.java index 89be0836f6af..568cd4dd80a2 100644 --- a/DynamicProgramming/Fibonacci.java +++ b/DynamicProgramming/Fibonacci.java @@ -4,97 +4,88 @@ import java.util.Map; import java.util.Scanner; -/** - * @author Varun Upadhyay (https://github.com/varunu28) - */ - +/** @author Varun Upadhyay (https://github.com/varunu28) */ public class Fibonacci { - private static Map map = new HashMap<>(); - - - public static void main(String[] args) { - - // Methods all returning [0, 1, 1, 2, 3, 5, ...] for n = [0, 1, 2, 3, 4, 5, ...] - Scanner sc = new Scanner(System.in); - int n = sc.nextInt(); - - System.out.println(fibMemo(n)); - System.out.println(fibBotUp(n)); - System.out.println(fibOptimized(n)); - sc.close(); + private static Map map = new HashMap<>(); + + public static void main(String[] args) { + + // Methods all returning [0, 1, 1, 2, 3, 5, ...] for n = [0, 1, 2, 3, 4, 5, ...] + Scanner sc = new Scanner(System.in); + int n = sc.nextInt(); + + System.out.println(fibMemo(n)); + System.out.println(fibBotUp(n)); + System.out.println(fibOptimized(n)); + sc.close(); + } + + /** + * This method finds the nth fibonacci number using memoization technique + * + * @param n The input n for which we have to determine the fibonacci number Outputs the nth + * fibonacci number + */ + public static int fibMemo(int n) { + if (map.containsKey(n)) { + return map.get(n); } - /** - * This method finds the nth fibonacci number using memoization technique - * - * @param n The input n for which we have to determine the fibonacci number - * Outputs the nth fibonacci number - **/ - public static int fibMemo(int n) { - if (map.containsKey(n)) { - return map.get(n); - } - - int f; + int f; - if (n <= 1) { - f = n; - } else { - f = fibMemo(n - 1) + fibMemo(n - 2); - map.put(n, f); - } - return f; + if (n <= 1) { + f = n; + } else { + f = fibMemo(n - 1) + fibMemo(n - 2); + map.put(n, f); } - - /** - * This method finds the nth fibonacci number using bottom up - * - * @param n The input n for which we have to determine the fibonacci number - * Outputs the nth fibonacci number - **/ - public static int fibBotUp(int n) { - - Map fib = new HashMap<>(); - - for (int i = 0; i <= n; i++) { - int f; - if (i <= 1) { - f = i; - } else { - f = fib.get(i - 1) + fib.get(i - 2); - } - fib.put(i, f); - } - - return fib.get(n); + return f; + } + + /** + * This method finds the nth fibonacci number using bottom up + * + * @param n The input n for which we have to determine the fibonacci number Outputs the nth + * fibonacci number + */ + public static int fibBotUp(int n) { + + Map fib = new HashMap<>(); + + for (int i = 0; i <= n; i++) { + int f; + if (i <= 1) { + f = i; + } else { + f = fib.get(i - 1) + fib.get(i - 2); + } + fib.put(i, f); } - - /** - * This method finds the nth fibonacci number using bottom up - * - * @param n The input n for which we have to determine the fibonacci number - * Outputs the nth fibonacci number - *

- * This is optimized version of Fibonacci Program. Without using Hashmap and recursion. - * It saves both memory and time. - * Space Complexity will be O(1) - * Time Complexity will be O(n) - *

- * Whereas , the above functions will take O(n) Space. - * @author Shoaib Rayeen (https://github.com/shoaibrayeen) - **/ - public static int fibOptimized(int n) { - if (n == 0) { - return 0; - } - int prev = 0, res = 1, next; - for (int i = 2; i <= n; i++) { - next = prev + res; - prev = res; - res = next; - } - return res; + return fib.get(n); + } + + /** + * This method finds the nth fibonacci number using bottom up + * + * @param n The input n for which we have to determine the fibonacci number Outputs the nth + * fibonacci number + *

This is optimized version of Fibonacci Program. Without using Hashmap and recursion. It + * saves both memory and time. Space Complexity will be O(1) Time Complexity will be O(n) + *

Whereas , the above functions will take O(n) Space. + * @author Shoaib Rayeen (https://github.com/shoaibrayeen) + */ + public static int fibOptimized(int n) { + if (n == 0) { + return 0; + } + int prev = 0, res = 1, next; + for (int i = 2; i <= n; i++) { + next = prev + res; + prev = res; + res = next; } + return res; + } } diff --git a/DynamicProgramming/FordFulkerson.java b/DynamicProgramming/FordFulkerson.java index 7a162fbb06d1..419316d71ea5 100644 --- a/DynamicProgramming/FordFulkerson.java +++ b/DynamicProgramming/FordFulkerson.java @@ -5,68 +5,66 @@ import java.util.Vector; public class FordFulkerson { - final static int INF = 987654321; - // edges - static int V; - static int[][] capacity, flow; + static final int INF = 987654321; + // edges + static int V; + static int[][] capacity, flow; - public static void main(String[] args) { - System.out.println("V : 6"); - V = 6; - capacity = new int[V][V]; + public static void main(String[] args) { + System.out.println("V : 6"); + V = 6; + capacity = new int[V][V]; - capacity[0][1] = 12; - capacity[0][3] = 13; - capacity[1][2] = 10; - capacity[2][3] = 13; - capacity[2][4] = 3; - capacity[2][5] = 15; - capacity[3][2] = 7; - capacity[3][4] = 15; - capacity[4][5] = 17; + capacity[0][1] = 12; + capacity[0][3] = 13; + capacity[1][2] = 10; + capacity[2][3] = 13; + capacity[2][4] = 3; + capacity[2][5] = 15; + capacity[3][2] = 7; + capacity[3][4] = 15; + capacity[4][5] = 17; - System.out.println("Max capacity in networkFlow : " + networkFlow(0, 5)); - } - - private static int networkFlow(int source, int sink) { - flow = new int[V][V]; - int totalFlow = 0; - while (true) { - Vector parent = new Vector<>(V); - for (int i = 0; i < V; i++) - parent.add(-1); - Queue q = new LinkedList<>(); - parent.set(source, source); - q.add(source); - while (!q.isEmpty() && parent.get(sink) == -1) { - int here = q.peek(); - q.poll(); - for (int there = 0; there < V; ++there) - if (capacity[here][there] - flow[here][there] > 0 && parent.get(there) == -1) { - q.add(there); - parent.set(there, here); - } - } - if (parent.get(sink) == -1) - break; + System.out.println("Max capacity in networkFlow : " + networkFlow(0, 5)); + } - int amount = INF; - String printer = "path : "; - StringBuilder sb = new StringBuilder(); - for (int p = sink; p != source; p = parent.get(p)) { - amount = Math.min(capacity[parent.get(p)][p] - flow[parent.get(p)][p], amount); - sb.append(p + "-"); - } - sb.append(source); - for (int p = sink; p != source; p = parent.get(p)) { - flow[parent.get(p)][p] += amount; - flow[p][parent.get(p)] -= amount; - } - totalFlow += amount; - printer += sb.reverse() + " / max flow : " + totalFlow; - System.out.println(printer); - } + private static int networkFlow(int source, int sink) { + flow = new int[V][V]; + int totalFlow = 0; + while (true) { + Vector parent = new Vector<>(V); + for (int i = 0; i < V; i++) parent.add(-1); + Queue q = new LinkedList<>(); + parent.set(source, source); + q.add(source); + while (!q.isEmpty() && parent.get(sink) == -1) { + int here = q.peek(); + q.poll(); + for (int there = 0; there < V; ++there) + if (capacity[here][there] - flow[here][there] > 0 && parent.get(there) == -1) { + q.add(there); + parent.set(there, here); + } + } + if (parent.get(sink) == -1) break; - return totalFlow; + int amount = INF; + String printer = "path : "; + StringBuilder sb = new StringBuilder(); + for (int p = sink; p != source; p = parent.get(p)) { + amount = Math.min(capacity[parent.get(p)][p] - flow[parent.get(p)][p], amount); + sb.append(p + "-"); + } + sb.append(source); + for (int p = sink; p != source; p = parent.get(p)) { + flow[parent.get(p)][p] += amount; + flow[p][parent.get(p)] -= amount; + } + totalFlow += amount; + printer += sb.reverse() + " / max flow : " + totalFlow; + System.out.println(printer); } + + return totalFlow; + } } diff --git a/DynamicProgramming/KadaneAlgorithm.java b/DynamicProgramming/KadaneAlgorithm.java index 8d77c7a7c556..f33d941e8da1 100644 --- a/DynamicProgramming/KadaneAlgorithm.java +++ b/DynamicProgramming/KadaneAlgorithm.java @@ -3,53 +3,50 @@ import java.util.Scanner; /** - * Program to implement Kadane’s Algorithm to - * calculate maximum contiguous subarray sum of an array + * Program to implement Kadane’s Algorithm to calculate maximum contiguous subarray sum of an array * Time Complexity: O(n) * * @author Nishita Aggarwal */ - public class KadaneAlgorithm { - /** - * This method implements Kadane's Algorithm - * - * @param arr The input array - * @return The maximum contiguous subarray sum of the array - */ - static int largestContiguousSum(int arr[]) { - int i, len = arr.length, cursum = 0, maxsum = Integer.MIN_VALUE; - if (len == 0) //empty array - return 0; - for (i = 0; i < len; i++) { - cursum += arr[i]; - if (cursum > maxsum) { - maxsum = cursum; - } - if (cursum <= 0) { - cursum = 0; - } - } - return maxsum; + /** + * This method implements Kadane's Algorithm + * + * @param arr The input array + * @return The maximum contiguous subarray sum of the array + */ + static int largestContiguousSum(int arr[]) { + int i, len = arr.length, cursum = 0, maxsum = Integer.MIN_VALUE; + if (len == 0) // empty array + return 0; + for (i = 0; i < len; i++) { + cursum += arr[i]; + if (cursum > maxsum) { + maxsum = cursum; + } + if (cursum <= 0) { + cursum = 0; + } } + return maxsum; + } - /** - * Main method - * - * @param args Command line arguments - */ - public static void main(String[] args) { - Scanner sc = new Scanner(System.in); - int n, arr[], i; - n = sc.nextInt(); - arr = new int[n]; - for (i = 0; i < n; i++) { - arr[i] = sc.nextInt(); - } - int maxContSum = largestContiguousSum(arr); - System.out.println(maxContSum); - sc.close(); + /** + * Main method + * + * @param args Command line arguments + */ + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + int n, arr[], i; + n = sc.nextInt(); + arr = new int[n]; + for (i = 0; i < n; i++) { + arr[i] = sc.nextInt(); } - + int maxContSum = largestContiguousSum(arr); + System.out.println(maxContSum); + sc.close(); + } } diff --git a/DynamicProgramming/Knapsack.java b/DynamicProgramming/Knapsack.java index 1652dc63b14d..e49022e0ba56 100644 --- a/DynamicProgramming/Knapsack.java +++ b/DynamicProgramming/Knapsack.java @@ -1,39 +1,32 @@ package DynamicProgramming; -/** - * A DynamicProgramming based solution for 0-1 Knapsack problem - */ - +/** A DynamicProgramming based solution for 0-1 Knapsack problem */ public class Knapsack { - private static int knapSack(int W, int wt[], int val[], int n) throws IllegalArgumentException { - if(wt == null || val == null) - throw new IllegalArgumentException(); - int i, w; - int rv[][] = new int[n + 1][W + 1]; //rv means return value - - // Build table rv[][] in bottom up manner - for (i = 0; i <= n; i++) { - for (w = 0; w <= W; w++) { - if (i == 0 || w == 0) - rv[i][w] = 0; - else if (wt[i - 1] <= w) - rv[i][w] = Math.max(val[i - 1] + rv[i - 1][w - wt[i - 1]], rv[i - 1][w]); - else - rv[i][w] = rv[i - 1][w]; - } - } + private static int knapSack(int W, int wt[], int val[], int n) throws IllegalArgumentException { + if (wt == null || val == null) throw new IllegalArgumentException(); + int i, w; + int rv[][] = new int[n + 1][W + 1]; // rv means return value - return rv[n][W]; + // Build table rv[][] in bottom up manner + for (i = 0; i <= n; i++) { + for (w = 0; w <= W; w++) { + if (i == 0 || w == 0) rv[i][w] = 0; + else if (wt[i - 1] <= w) + rv[i][w] = Math.max(val[i - 1] + rv[i - 1][w - wt[i - 1]], rv[i - 1][w]); + else rv[i][w] = rv[i - 1][w]; + } } + return rv[n][W]; + } - // Driver program to test above function - public static void main(String args[]) { - int val[] = new int[]{50, 100, 130}; - int wt[] = new int[]{10, 20, 40}; - int W = 50; - int n = val.length; - System.out.println(knapSack(W, wt, val, n)); - } + // Driver program to test above function + public static void main(String args[]) { + int val[] = new int[] {50, 100, 130}; + int wt[] = new int[] {10, 20, 40}; + int W = 50; + int n = val.length; + System.out.println(knapSack(W, wt, val, n)); + } } diff --git a/DynamicProgramming/LevenshteinDistance.java b/DynamicProgramming/LevenshteinDistance.java index c4d53143f80b..c18d24f3f7a0 100644 --- a/DynamicProgramming/LevenshteinDistance.java +++ b/DynamicProgramming/LevenshteinDistance.java @@ -1,56 +1,52 @@ package DynamicProgramming; /** - * @author Kshitij VERMA (github.com/kv19971) - * LEVENSHTEIN DISTANCE dyamic programming implementation to show the difference between two strings (https://en.wikipedia.org/wiki/Levenshtein_distance) + * @author Kshitij VERMA (github.com/kv19971) LEVENSHTEIN DISTANCE dyamic programming implementation + * to show the difference between two strings + * (https://en.wikipedia.org/wiki/Levenshtein_distance) */ - public class LevenshteinDistance { - private static int minimum(int a, int b, int c) { - if (a < b && a < c) { - return a; - } else if (b < a && b < c) { - return b; - } else { - return c; - } + private static int minimum(int a, int b, int c) { + if (a < b && a < c) { + return a; + } else if (b < a && b < c) { + return b; + } else { + return c; } - - private static int calculate_distance(String a, String b) { - int len_a = a.length() + 1; - int len_b = b.length() + 1; - int[][] distance_mat = new int[len_a][len_b]; - for (int i = 0; i < len_a; i++) { - distance_mat[i][0] = i; - } - for (int j = 0; j < len_b; j++) { - distance_mat[0][j] = j; - } - for (int i = 0; i < len_a; i++) { - for (int j = 0; j < len_b; j++) { - int cost; - if (a.charAt(i) == b.charAt(j)) { - cost = 0; - } else { - cost = 1; - } - distance_mat[i][j] = minimum(distance_mat[i - 1][j], distance_mat[i - 1][j - 1], distance_mat[i][j - 1]) + cost; - - - } - + } + + private static int calculate_distance(String a, String b) { + int len_a = a.length() + 1; + int len_b = b.length() + 1; + int[][] distance_mat = new int[len_a][len_b]; + for (int i = 0; i < len_a; i++) { + distance_mat[i][0] = i; + } + for (int j = 0; j < len_b; j++) { + distance_mat[0][j] = j; + } + for (int i = 0; i < len_a; i++) { + for (int j = 0; j < len_b; j++) { + int cost; + if (a.charAt(i) == b.charAt(j)) { + cost = 0; + } else { + cost = 1; } - return distance_mat[len_a - 1][len_b - 1]; - + distance_mat[i][j] = + minimum(distance_mat[i - 1][j], distance_mat[i - 1][j - 1], distance_mat[i][j - 1]) + + cost; + } } + return distance_mat[len_a - 1][len_b - 1]; + } - public static void main(String[] args) { - String a = ""; // enter your string here - String b = ""; // enter your string here - - System.out.print("Levenshtein distance between " + a + " and " + b + " is: "); - System.out.println(calculate_distance(a, b)); + public static void main(String[] args) { + String a = ""; // enter your string here + String b = ""; // enter your string here - - } + System.out.print("Levenshtein distance between " + a + " and " + b + " is: "); + System.out.println(calculate_distance(a, b)); + } } diff --git a/DynamicProgramming/LongestCommonSubsequence.java b/DynamicProgramming/LongestCommonSubsequence.java index fad223748bdd..f39587010f14 100644 --- a/DynamicProgramming/LongestCommonSubsequence.java +++ b/DynamicProgramming/LongestCommonSubsequence.java @@ -2,67 +2,63 @@ class LongestCommonSubsequence { - public static String getLCS(String str1, String str2) { + 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 null + if (str1 == null || str2 == null) return null; - //At least one string is empty - if (str1.length() == 0 || str2.length() == 0) - return ""; + // At least one string is empty + if (str1.length() == 0 || str2.length() == 0) return ""; - String[] arr1 = str1.split(""); - String[] arr2 = str2.split(""); + 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]; + // 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]; - } - } + 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); + } } + 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 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); + 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()); - } + // 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 + } +} diff --git a/DynamicProgramming/LongestIncreasingSubsequence.java b/DynamicProgramming/LongestIncreasingSubsequence.java index e30adfeffd39..06885fbdd463 100644 --- a/DynamicProgramming/LongestIncreasingSubsequence.java +++ b/DynamicProgramming/LongestIncreasingSubsequence.java @@ -2,64 +2,58 @@ import java.util.Scanner; -/** - * @author Afrizal Fikri (https://github.com/icalF) - */ +/** @author Afrizal Fikri (https://github.com/icalF) */ public class LongestIncreasingSubsequence { - public static void main(String[] args) { + public static void main(String[] args) { - Scanner sc = new Scanner(System.in); - int n = sc.nextInt(); + Scanner sc = new Scanner(System.in); + int n = sc.nextInt(); - int ar[] = new int[n]; - for (int i = 0; i < n; i++) { - ar[i] = sc.nextInt(); - } - - System.out.println(LIS(ar)); - sc.close(); + int ar[] = new int[n]; + for (int i = 0; i < n; i++) { + ar[i] = sc.nextInt(); } - private static int upperBound(int[] ar, int l, int r, int key) { - while (l < r - 1) { - int m = (l + r) >>> 1; - if (ar[m] >= key) - r = m; - else - l = m; - } + System.out.println(LIS(ar)); + sc.close(); + } - return r; + private static int upperBound(int[] ar, int l, int r, int key) { + while (l < r - 1) { + int m = (l + r) >>> 1; + if (ar[m] >= key) r = m; + else l = m; } - private static int LIS(int[] array) { - int N = array.length; - if (N == 0) - return 0; + return r; + } - int[] tail = new int[N]; + private static int LIS(int[] array) { + int N = array.length; + if (N == 0) return 0; - // always points empty slot in tail - int length = 1; + int[] tail = new int[N]; - tail[0] = array[0]; - for (int i = 1; i < N; i++) { + // always points empty slot in tail + int length = 1; - // new smallest value - if (array[i] < tail[0]) - tail[0] = array[i]; + tail[0] = array[0]; + for (int i = 1; i < N; i++) { - // array[i] extends largest subsequence - else if (array[i] > tail[length - 1]) - tail[length++] = array[i]; + // new smallest value + if (array[i] < tail[0]) tail[0] = array[i]; - // array[i] will become end candidate of an existing subsequence or - // Throw away larger elements in all LIS, to make room for upcoming grater elements than array[i] - // (and also, array[i] would have already appeared in one of LIS, identify the location and replace it) - else - tail[upperBound(tail, -1, length - 1, array[i])] = array[i]; - } + // array[i] extends largest subsequence + else if (array[i] > tail[length - 1]) tail[length++] = array[i]; - return length; + // array[i] will become end candidate of an existing subsequence or + // Throw away larger elements in all LIS, to make room for upcoming grater elements than + // array[i] + // (and also, array[i] would have already appeared in one of LIS, identify the location and + // replace it) + else tail[upperBound(tail, -1, length - 1, array[i])] = array[i]; } -} \ No newline at end of file + + return length; + } +} diff --git a/DynamicProgramming/LongestPalindromicSubsequence.java b/DynamicProgramming/LongestPalindromicSubsequence.java index 53ea6a794519..a7a62891cf54 100644 --- a/DynamicProgramming/LongestPalindromicSubsequence.java +++ b/DynamicProgramming/LongestPalindromicSubsequence.java @@ -1,57 +1,62 @@ package test; -import java.lang.*; -import java.io.*; -import java.util.*; - + +import java.io.*; +import java.util.*; + /** * Algorithm explanation https://www.educative.io/edpresso/longest-palindromic-subsequence-algorithm */ public class LongestPalindromicSubsequence { - public static void main(String[] args) { - String a = "BBABCBCAB"; - String b = "BABCBAB"; + public static void main(String[] args) { + String a = "BBABCBCAB"; + String b = "BABCBAB"; - String aLPS = LPS(a); - String bLPS = LPS(b); + String aLPS = LPS(a); + String bLPS = LPS(b); - System.out.println(a + " => " + aLPS); - System.out.println(b + " => " + bLPS); - } + System.out.println(a + " => " + aLPS); + System.out.println(b + " => " + bLPS); + } - public static String LPS(String original) throws IllegalArgumentException { - StringBuilder reverse = new StringBuilder(original); - reverse = reverse.reverse(); - return recursiveLPS(original, reverse.toString()); - } + public static String LPS(String original) throws IllegalArgumentException { + StringBuilder reverse = new StringBuilder(original); + reverse = reverse.reverse(); + return recursiveLPS(original, reverse.toString()); + } + + private static String recursiveLPS(String original, String reverse) { + String bestResult = ""; - private static String recursiveLPS(String original, String reverse) { - String bestResult = ""; - - //no more chars, then return empty - if(original.length() == 0 || reverse.length() == 0) { - bestResult = ""; + // no more chars, then return empty + if (original.length() == 0 || reverse.length() == 0) { + bestResult = ""; + } else { + + // if the last chars match, then remove it from both strings and recur + if (original.charAt(original.length() - 1) == reverse.charAt(reverse.length() - 1)) { + String bestSubResult = + recursiveLPS( + original.substring(0, original.length() - 1), + reverse.substring(0, reverse.length() - 1)); + + bestResult = reverse.charAt(reverse.length() - 1) + bestSubResult; + } else { + // otherwise (1) ignore the last character of reverse, and recur on original and updated + // reverse again + // (2) ignore the last character of original and recur on the updated original and reverse + // again + // then select the best result from these two subproblems. + + String bestSubResult1 = recursiveLPS(original, reverse.substring(0, reverse.length() - 1)); + String bestSubResult2 = recursiveLPS(original.substring(0, original.length() - 1), reverse); + if (bestSubResult1.length() > bestSubResult2.length()) { + bestResult = bestSubResult1; } else { - - //if the last chars match, then remove it from both strings and recur - if(original.charAt(original.length() - 1) == reverse.charAt(reverse.length() - 1)) { - String bestSubResult = recursiveLPS(original.substring(0, original.length() - 1), reverse.substring(0, reverse.length() - 1)); - - bestResult = reverse.charAt(reverse.length() - 1) + bestSubResult; - } else { - //otherwise (1) ignore the last character of reverse, and recur on original and updated reverse again - //(2) ignore the last character of original and recur on the updated original and reverse again - //then select the best result from these two subproblems. - - String bestSubResult1 = recursiveLPS(original, reverse.substring(0, reverse.length() - 1)); - String bestSubResult2 = recursiveLPS(original.substring(0, original.length() - 1), reverse); - if(bestSubResult1.length()>bestSubResult2.length()) { - bestResult = bestSubResult1; - } else { - bestResult = bestSubResult2; - } - } + bestResult = bestSubResult2; } - - return bestResult; + } } -} \ No newline at end of file + + return bestResult; + } +} diff --git a/DynamicProgramming/LongestValidParentheses.java b/DynamicProgramming/LongestValidParentheses.java index bc5f18ae0593..3bae80acae32 100644 --- a/DynamicProgramming/LongestValidParentheses.java +++ b/DynamicProgramming/LongestValidParentheses.java @@ -3,59 +3,56 @@ import java.util.Scanner; /** - * Given a string containing just the characters '(' and ')', find the length of - * the longest valid (well-formed) parentheses substring. + * Given a string containing just the characters '(' and ')', find the length of the longest valid + * (well-formed) parentheses substring. * * @author Libin Yang (https://github.com/yanglbme) * @since 2018/10/5 */ - public class LongestValidParentheses { - public static int getLongestValidParentheses(String s) { - if (s == null || s.length() < 2) { - return 0; - } - char[] chars = s.toCharArray(); - int n = chars.length; - int[] res = new int[n]; - res[0] = 0; - res[1] = chars[1] == ')' && chars[0] == '(' ? 2 : 0; - - int max = res[1]; - - for (int i = 2; i < n; ++i) { - if (chars[i] == ')') { - if (chars[i - 1] == '(') { - res[i] = res[i - 2] + 2; - } else { - int index = i - res[i - 1] - 1; - if (index >= 0 && chars[index] == '(') { - // ()(()) - res[i] = res[i - 1] + 2 + (index - 1 >= 0 ? res[index - 1] : 0); - } - } - } - max = Math.max(max, res[i]); + public static int getLongestValidParentheses(String s) { + if (s == null || s.length() < 2) { + return 0; + } + char[] chars = s.toCharArray(); + int n = chars.length; + int[] res = new int[n]; + res[0] = 0; + res[1] = chars[1] == ')' && chars[0] == '(' ? 2 : 0; + + int max = res[1]; + + for (int i = 2; i < n; ++i) { + if (chars[i] == ')') { + if (chars[i - 1] == '(') { + res[i] = res[i - 2] + 2; + } else { + int index = i - res[i - 1] - 1; + if (index >= 0 && chars[index] == '(') { + // ()(()) + res[i] = res[i - 1] + 2 + (index - 1 >= 0 ? res[index - 1] : 0); + } } - - return max; - + } + max = Math.max(max, res[i]); } - public static void main(String[] args) { - Scanner sc = new Scanner(System.in); - - while (true) { - String str = sc.nextLine(); - if ("quit".equals(str)) { - break; - } - int len = getLongestValidParentheses(str); - System.out.println(len); + return max; + } - } + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); - sc.close(); + while (true) { + String str = sc.nextLine(); + if ("quit".equals(str)) { + break; + } + int len = getLongestValidParentheses(str); + System.out.println(len); } + + sc.close(); + } } diff --git a/DynamicProgramming/MatrixChainMultiplication.java b/DynamicProgramming/MatrixChainMultiplication.java index 9073400d3299..9a17fe815fa1 100644 --- a/DynamicProgramming/MatrixChainMultiplication.java +++ b/DynamicProgramming/MatrixChainMultiplication.java @@ -5,132 +5,131 @@ import java.util.Scanner; public class MatrixChainMultiplication { - private static Scanner scan = new Scanner(System.in); - private static ArrayList mArray = new ArrayList<>(); - private static int size; - private static int[][] m; - private static int[][] s; - private static int[] p; - - public static void main(String[] args) { - int count = 1; - while (true) { - String[] mSize = input("input size of matrix A(" + count + ") ( ex. 10 20 ) : "); - int col = Integer.parseInt(mSize[0]); - if (col == 0) break; - int row = Integer.parseInt(mSize[1]); - - Matrix matrix = new Matrix(count, col, row); - mArray.add(matrix); - count++; - } - for (Matrix m : mArray) { - System.out.format("A(%d) = %2d x %2d%n", m.count(), m.col(), m.row()); - } - - size = mArray.size(); - m = new int[size + 1][size + 1]; - s = new int[size + 1][size + 1]; - p = new int[size + 1]; - - for (int i = 0; i < size + 1; i++) { - Arrays.fill(m[i], -1); - Arrays.fill(s[i], -1); - } - - for (int i = 0; i < p.length; i++) { - p[i] = i == 0 ? mArray.get(i).col() : mArray.get(i - 1).row(); - } + private static Scanner scan = new Scanner(System.in); + private static ArrayList mArray = new ArrayList<>(); + private static int size; + private static int[][] m; + private static int[][] s; + private static int[] p; + + public static void main(String[] args) { + int count = 1; + while (true) { + String[] mSize = input("input size of matrix A(" + count + ") ( ex. 10 20 ) : "); + int col = Integer.parseInt(mSize[0]); + if (col == 0) break; + int row = Integer.parseInt(mSize[1]); + + Matrix matrix = new Matrix(count, col, row); + mArray.add(matrix); + count++; + } + for (Matrix m : mArray) { + System.out.format("A(%d) = %2d x %2d%n", m.count(), m.col(), m.row()); + } - matrixChainOrder(); - for (int i = 0; i < size; i++) { - System.out.print("-------"); - } - System.out.println(); - printArray(m); - for (int i = 0; i < size; i++) { - System.out.print("-------"); - } - System.out.println(); - printArray(s); - for (int i = 0; i < size; i++) { - System.out.print("-------"); - } - System.out.println(); + size = mArray.size(); + m = new int[size + 1][size + 1]; + s = new int[size + 1][size + 1]; + p = new int[size + 1]; - System.out.println("Optimal solution : " + m[1][size]); - System.out.print("Optimal parens : "); - printOptimalParens(1, size); + for (int i = 0; i < size + 1; i++) { + Arrays.fill(m[i], -1); + Arrays.fill(s[i], -1); } - private static void printOptimalParens(int i, int j) { - if (i == j) { - System.out.print("A" + i); - } else { - System.out.print("("); - printOptimalParens(i, s[i][j]); - printOptimalParens(s[i][j] + 1, j); - System.out.print(")"); - } + for (int i = 0; i < p.length; i++) { + p[i] = i == 0 ? mArray.get(i).col() : mArray.get(i - 1).row(); } - private static void printArray(int[][] array) { - for (int i = 1; i < size + 1; i++) { - for (int j = 1; j < size + 1; j++) { - System.out.print(String.format("%7d", array[i][j])); - } - System.out.println(); - } + matrixChainOrder(); + for (int i = 0; i < size; i++) { + System.out.print("-------"); } - - private static void matrixChainOrder() { - for (int i = 1; i < size + 1; i++) { - m[i][i] = 0; - } - - for (int l = 2; l < size + 1; l++) { - for (int i = 1; i < size - l + 2; i++) { - int j = i + l - 1; - m[i][j] = Integer.MAX_VALUE; - - for (int k = i; k < j; k++) { - int q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j]; - if (q < m[i][j]) { - m[i][j] = q; - s[i][j] = k; - } - } - } - } + System.out.println(); + printArray(m); + for (int i = 0; i < size; i++) { + System.out.print("-------"); } - - private static String[] input(String string) { - System.out.print(string); - return (scan.nextLine().split(" ")); + System.out.println(); + printArray(s); + for (int i = 0; i < size; i++) { + System.out.print("-------"); } - -} - -class Matrix { - private int count; - private int col; - private int row; - - Matrix(int count, int col, int row) { - this.count = count; - this.col = col; - this.row = row; + System.out.println(); + + System.out.println("Optimal solution : " + m[1][size]); + System.out.print("Optimal parens : "); + printOptimalParens(1, size); + } + + private static void printOptimalParens(int i, int j) { + if (i == j) { + System.out.print("A" + i); + } else { + System.out.print("("); + printOptimalParens(i, s[i][j]); + printOptimalParens(s[i][j] + 1, j); + System.out.print(")"); } - - int count() { - return count; + } + + private static void printArray(int[][] array) { + for (int i = 1; i < size + 1; i++) { + for (int j = 1; j < size + 1; j++) { + System.out.print(String.format("%7d", array[i][j])); + } + System.out.println(); } + } - int col() { - return col; + private static void matrixChainOrder() { + for (int i = 1; i < size + 1; i++) { + m[i][i] = 0; } - int row() { - return row; + for (int l = 2; l < size + 1; l++) { + for (int i = 1; i < size - l + 2; i++) { + int j = i + l - 1; + m[i][j] = Integer.MAX_VALUE; + + for (int k = i; k < j; k++) { + int q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j]; + if (q < m[i][j]) { + m[i][j] = q; + s[i][j] = k; + } + } + } } + } + + private static String[] input(String string) { + System.out.print(string); + return (scan.nextLine().split(" ")); + } +} + +class Matrix { + private int count; + private int col; + private int row; + + Matrix(int count, int col, int row) { + this.count = count; + this.col = col; + this.row = row; + } + + int count() { + return count; + } + + int col() { + return col; + } + + int row() { + return row; + } } diff --git a/DynamicProgramming/MinimumSumPartition.java b/DynamicProgramming/MinimumSumPartition.java index e0fb5296f4b4..745d22a1b5cf 100644 --- a/DynamicProgramming/MinimumSumPartition.java +++ b/DynamicProgramming/MinimumSumPartition.java @@ -1,12 +1,12 @@ package DynamicProgramming; // Partition a set into two subsets such that the difference of subset sums is minimum -/* -Input: arr[] = {1, 6, 11, 5} +/* +Input: arr[] = {1, 6, 11, 5} Output: 1 Explanation: -Subset1 = {1, 5, 6}, sum of Subset1 = 12 -Subset2 = {11}, sum of Subset2 = 11 +Subset1 = {1, 5, 6}, sum of Subset1 = 12 +Subset2 = {11}, sum of Subset2 = 11 Input: arr[] = {36, 7, 46, 40} Output: 23 @@ -15,78 +15,75 @@ Subset2 = {36, 40} ; sum of Subset2 = 76 */ -import java.util.*; -import java.lang.*; import java.io.*; -public class MinimumSumPartition -{ - public static int subSet(int[] arr) { - int n = arr.length; - int sum = getSum(arr); - boolean[][] dp = new boolean[n + 1][sum + 1]; - for (int i = 0; i <= n; i++) { - dp[i][0] = true; - } - for (int j = 0; j <= sum; j++) { - dp[0][j] = false; - } +import java.util.*; - //fill dp array - for (int i = 1; i <= n; i++) { - for (int j = 1; j <= sum; j++) { - if (arr[i - 1] < j) { - dp[i][j] = dp[i - 1][j - arr[i - 1]] || dp[i - 1][j]; - } else if (arr[i - 1] == j) { - dp[i][j] = true; - } else { - dp[i][j] = dp[i - 1][j]; - } - } - } +public class MinimumSumPartition { + public static int subSet(int[] arr) { + int n = arr.length; + int sum = getSum(arr); + boolean[][] dp = new boolean[n + 1][sum + 1]; + for (int i = 0; i <= n; i++) { + dp[i][0] = true; + } + for (int j = 0; j <= sum; j++) { + dp[0][j] = false; + } - // fill the index array - int[] index = new int[sum]; - int p = 0; - for (int i = 0; i <= sum / 2; i++) { - if (dp[n][i]) { - index[p++] = i; - } + // fill dp array + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= sum; j++) { + if (arr[i - 1] < j) { + dp[i][j] = dp[i - 1][j - arr[i - 1]] || dp[i - 1][j]; + } else if (arr[i - 1] == j) { + dp[i][j] = true; + } else { + dp[i][j] = dp[i - 1][j]; } - - return getMin(index, sum); + } } - /** - * Calculate sum of array elements - * - * @param arr the array - * @return sum of given array - */ - public static int getSum(int[] arr) { - int sum = 0; - for (int temp : arr) { - sum += temp; - } - return sum; + // fill the index array + int[] index = new int[sum]; + int p = 0; + for (int i = 0; i <= sum / 2; i++) { + if (dp[n][i]) { + index[p++] = i; + } } - public static int getMin(int[] arr, int sum) { - if (arr.length == 0) { - return 0; - } - int min = Integer.MAX_VALUE; - for (int temp : arr) { - min = Math.min(min, sum - 2 * temp); - } - return min; + return getMin(index, sum); + } + + /** + * Calculate sum of array elements + * + * @param arr the array + * @return sum of given array + */ + public static int getSum(int[] arr) { + int sum = 0; + for (int temp : arr) { + sum += temp; } + return sum; + } - /** - * Driver Code - */ - public static void main(String[] args) { - assert subSet(new int[]{1, 6, 11,5}) == 1; - assert subSet(new int[]{36, 7, 46, 40}) == 23; - assert subSet(new int[]{1, 2, 3, 9}) == 3; + public static int getMin(int[] arr, int sum) { + if (arr.length == 0) { + return 0; + } + int min = Integer.MAX_VALUE; + for (int temp : arr) { + min = Math.min(min, sum - 2 * temp); } + return min; + } + + /** Driver Code */ + public static void main(String[] args) { + assert subSet(new int[] {1, 6, 11, 5}) == 1; + assert subSet(new int[] {36, 7, 46, 40}) == 23; + assert subSet(new int[] {1, 2, 3, 9}) == 3; + } } diff --git a/DynamicProgramming/RodCutting.java b/DynamicProgramming/RodCutting.java index 0913dfd80b1f..8a3242a05dbf 100644 --- a/DynamicProgramming/RodCutting.java +++ b/DynamicProgramming/RodCutting.java @@ -1,33 +1,30 @@ package DynamicProgramming; /** - * A DynamicProgramming solution for Rod cutting problem - * Returns the best obtainable price for a rod of - * length n and price[] as prices of different pieces + * A DynamicProgramming solution for Rod cutting problem Returns the best obtainable price for a rod + * of length n and price[] as prices of different pieces */ public class RodCutting { - private static int cutRod(int[] price, int n) { - int val[] = new int[n + 1]; - val[0] = 0; + private static int cutRod(int[] price, int n) { + int val[] = new int[n + 1]; + val[0] = 0; - for (int i = 1; i <= n; i++) { - int max_val = Integer.MIN_VALUE; - for (int j = 0; j < i; j++) - max_val = Math.max(max_val, price[j] + val[i - j - 1]); + for (int i = 1; i <= n; i++) { + int max_val = Integer.MIN_VALUE; + for (int j = 0; j < i; j++) max_val = Math.max(max_val, price[j] + val[i - j - 1]); - val[i] = max_val; - } - - return val[n]; + val[i] = max_val; } - // main function to test - public static void main(String args[]) { - int[] arr = new int[]{2, 5, 13, 19, 20}; - int size = arr.length; - int result = cutRod(arr,size); - System.out.println("Maximum Obtainable Value is " + - result); - } + return val[n]; + } + + // main function to test + public static void main(String args[]) { + int[] arr = new int[] {2, 5, 13, 19, 20}; + int size = arr.length; + int result = cutRod(arr, size); + System.out.println("Maximum Obtainable Value is " + result); + } } diff --git a/DynamicProgramming/SubsetSum.java b/DynamicProgramming/SubsetSum.java index 18a357248720..2e97ffb18042 100644 --- a/DynamicProgramming/SubsetSum.java +++ b/DynamicProgramming/SubsetSum.java @@ -2,45 +2,43 @@ public class SubsetSum { - /** - * Driver Code - */ - public static void main(String[] args) { - int[] arr = new int[]{50, 4, 10, 15, 34}; - assert subsetSum(arr, 64); /* 4 + 10 + 15 + 34 = 64 */ - assert subsetSum(arr, 99); /* 50 + 15 + 34 = 99 */ - assert !subsetSum(arr, 5); - assert !subsetSum(arr, 66); - } + /** Driver Code */ + public static void main(String[] args) { + int[] arr = new int[] {50, 4, 10, 15, 34}; + assert subsetSum(arr, 64); /* 4 + 10 + 15 + 34 = 64 */ + assert subsetSum(arr, 99); /* 50 + 15 + 34 = 99 */ + assert !subsetSum(arr, 5); + assert !subsetSum(arr, 66); + } - /** - * Test if a set of integers contains a subset that sum to a given integer. - * - * @param arr the array contains integers. - * @param sum target sum of subset. - * @return {@code true} if subset exists, otherwise {@code false}. - */ - private static boolean subsetSum(int[] arr, int sum) { - int n = arr.length; - boolean[][] isSum = new boolean[n + 2][sum + 1]; + /** + * Test if a set of integers contains a subset that sum to a given integer. + * + * @param arr the array contains integers. + * @param sum target sum of subset. + * @return {@code true} if subset exists, otherwise {@code false}. + */ + private static boolean subsetSum(int[] arr, int sum) { + int n = arr.length; + boolean[][] isSum = new boolean[n + 2][sum + 1]; - isSum[n + 1][0] = true; - for (int i = 1; i <= sum; i++) { - isSum[n + 1][i] = false; - } + isSum[n + 1][0] = true; + for (int i = 1; i <= sum; i++) { + isSum[n + 1][i] = false; + } - for (int i = n; i > 0; i--) { - isSum[i][0] = true; - for (int j = 1; j <= arr[i - 1] - 1; j++) { - if (j <= sum) { - isSum[i][j] = isSum[i + 1][j]; - } - } - for (int j = arr[i - 1]; j <= sum; j++) { - isSum[i][j] = (isSum[i + 1][j] || isSum[i + 1][j - arr[i - 1]]); - } + for (int i = n; i > 0; i--) { + isSum[i][0] = true; + for (int j = 1; j <= arr[i - 1] - 1; j++) { + if (j <= sum) { + isSum[i][j] = isSum[i + 1][j]; } - - return isSum[1][sum]; + } + for (int j = arr[i - 1]; j <= sum; j++) { + isSum[i][j] = (isSum[i + 1][j] || isSum[i + 1][j - arr[i - 1]]); + } } -} \ No newline at end of file + + return isSum[1][sum]; + } +} diff --git a/Maths/AbsoluteMax.java b/Maths/AbsoluteMax.java index 05aa653bd43e..fe1376232322 100644 --- a/Maths/AbsoluteMax.java +++ b/Maths/AbsoluteMax.java @@ -4,32 +4,31 @@ /** * description: - *

- * absMax([0, 5, 1, 11]) = 11, absMax([3 , -10, -2]) = -10 - *

+ * + *

absMax([0, 5, 1, 11]) = 11, absMax([3 , -10, -2]) = -10 */ public class AbsoluteMax { - public static void main(String[] args) { - int[] testnums = {-2, 0, 16}; - assert absMax(testnums) == 16; - - int[] numbers = {3, -10, -2}; - System.out.println("absMax(" + Arrays.toString(numbers) + ") = " + absMax(numbers)); - } + public static void main(String[] args) { + int[] testnums = {-2, 0, 16}; + assert absMax(testnums) == 16; + + int[] numbers = {3, -10, -2}; + System.out.println("absMax(" + Arrays.toString(numbers) + ") = " + absMax(numbers)); + } - /** - * get the value, return the absolute max value - * - * @param numbers contains elements - * @return the absolute max value - */ - public static int absMax(int[] numbers) { - int absMaxValue = numbers[0]; - for (int i = 1, length = numbers.length; i < length; ++i) { - if (Math.abs(numbers[i]) > Math.abs(absMaxValue)) { - absMaxValue = numbers[i]; - } - } - return absMaxValue; + /** + * get the value, return the absolute max value + * + * @param numbers contains elements + * @return the absolute max value + */ + public static int absMax(int[] numbers) { + int absMaxValue = numbers[0]; + for (int i = 1, length = numbers.length; i < length; ++i) { + if (Math.abs(numbers[i]) > Math.abs(absMaxValue)) { + absMaxValue = numbers[i]; + } } + return absMaxValue; + } } diff --git a/Maths/AbsoluteMin.java b/Maths/AbsoluteMin.java index 597944dca0a2..8e8c71fdbb29 100644 --- a/Maths/AbsoluteMin.java +++ b/Maths/AbsoluteMin.java @@ -4,32 +4,31 @@ /** * description: - *

- * absMin([0, 5, 1, 11]) = 0, absMin([3 , -10, -2]) = -2 - *

+ * + *

absMin([0, 5, 1, 11]) = 0, absMin([3 , -10, -2]) = -2 */ public class AbsoluteMin { - public static void main(String[] args) { - int[] testnums = {4, 0, 16}; - assert absMin(testnums) == 0; - - int[] numbers = {3, -10, -2}; - System.out.println("absMin(" + Arrays.toString(numbers) + ") = " + absMin(numbers)); - } + public static void main(String[] args) { + int[] testnums = {4, 0, 16}; + assert absMin(testnums) == 0; + + int[] numbers = {3, -10, -2}; + System.out.println("absMin(" + Arrays.toString(numbers) + ") = " + absMin(numbers)); + } - /** - * get the value, returns the absolute min value min - * - * @param numbers contains elements - * @return the absolute min value - */ - public static int absMin(int[] numbers) { - int absMinValue = numbers[0]; - for (int i = 1, length = numbers.length; i < length; ++i) { - if (Math.abs(numbers[i]) < Math.abs(absMinValue)) { - absMinValue = numbers[i]; - } - } - return absMinValue; + /** + * get the value, returns the absolute min value min + * + * @param numbers contains elements + * @return the absolute min value + */ + public static int absMin(int[] numbers) { + int absMinValue = numbers[0]; + for (int i = 1, length = numbers.length; i < length; ++i) { + if (Math.abs(numbers[i]) < Math.abs(absMinValue)) { + absMinValue = numbers[i]; + } } + return absMinValue; + } } diff --git a/Maths/AbsoluteValue.java b/Maths/AbsoluteValue.java index 440a7e230093..d465de67d4ff 100644 --- a/Maths/AbsoluteValue.java +++ b/Maths/AbsoluteValue.java @@ -4,24 +4,23 @@ public class AbsoluteValue { - public static void main(String[] args) { - Random random = new Random(); + public static void main(String[] args) { + Random random = new Random(); - /* test 1000 random numbers */ - for (int i = 1; i <= 1000; ++i) { - int randomNumber = random.nextInt(); - assert absVal(randomNumber) == Math.abs(randomNumber); - } - } - - /** - * If value is less than zero, make value positive. - * - * @param value a number - * @return the absolute value of a number - */ - public static int absVal(int value) { - return value < 0 ? -value : value; + /* test 1000 random numbers */ + for (int i = 1; i <= 1000; ++i) { + int randomNumber = random.nextInt(); + assert absVal(randomNumber) == Math.abs(randomNumber); } + } + /** + * If value is less than zero, make value positive. + * + * @param value a number + * @return the absolute value of a number + */ + public static int absVal(int value) { + return value < 0 ? -value : value; + } } diff --git a/Maths/AliquotSum.java b/Maths/AliquotSum.java index 28dbca41a7ff..09b7c730b159 100644 --- a/Maths/AliquotSum.java +++ b/Maths/AliquotSum.java @@ -1,35 +1,32 @@ package Maths; /** - *

- * In number theory, the aliquot sum s(n) of a positive integer n is the sum of all proper divisors of n, - * that is, all divisors of n other than n itself. - * For example, the proper divisors of 15 (that is, the positive divisors of 15 that are not equal to 15) - * are 1, 3 and 5, so the aliquot sum of 15 is 9 i.e. (1 + 3 + 5). - *

- * Wikipedia: https://en.wikipedia.org/wiki/Aliquot_sum + * In number theory, the aliquot sum s(n) of a positive integer n is the sum of all proper divisors + * of n, that is, all divisors of n other than n itself. For example, the proper divisors of 15 + * (that is, the positive divisors of 15 that are not equal to 15) are 1, 3 and 5, so the aliquot + * sum of 15 is 9 i.e. (1 + 3 + 5). Wikipedia: https://en.wikipedia.org/wiki/Aliquot_sum */ public class AliquotSum { - public static void main(String[] args) { - assert aliquotSum(1) == 0; - assert aliquotSum(6) == 6; - assert aliquotSum(15) == 9; - assert aliquotSum(19) == 1; - } + public static void main(String[] args) { + assert aliquotSum(1) == 0; + assert aliquotSum(6) == 6; + assert aliquotSum(15) == 9; + assert aliquotSum(19) == 1; + } - /** - * Finds the aliquot sum of an integer number - * - * @param number a positive integer - * @return aliquot sum of given {@code number} - */ - public static int aliquotSum(int number) { - int sum = 0; - for (int i = 1, limit = number / 2; i <= limit; ++i) { - if (number % i == 0) { - sum += i; - } - } - return sum; + /** + * Finds the aliquot sum of an integer number + * + * @param number a positive integer + * @return aliquot sum of given {@code number} + */ + public static int aliquotSum(int number) { + int sum = 0; + for (int i = 1, limit = number / 2; i <= limit; ++i) { + if (number % i == 0) { + sum += i; + } } + return sum; + } } diff --git a/Maths/AmicableNumber.java b/Maths/AmicableNumber.java index 1d81a393a6ff..4080ce6263a0 100644 --- a/Maths/AmicableNumber.java +++ b/Maths/AmicableNumber.java @@ -1,87 +1,87 @@ package Maths; /** - * Amicable numbers are two different numbers so related - * that the sum of the proper divisors of each is equal to the other number. - * (A proper divisor of a number is a positive factor of that number other than the number itself. - * For example, the proper divisors of 6 are 1, 2, and 3.) - * A pair of amicable numbers constitutes an aliquot sequence of period 2. - * It is unknown if there are infinitely many pairs of amicable numbers. - * * - *

- * * link: https://en.wikipedia.org/wiki/Amicable_numbers - * *

- *

- * Simple Example : (220,284) 220 is divisible by {1,2,4,5,10,11,20,22,44,55,110 } <- Sum = 284 - * 284 is divisible by -> 1,2,4,71,142 and the Sum of that is. Yes right you probably expected it 220 + * Amicable numbers are two different numbers so related that the sum of the proper divisors of each + * is equal to the other number. (A proper divisor of a number is a positive factor of that number + * other than the number itself. For example, the proper divisors of 6 are 1, 2, and 3.) A pair of + * amicable numbers constitutes an aliquot sequence of period 2. It is unknown if there are + * infinitely many pairs of amicable numbers. * + * + *

* link: https://en.wikipedia.org/wiki/Amicable_numbers * + * + *

Simple Example : (220,284) 220 is divisible by {1,2,4,5,10,11,20,22,44,55,110 } <- Sum = 284 + * 284 is divisible by -> 1,2,4,71,142 and the Sum of that is. Yes right you probably expected it + * 220 */ - public class AmicableNumber { - public static void main(String[] args) { + public static void main(String[] args) { - AmicableNumber.findAllInRange(1,3000); - /* Res -> Int Range of 1 till 3000there are 3Amicable_numbers These are 1: = ( 220,284) 2: = ( 1184,1210) - 3: = ( 2620,2924) So it worked */ + AmicableNumber.findAllInRange(1, 3000); + /* Res -> Int Range of 1 till 3000there are 3Amicable_numbers These are 1: = ( 220,284) 2: = ( 1184,1210) + 3: = ( 2620,2924) So it worked */ - } + } - /** - * @param startValue - * @param stopValue - * @return - */ - static void findAllInRange(int startValue, int stopValue) { + /** + * @param startValue + * @param stopValue + * @return + */ + static void findAllInRange(int startValue, int stopValue) { - /* the 2 for loops are to avoid to double check tuple. For example (200,100) and (100,200) is the same calculation - * also to avoid is to check the number with it self. a number with itself is always a AmicableNumber - * */ - StringBuilder res = new StringBuilder(); - int countofRes = 0; + /* the 2 for loops are to avoid to double check tuple. For example (200,100) and (100,200) is the same calculation + * also to avoid is to check the number with it self. a number with itself is always a AmicableNumber + * */ + StringBuilder res = new StringBuilder(); + int countofRes = 0; - for (int i = startValue; i < stopValue; i++) { - for (int j = i + 1; j <= stopValue; j++) { - if (isAmicableNumber(i, j)) { - countofRes++; - res.append("" + countofRes + ": = ( " + i + "," + j + ")" + "\t"); - } - } + for (int i = startValue; i < stopValue; i++) { + for (int j = i + 1; j <= stopValue; j++) { + if (isAmicableNumber(i, j)) { + countofRes++; + res.append("" + countofRes + ": = ( " + i + "," + j + ")" + "\t"); } - res.insert(0, "Int Range of " + startValue + " till " + stopValue + " there are " + countofRes + " Amicable_numbers.These are \n "); - System.out.println(res.toString()); + } } - - /** - * Check if {@code numberOne and numberTwo } are AmicableNumbers or not - * - * @param numberOne numberTwo - * @return {@code true} if {@code numberOne numberTwo} isAmicableNumbers otherwise false - */ - static boolean isAmicableNumber(int numberOne, int numberTwo) { - - return ((recursiveCalcOfDividerSum(numberOne, numberOne) == numberTwo && numberOne == recursiveCalcOfDividerSum(numberTwo, numberTwo))); - } - - /** - * calculated in recursive calls the Sum of all the Dividers beside it self - * - * @param number div = the next to test dividely by using the modulo operator - * @return sum of all the dividers - */ - static int recursiveCalcOfDividerSum(int number, int div) { - - if (div == 1) { - return 0; - } else if (number % --div == 0) { - return recursiveCalcOfDividerSum(number, div) + div; - } else { - return recursiveCalcOfDividerSum(number, div); - } + res.insert( + 0, + "Int Range of " + + startValue + + " till " + + stopValue + + " there are " + + countofRes + + " Amicable_numbers.These are \n "); + System.out.println(res.toString()); + } + + /** + * Check if {@code numberOne and numberTwo } are AmicableNumbers or not + * + * @param numberOne numberTwo + * @return {@code true} if {@code numberOne numberTwo} isAmicableNumbers otherwise false + */ + static boolean isAmicableNumber(int numberOne, int numberTwo) { + + return ((recursiveCalcOfDividerSum(numberOne, numberOne) == numberTwo + && numberOne == recursiveCalcOfDividerSum(numberTwo, numberTwo))); + } + + /** + * calculated in recursive calls the Sum of all the Dividers beside it self + * + * @param number div = the next to test dividely by using the modulo operator + * @return sum of all the dividers + */ + static int recursiveCalcOfDividerSum(int number, int div) { + + if (div == 1) { + return 0; + } else if (number % --div == 0) { + return recursiveCalcOfDividerSum(number, div) + div; + } else { + return recursiveCalcOfDividerSum(number, div); } - - - - - - + } } diff --git a/Maths/Area.java b/Maths/Area.java index 2faac63b21a4..ea1db120b779 100644 --- a/Maths/Area.java +++ b/Maths/Area.java @@ -1,119 +1,117 @@ package Maths; -/** - * Find the area of various geometric shapes - */ +/** Find the area of various geometric shapes */ public class Area { - public static void main(String[] args) { - - /* test cube */ - assert Double.compare(surfaceAreaCube(1), 6.0) == 0; - - /* test sphere */ - assert Double.compare(surfaceAreaSphere(5), 314.1592653589793) == 0; - assert Double.compare(surfaceAreaSphere(1), 12.566370614359172) == 0; - - /* test rectangle */ - assert Double.compare(surfaceAreaRectangle(10, 20), 200.0) == 0; - - /* test square */ - assert Double.compare(surfaceAreaSquare(10), 100.0) == 0; - - /* test triangle */ - assert Double.compare(surfaceAreaTriangle(10, 10), 50.0) == 0; - - /* test parallelogram */ - assert Double.compare(surfaceAreaParallelogram(10, 20), 200.0) == 0; - - /* test trapezium */ - assert Double.compare(surfaceAreaTrapezium(10, 20, 30), 450.0) == 0; - - /* test circle */ - assert Double.compare(surfaceAreaCircle(20), 1256.6370614359173) == 0; - } - - /** - * Calculate the surface area of a cube. - * - * @param sideLength side length of cube - * @return surface area of given cube - */ - private static double surfaceAreaCube(double sideLength) { - return 6 * sideLength * sideLength; - } - - /** - * Calculate the surface area of a sphere. - * - * @param radius radius of sphere - * @return surface area of given sphere - */ - private static double surfaceAreaSphere(double radius) { - return 4 * Math.PI * radius * radius; - } - - /** - * Calculate the area of a rectangle - * - * @param length length of rectangle - * @param width width of rectangle - * @return area of given rectangle - */ - private static double surfaceAreaRectangle(double length, double width) { - return length * width; - } - - /** - * Calculate the area of a square - * - * @param sideLength side length of square - * @return area of given square - */ - private static double surfaceAreaSquare(double sideLength) { - return sideLength * sideLength; - } - - /** - * Calculate the area of a triangle - * - * @param base base of triangle - * @param height height of triangle - * @return area of given triangle - */ - private static double surfaceAreaTriangle(double base, double height) { - return base * height / 2; - } - - /** - * Calculate the area of a parallelogram - * - * @param base base of parallelogram - * @param height height of parallelogram - * @return area of given parallelogram - */ - private static double surfaceAreaParallelogram(double base, double height) { - return base * height; - } - - /** - * Calculate the area of a trapezium - * - * @param base1 upper base of trapezium - * @param base2 bottom base of trapezium - * @param height height of trapezium - * @return area of given trapezium - */ - private static double surfaceAreaTrapezium(double base1, double base2, double height) { - return (base1 + base2) * height / 2; - } - - /** - * Calculate the area of a circle - * - * @param radius radius of circle - * @return area of given circle - */ - private static double surfaceAreaCircle(double radius) { - return Math.PI * radius * radius; - } -} \ No newline at end of file + public static void main(String[] args) { + + /* test cube */ + assert Double.compare(surfaceAreaCube(1), 6.0) == 0; + + /* test sphere */ + assert Double.compare(surfaceAreaSphere(5), 314.1592653589793) == 0; + assert Double.compare(surfaceAreaSphere(1), 12.566370614359172) == 0; + + /* test rectangle */ + assert Double.compare(surfaceAreaRectangle(10, 20), 200.0) == 0; + + /* test square */ + assert Double.compare(surfaceAreaSquare(10), 100.0) == 0; + + /* test triangle */ + assert Double.compare(surfaceAreaTriangle(10, 10), 50.0) == 0; + + /* test parallelogram */ + assert Double.compare(surfaceAreaParallelogram(10, 20), 200.0) == 0; + + /* test trapezium */ + assert Double.compare(surfaceAreaTrapezium(10, 20, 30), 450.0) == 0; + + /* test circle */ + assert Double.compare(surfaceAreaCircle(20), 1256.6370614359173) == 0; + } + + /** + * Calculate the surface area of a cube. + * + * @param sideLength side length of cube + * @return surface area of given cube + */ + private static double surfaceAreaCube(double sideLength) { + return 6 * sideLength * sideLength; + } + + /** + * Calculate the surface area of a sphere. + * + * @param radius radius of sphere + * @return surface area of given sphere + */ + private static double surfaceAreaSphere(double radius) { + return 4 * Math.PI * radius * radius; + } + + /** + * Calculate the area of a rectangle + * + * @param length length of rectangle + * @param width width of rectangle + * @return area of given rectangle + */ + private static double surfaceAreaRectangle(double length, double width) { + return length * width; + } + + /** + * Calculate the area of a square + * + * @param sideLength side length of square + * @return area of given square + */ + private static double surfaceAreaSquare(double sideLength) { + return sideLength * sideLength; + } + + /** + * Calculate the area of a triangle + * + * @param base base of triangle + * @param height height of triangle + * @return area of given triangle + */ + private static double surfaceAreaTriangle(double base, double height) { + return base * height / 2; + } + + /** + * Calculate the area of a parallelogram + * + * @param base base of parallelogram + * @param height height of parallelogram + * @return area of given parallelogram + */ + private static double surfaceAreaParallelogram(double base, double height) { + return base * height; + } + + /** + * Calculate the area of a trapezium + * + * @param base1 upper base of trapezium + * @param base2 bottom base of trapezium + * @param height height of trapezium + * @return area of given trapezium + */ + private static double surfaceAreaTrapezium(double base1, double base2, double height) { + return (base1 + base2) * height / 2; + } + + /** + * Calculate the area of a circle + * + * @param radius radius of circle + * @return area of given circle + */ + private static double surfaceAreaCircle(double radius) { + return Math.PI * radius * radius; + } +} diff --git a/Maths/Armstrong.java b/Maths/Armstrong.java index e1e10847376b..e41e85d062fd 100644 --- a/Maths/Armstrong.java +++ b/Maths/Armstrong.java @@ -1,43 +1,44 @@ package Maths; /** - * An Armstrong number is equal to the sum of the cubes of its digits. - * For example, 370 is an Armstrong number because 3*3*3 + 7*7*7 + 0*0*0 = 370. - * An Armstrong number is often called Narcissistic number. + * An Armstrong number is equal to the sum of the cubes of its digits. For example, 370 is an + * Armstrong number because 3*3*3 + 7*7*7 + 0*0*0 = 370. An Armstrong number is often called + * Narcissistic number. */ public class Armstrong { - public static void main(String[] args) { - assert (isArmStrong(0)); - assert (isArmStrong(1)); - assert (isArmStrong(153)); - assert (isArmStrong(1634)); - assert (isArmStrong(371)); - assert (!isArmStrong(200)); - } + public static void main(String[] args) { + assert (isArmStrong(0)); + assert (isArmStrong(1)); + assert (isArmStrong(153)); + assert (isArmStrong(1634)); + assert (isArmStrong(371)); + assert (!isArmStrong(200)); + } - /** - * Checks whether a given number is an armstrong number or not. - * - * @param number number to check - * @return {@code true} if given number is armstrong number, {@code false} otherwise - */ - private static boolean isArmStrong(int number) { - int sum = 0; - int temp = number; - int numberOfDigits = 0; - while (temp != 0) { - numberOfDigits++; - temp /= 10; - } - temp = number; /* copy number again */ - while (number > 0) { - int remainder = number % 10; - int power = 1; - for (int i = 1; i <= numberOfDigits; power *= remainder, ++i) ; - sum = sum + power; - number /= 10; - } - return sum == temp; + /** + * Checks whether a given number is an armstrong number or not. + * + * @param number number to check + * @return {@code true} if given number is armstrong number, {@code false} otherwise + */ + private static boolean isArmStrong(int number) { + int sum = 0; + int temp = number; + int numberOfDigits = 0; + while (temp != 0) { + numberOfDigits++; + temp /= 10; + } + temp = number; /* copy number again */ + while (number > 0) { + int remainder = number % 10; + int power = 1; + for (int i = 1; i <= numberOfDigits; power *= remainder, ++i) + ; + sum = sum + power; + number /= 10; } + return sum == temp; + } } diff --git a/Maths/Average.java b/Maths/Average.java index 9f4bb3af6b58..5c66569a642e 100644 --- a/Maths/Average.java +++ b/Maths/Average.java @@ -1,44 +1,42 @@ package Maths; -/** - * Calculate average of a list of numbers - */ +/** Calculate average of a list of numbers */ public class Average { - private static final double SMALL_VALUE = 0.00001f; - public static void main(String[] args) { - assert Math.abs(average(new double[]{3, 6, 9, 12, 15, 18, 21}) - 12) < SMALL_VALUE; - assert Math.abs(average(new double[]{5, 10, 15, 20, 25, 30, 35}) - 20) < SMALL_VALUE; - assert Math.abs(average(new double[]{1, 2, 3, 4, 5, 6, 7, 8}) - 4.5) < SMALL_VALUE; - int[] array = {2, 4, 10}; - assert average(array) == 5; - } + private static final double SMALL_VALUE = 0.00001f; + + public static void main(String[] args) { + assert Math.abs(average(new double[] {3, 6, 9, 12, 15, 18, 21}) - 12) < SMALL_VALUE; + assert Math.abs(average(new double[] {5, 10, 15, 20, 25, 30, 35}) - 20) < SMALL_VALUE; + assert Math.abs(average(new double[] {1, 2, 3, 4, 5, 6, 7, 8}) - 4.5) < SMALL_VALUE; + int[] array = {2, 4, 10}; + assert average(array) == 5; + } - /** - * Calculate average of a list of numbers - * - * @param numbers array to store numbers - * @return mean of given numbers - */ - public static double average(double[] numbers) { - double sum = 0; - for (double number : numbers) { - sum += number; - } - return sum / numbers.length; + /** + * Calculate average of a list of numbers + * + * @param numbers array to store numbers + * @return mean of given numbers + */ + public static double average(double[] numbers) { + double sum = 0; + for (double number : numbers) { + sum += number; } - - /** - * find average value of int array - * - * @param array the array contains element and the sum does not - * excess long value limit - * @return average value - */ - public static int average(int[] array) { - long sum = 0; - for (int i = 0 ; i < array.length; ++i) { - sum += array[i]; - } - return (int)(sum / array.length); + return sum / numbers.length; + } + + /** + * find average value of int array + * + * @param array the array contains element and the sum does not excess long value limit + * @return average value + */ + public static int average(int[] array) { + long sum = 0; + for (int i = 0; i < array.length; ++i) { + sum += array[i]; } -} \ No newline at end of file + return (int) (sum / array.length); + } +} diff --git a/Maths/Ceil.java b/Maths/Ceil.java index b6f08693617e..fd6d8300a4c9 100644 --- a/Maths/Ceil.java +++ b/Maths/Ceil.java @@ -3,27 +3,27 @@ import java.util.Random; public class Ceil { - public static void main(String[] args) { - Random random = new Random(); - for (int i = 1; i <= 1000; ++i) { - double randomNumber = random.nextDouble(); - assert ceil(randomNumber) == Math.ceil(randomNumber); - } + public static void main(String[] args) { + Random random = new Random(); + for (int i = 1; i <= 1000; ++i) { + double randomNumber = random.nextDouble(); + assert ceil(randomNumber) == Math.ceil(randomNumber); } + } - /** - * Returns the smallest (closest to negative infinity) - * - * @param number the number - * @return the smallest (closest to negative infinity) of given {@code number} - */ - public static double ceil(double number) { - if (number - (int) number == 0) { - return number; - } else if (number - (int) number > 0) { - return (int) (number + 1); - } else { - return (int) number; - } + /** + * Returns the smallest (closest to negative infinity) + * + * @param number the number + * @return the smallest (closest to negative infinity) of given {@code number} + */ + public static double ceil(double number) { + if (number - (int) number == 0) { + return number; + } else if (number - (int) number > 0) { + return (int) (number + 1); + } else { + return (int) number; } -} \ No newline at end of file + } +} diff --git a/Maths/Combinations.java b/Maths/Combinations.java index 4ff237bb362f..0fb2437c21f3 100644 --- a/Maths/Combinations.java +++ b/Maths/Combinations.java @@ -1,37 +1,35 @@ package Maths; -/** - * @see Combination - */ +/** @see Combination */ public class Combinations { - public static void main(String[] args) { - assert combinations(1, 1) == 1; - assert combinations(10, 5) == 252; - assert combinations(6, 3) == 20; - assert combinations(20, 5) == 15504; - } + public static void main(String[] args) { + assert combinations(1, 1) == 1; + assert combinations(10, 5) == 252; + assert combinations(6, 3) == 20; + assert combinations(20, 5) == 15504; + } - /** - * Calculate of factorial - * - * @param n the number - * @return factorial of given number - */ - public static long factorial(int n) { - if (n < 0) { - throw new IllegalArgumentException("number is negative"); - } - return n == 0 || n == 1 ? 1 : n * factorial(n - 1); + /** + * Calculate of factorial + * + * @param n the number + * @return factorial of given number + */ + public static long factorial(int n) { + if (n < 0) { + throw new IllegalArgumentException("number is negative"); } + return n == 0 || n == 1 ? 1 : n * factorial(n - 1); + } - /** - * Calculate combinations - * - * @param n first number - * @param k second number - * @return combinations of given {@code n} and {@code k} - */ - public static long combinations(int n, int k) { - return factorial(n) / (factorial(k) * factorial(n - k)); - } + /** + * Calculate combinations + * + * @param n first number + * @param k second number + * @return combinations of given {@code n} and {@code k} + */ + public static long combinations(int n, int k) { + return factorial(n) / (factorial(k) * factorial(n - k)); + } } diff --git a/Maths/Factorial.java b/Maths/Factorial.java index e1ce91f62f93..3bd2e74a4864 100644 --- a/Maths/Factorial.java +++ b/Maths/Factorial.java @@ -2,26 +2,27 @@ public class Factorial { - /* Driver Code */ - public static void main(String[] args) { - assert factorial(0) == 1; - assert factorial(1) == 1; - assert factorial(5) == 120; - assert factorial(10) == 3628800; - } + /* Driver Code */ + public static void main(String[] args) { + assert factorial(0) == 1; + assert factorial(1) == 1; + assert factorial(5) == 120; + assert factorial(10) == 3628800; + } - /** - * Calculate factorial N using iteration - * - * @param n the number - * @return the factorial of {@code n} - */ - public static long factorial(int n) { - if (n < 0) { - throw new IllegalArgumentException("number is negative"); - } - long factorial = 1; - for (int i = 1; i <= n; factorial *= i, ++i) ; - return factorial; + /** + * Calculate factorial N using iteration + * + * @param n the number + * @return the factorial of {@code n} + */ + public static long factorial(int n) { + if (n < 0) { + throw new IllegalArgumentException("number is negative"); } + long factorial = 1; + for (int i = 1; i <= n; factorial *= i, ++i) + ; + return factorial; + } } diff --git a/Maths/FactorialRecursion.java b/Maths/FactorialRecursion.java index 6e12d0babbcd..e580fe9b1ba6 100644 --- a/Maths/FactorialRecursion.java +++ b/Maths/FactorialRecursion.java @@ -2,25 +2,25 @@ public class FactorialRecursion { - /* Driver Code */ - public static void main(String[] args) { - assert factorial(0) == 1; - assert factorial(1) == 1; - assert factorial(2) == 2; - assert factorial(3) == 6; - assert factorial(5) == 120; - } + /* Driver Code */ + public static void main(String[] args) { + assert factorial(0) == 1; + assert factorial(1) == 1; + assert factorial(2) == 2; + assert factorial(3) == 6; + assert factorial(5) == 120; + } - /** - * Recursive FactorialRecursion Method - * - * @param n The number to factorial - * @return The factorial of the number - */ - public static long factorial(int n) { - if (n < 0) { - throw new IllegalArgumentException("number is negative"); - } - return n == 0 || n == 1 ? 1 : n * factorial(n - 1); + /** + * Recursive FactorialRecursion Method + * + * @param n The number to factorial + * @return The factorial of the number + */ + public static long factorial(int n) { + if (n < 0) { + throw new IllegalArgumentException("number is negative"); } + return n == 0 || n == 1 ? 1 : n * factorial(n - 1); + } } diff --git a/Maths/FibonacciNumber.java b/Maths/FibonacciNumber.java index 89796b337135..1cec0963d30c 100644 --- a/Maths/FibonacciNumber.java +++ b/Maths/FibonacciNumber.java @@ -1,37 +1,35 @@ package Maths; -/** - * Fibonacci: 0 1 1 2 3 5 8 13 21 ... - */ +/** Fibonacci: 0 1 1 2 3 5 8 13 21 ... */ public class FibonacciNumber { - public static void main(String[] args) { - assert isFibonacciNumber(1); - assert isFibonacciNumber(2); - assert isFibonacciNumber(21); - assert !isFibonacciNumber(9); - assert !isFibonacciNumber(10); - } + public static void main(String[] args) { + assert isFibonacciNumber(1); + assert isFibonacciNumber(2); + assert isFibonacciNumber(21); + assert !isFibonacciNumber(9); + assert !isFibonacciNumber(10); + } - /** - * Check if a number is perfect square number - * - * @param number the number to be checked - * @return true if {@code number} is perfect square, otherwise false - */ - public static boolean isPerfectSquare(int number) { - int sqrt = (int) Math.sqrt(number); - return sqrt * sqrt == number; - } + /** + * Check if a number is perfect square number + * + * @param number the number to be checked + * @return true if {@code number} is perfect square, otherwise false + */ + public static boolean isPerfectSquare(int number) { + int sqrt = (int) Math.sqrt(number); + return sqrt * sqrt == number; + } - /** - * Check if a number is fibonacci number - * This is true if and only if at least one of 5x^2+4 or 5x^2-4 is a perfect square - * - * @param number the number - * @return true if {@code number} is fibonacci number, otherwise false - * @link https://en.wikipedia.org/wiki/Fibonacci_number#Identification - */ - public static boolean isFibonacciNumber(int number) { - return isPerfectSquare(5 * number * number + 4) || isPerfectSquare(5 * number * number - 4); - } + /** + * Check if a number is fibonacci number This is true if and only if at least one of 5x^2+4 or + * 5x^2-4 is a perfect square + * + * @param number the number + * @return true if {@code number} is fibonacci number, otherwise false + * @link https://en.wikipedia.org/wiki/Fibonacci_number#Identification + */ + public static boolean isFibonacciNumber(int number) { + return isPerfectSquare(5 * number * number + 4) || isPerfectSquare(5 * number * number - 4); + } } diff --git a/Maths/FindMax.java b/Maths/FindMax.java index 1a332367de15..961b23380a3a 100644 --- a/Maths/FindMax.java +++ b/Maths/FindMax.java @@ -5,37 +5,35 @@ public class FindMax { - /** - * Driver Code - */ - public static void main(String[] args) { - Random random = new Random(); + /** Driver Code */ + public static void main(String[] args) { + Random random = new Random(); - /* random size */ - int size = random.nextInt(100) + 1; - int[] array = new int[size]; + /* random size */ + int size = random.nextInt(100) + 1; + int[] array = new int[size]; - /* init array with random numbers */ - for (int i = 0; i < size; i++) { - array[i] = random.nextInt() % 100; - } - - assert Arrays.stream(array).max().getAsInt() == findMax(array); + /* init array with random numbers */ + for (int i = 0; i < size; i++) { + array[i] = random.nextInt() % 100; } - /** - * find max of array - * - * @param array the array contains element - * @return max value of given array - */ - public static int findMax(int[] array) { - int max = array[0]; - for (int i = 1; i < array.length; ++i) { - if (array[i] > max) { - max = array[i]; - } - } - return max; + assert Arrays.stream(array).max().getAsInt() == findMax(array); + } + + /** + * find max of array + * + * @param array the array contains element + * @return max value of given array + */ + public static int findMax(int[] array) { + int max = array[0]; + for (int i = 1; i < array.length; ++i) { + if (array[i] > max) { + max = array[i]; + } } + return max; + } } diff --git a/Maths/FindMaxRecursion.java b/Maths/FindMaxRecursion.java index 867390b315c5..38fe2dae8ac5 100644 --- a/Maths/FindMaxRecursion.java +++ b/Maths/FindMaxRecursion.java @@ -4,51 +4,51 @@ import java.util.Random; public class FindMaxRecursion { - public static void main(String[] args) { - Random rand = new Random(); + public static void main(String[] args) { + Random rand = new Random(); - /* rand size */ - int size = rand.nextInt(100) + 1; - int[] array = new int[size]; + /* rand size */ + int size = rand.nextInt(100) + 1; + int[] array = new int[size]; - /* init array with rand numbers */ - for (int i = 0; i < size; i++) { - array[i] = rand.nextInt() % 100; - } - - assert max(array, array.length) == Arrays.stream(array).max().getAsInt(); - assert max(array, 0, array.length - 1) == Arrays.stream(array).max().getAsInt(); + /* init array with rand numbers */ + for (int i = 0; i < size; i++) { + array[i] = rand.nextInt() % 100; } - /** - * Get max of array using divide and conquer algorithm - * - * @param array contains elements - * @param low the index of the first element - * @param high the index of the last element - * @return max of {@code array} - */ - public static int max(int[] array, int low, int high) { - if (low == high) { - return array[low]; //or array[high] - } - - int mid = (low + high) >>> 1; - - int leftMax = max(array, low, mid); //get max in [low, mid] - int rightMax = max(array, mid + 1, high); //get max in [mid+1, high] - - return Math.max(leftMax, rightMax); + assert max(array, array.length) == Arrays.stream(array).max().getAsInt(); + assert max(array, 0, array.length - 1) == Arrays.stream(array).max().getAsInt(); + } + + /** + * Get max of array using divide and conquer algorithm + * + * @param array contains elements + * @param low the index of the first element + * @param high the index of the last element + * @return max of {@code array} + */ + public static int max(int[] array, int low, int high) { + if (low == high) { + return array[low]; // or array[high] } - /** - * Get max of array using recursion algorithm - * - * @param array contains elements - * @param len length of given array - * @return max value of {@code array} - */ - public static int max(int[] array, int len) { - return len == 1 ? array[0] : Math.max(max(array, len - 1), array[len - 1]); - } + int mid = (low + high) >>> 1; + + int leftMax = max(array, low, mid); // get max in [low, mid] + int rightMax = max(array, mid + 1, high); // get max in [mid+1, high] + + return Math.max(leftMax, rightMax); + } + + /** + * Get max of array using recursion algorithm + * + * @param array contains elements + * @param len length of given array + * @return max value of {@code array} + */ + public static int max(int[] array, int len) { + return len == 1 ? array[0] : Math.max(max(array, len - 1), array[len - 1]); + } } diff --git a/Maths/FindMin.java b/Maths/FindMin.java index b8996cd106eb..198bd1e93a7b 100644 --- a/Maths/FindMin.java +++ b/Maths/FindMin.java @@ -5,37 +5,35 @@ public class FindMin { - /** - * Driver Code - */ - public static void main(String[] args) { - Random random = new Random(); + /** Driver Code */ + public static void main(String[] args) { + Random random = new Random(); - /* random size */ - int size = random.nextInt(100) + 1; - int[] array = new int[size]; + /* random size */ + int size = random.nextInt(100) + 1; + int[] array = new int[size]; - /* init array with random numbers */ - for (int i = 0; i < size; i++) { - array[i] = random.nextInt() % 100; - } - - assert Arrays.stream(array).min().getAsInt() == findMin(array); + /* init array with random numbers */ + for (int i = 0; i < size; i++) { + array[i] = random.nextInt() % 100; } - /** - * Find the minimum number of an array of numbers. - * - * @param array the array contains element - * @return min value - */ - public static int findMin(int[] array) { - int min = array[0]; - for (int i = 1; i < array.length; ++i) { - if (array[i] < min) { - min = array[i]; - } - } - return min; + assert Arrays.stream(array).min().getAsInt() == findMin(array); + } + + /** + * Find the minimum number of an array of numbers. + * + * @param array the array contains element + * @return min value + */ + public static int findMin(int[] array) { + int min = array[0]; + for (int i = 1; i < array.length; ++i) { + if (array[i] < min) { + min = array[i]; + } } + return min; + } } diff --git a/Maths/FindMinRecursion.java b/Maths/FindMinRecursion.java index ba9b9c91f24e..4922e0d109e6 100644 --- a/Maths/FindMinRecursion.java +++ b/Maths/FindMinRecursion.java @@ -5,54 +5,52 @@ public class FindMinRecursion { - /** - * Driver Code - */ - public static void main(String[] args) { - Random rand = new Random(); - - /* rand size */ - int size = rand.nextInt(100) + 1; - int[] array = new int[size]; - - /* init array with rand numbers */ - for (int i = 0; i < size; i++) { - array[i] = rand.nextInt() % 100; - } - - assert min(array, 0, array.length - 1) == Arrays.stream(array).min().getAsInt(); - assert min(array, array.length) == Arrays.stream(array).min().getAsInt(); - } + /** Driver Code */ + public static void main(String[] args) { + Random rand = new Random(); + + /* rand size */ + int size = rand.nextInt(100) + 1; + int[] array = new int[size]; - /** - * Get min of array using divide and conquer algorithm - * - * @param array contains elements - * @param low the index of the first element - * @param high the index of the last element - * @return min of {@code array} - */ - public static int min(int[] array, int low, int high) { - if (low == high) { - return array[low]; //or array[high] - } - - int mid = (low + high) >>> 1; - - int leftMin = min(array, low, mid); //get min in [low, mid] - int rightMin = min(array, mid + 1, high); //get min in [mid+1, high] - - return Math.min(leftMin, rightMin); + /* init array with rand numbers */ + for (int i = 0; i < size; i++) { + array[i] = rand.nextInt() % 100; } - /** - * Get min of array using recursion algorithm - * - * @param array contains elements - * @param len length of given array - * @return min value of {@code array} - */ - public static int min(int[] array, int len) { - return len == 1 ? array[0] : Math.min(min(array, len - 1), array[len - 1]); + assert min(array, 0, array.length - 1) == Arrays.stream(array).min().getAsInt(); + assert min(array, array.length) == Arrays.stream(array).min().getAsInt(); + } + + /** + * Get min of array using divide and conquer algorithm + * + * @param array contains elements + * @param low the index of the first element + * @param high the index of the last element + * @return min of {@code array} + */ + public static int min(int[] array, int low, int high) { + if (low == high) { + return array[low]; // or array[high] } + + int mid = (low + high) >>> 1; + + int leftMin = min(array, low, mid); // get min in [low, mid] + int rightMin = min(array, mid + 1, high); // get min in [mid+1, high] + + return Math.min(leftMin, rightMin); + } + + /** + * Get min of array using recursion algorithm + * + * @param array contains elements + * @param len length of given array + * @return min value of {@code array} + */ + public static int min(int[] array, int len) { + return len == 1 ? array[0] : Math.min(min(array, len - 1), array[len - 1]); + } } diff --git a/Maths/Floor.java b/Maths/Floor.java index 5bb4b86708f1..dbd41ac87344 100644 --- a/Maths/Floor.java +++ b/Maths/Floor.java @@ -3,27 +3,27 @@ import java.util.Random; public class Floor { - public static void main(String[] args) { - Random random = new Random(); - for (int i = 1; i <= 1000; ++i) { - double randomNumber = random.nextDouble(); - assert floor(randomNumber) == Math.floor(randomNumber); - } + public static void main(String[] args) { + Random random = new Random(); + for (int i = 1; i <= 1000; ++i) { + double randomNumber = random.nextDouble(); + assert floor(randomNumber) == Math.floor(randomNumber); } + } - /** - * Returns the largest (closest to positive infinity) - * - * @param number the number - * @return the largest (closest to positive infinity) of given {@code number} - */ - public static double floor(double number) { - if (number - (int) number == 0) { - return number; - } else if (number - (int) number > 0) { - return (int) number; - } else { - return (int) number - 1; - } + /** + * Returns the largest (closest to positive infinity) + * + * @param number the number + * @return the largest (closest to positive infinity) of given {@code number} + */ + public static double floor(double number) { + if (number - (int) number == 0) { + return number; + } else if (number - (int) number > 0) { + return (int) number; + } else { + return (int) number - 1; } -} \ No newline at end of file + } +} diff --git a/Maths/GCD.java b/Maths/GCD.java index bff1c33c80f5..0f17f6ea5f11 100644 --- a/Maths/GCD.java +++ b/Maths/GCD.java @@ -1,57 +1,57 @@ package Maths; /** - * This is Euclid's algorithm which is used to find the greatest common denominator - * Overide function name gcd + * This is Euclid's algorithm which is used to find the greatest common denominator Overide function + * name gcd * * @author Oskar Enmalm 3/10/17 */ public class GCD { - /** - * get greatest common divisor - * - * @param num1 the first number - * @param num2 the second number - * @return gcd - */ - public static int gcd(int num1, int num2) { - if (num1 < 0 || num2 < 0) { - throw new ArithmeticException(); - } - - if (num1 == 0 || num2 == 0) { - return Math.abs(num1 - num2); - } - - while (num1 % num2 != 0) { - int remainder = num1 % num2; - num1 = num2; - num2 = remainder; - } - return num2; + /** + * get greatest common divisor + * + * @param num1 the first number + * @param num2 the second number + * @return gcd + */ + public static int gcd(int num1, int num2) { + if (num1 < 0 || num2 < 0) { + throw new ArithmeticException(); } - /** - * get greatest common divisor in array - * - * @param number contains number - * @return gcd - */ - public static int gcd(int[] number) { - int result = number[0]; - for (int i = 1; i < number.length; i++) - // call gcd function (input two value) - result = gcd(result, number[i]); - - return result; + if (num1 == 0 || num2 == 0) { + return Math.abs(num1 - num2); } - public static void main(String[] args) { - int[] myIntArray = {4, 16, 32}; - - // call gcd function (input array) - System.out.println(gcd(myIntArray)); // => 4 - System.out.printf("gcd(40,24)=%d gcd(24,40)=%d%n", gcd(40, 24), gcd(24, 40)); // => 8 + while (num1 % num2 != 0) { + int remainder = num1 % num2; + num1 = num2; + num2 = remainder; } + return num2; + } + + /** + * get greatest common divisor in array + * + * @param number contains number + * @return gcd + */ + public static int gcd(int[] number) { + int result = number[0]; + for (int i = 1; i < number.length; i++) + // call gcd function (input two value) + result = gcd(result, number[i]); + + return result; + } + + public static void main(String[] args) { + int[] myIntArray = {4, 16, 32}; + + // call gcd function (input array) + System.out.println(gcd(myIntArray)); // => 4 + System.out.printf("gcd(40,24)=%d gcd(24,40)=%d%n", gcd(40, 24), gcd(24, 40)); // => 8 + } } diff --git a/Maths/GCDRecursion.java b/Maths/GCDRecursion.java index be5e2904733e..d0104d3db9e9 100644 --- a/Maths/GCDRecursion.java +++ b/Maths/GCDRecursion.java @@ -1,36 +1,34 @@ package Maths; -/** - * @author https://github.com/shellhub/ - */ +/** @author https://github.com/shellhub/ */ public class GCDRecursion { - public static void main(String[] args) { - System.out.println(gcd(20, 15)); /* output: 5 */ - System.out.println(gcd(10, 8)); /* output: 2 */ - System.out.println(gcd(gcd(10, 5), gcd(5, 10))); /* output: 5 */ - } + public static void main(String[] args) { + System.out.println(gcd(20, 15)); /* output: 5 */ + System.out.println(gcd(10, 8)); /* output: 2 */ + System.out.println(gcd(gcd(10, 5), gcd(5, 10))); /* output: 5 */ + } - /** - * get greatest common divisor - * - * @param a the first number - * @param b the second number - * @return gcd - */ - public static int gcd(int a, int b) { + /** + * get greatest common divisor + * + * @param a the first number + * @param b the second number + * @return gcd + */ + public static int gcd(int a, int b) { - if (a < 0 || b < 0) { - throw new ArithmeticException(); - } + if (a < 0 || b < 0) { + throw new ArithmeticException(); + } - if (a == 0 || b == 0) { - return Math.abs(a - b); - } + if (a == 0 || b == 0) { + return Math.abs(a - b); + } - if (a % b == 0) { - return b; - } else { - return gcd(b, a % b); - } + if (a % b == 0) { + return b; + } else { + return gcd(b, a % b); } + } } diff --git a/Maths/LucasSeries.java b/Maths/LucasSeries.java index 8fa7097ba1d0..ade5ab2c52fe 100644 --- a/Maths/LucasSeries.java +++ b/Maths/LucasSeries.java @@ -1,44 +1,43 @@ package Maths; -/** - * https://en.wikipedia.org/wiki/Lucas_number - */ +/** https://en.wikipedia.org/wiki/Lucas_number */ public class LucasSeries { - public static void main(String[] args) { - assert lucasSeries(1) == 2 && lucasSeriesIteration(1) == 2; - assert lucasSeries(2) == 1 && lucasSeriesIteration(2) == 1; - assert lucasSeries(3) == 3 && lucasSeriesIteration(3) == 3; - assert lucasSeries(4) == 4 && lucasSeriesIteration(4) == 4; - assert lucasSeries(5) == 7 && lucasSeriesIteration(5) == 7; - assert lucasSeries(6) == 11 && lucasSeriesIteration(6) == 11; - assert lucasSeries(11) == 123 && lucasSeriesIteration(11) == 123; + public static void main(String[] args) { + assert lucasSeries(1) == 2 && lucasSeriesIteration(1) == 2; + assert lucasSeries(2) == 1 && lucasSeriesIteration(2) == 1; + assert lucasSeries(3) == 3 && lucasSeriesIteration(3) == 3; + assert lucasSeries(4) == 4 && lucasSeriesIteration(4) == 4; + assert lucasSeries(5) == 7 && lucasSeriesIteration(5) == 7; + assert lucasSeries(6) == 11 && lucasSeriesIteration(6) == 11; + assert lucasSeries(11) == 123 && lucasSeriesIteration(11) == 123; + } - } - - /** - * Calculate nth number of lucas series(2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, ....) using recursion - * - * @param n nth - * @return nth number of lucas series - */ - public static int lucasSeries(int n) { - return n == 1 ? 2 : n == 2 ? 1 : lucasSeries(n - 1) + lucasSeries(n - 2); - } + /** + * Calculate nth number of lucas series(2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, ....) using + * recursion + * + * @param n nth + * @return nth number of lucas series + */ + public static int lucasSeries(int n) { + return n == 1 ? 2 : n == 2 ? 1 : lucasSeries(n - 1) + lucasSeries(n - 2); + } - /** - * Calculate nth number of lucas series(2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, ....) using iteration - * - * @param n nth - * @return nth number of lucas series - */ - public static int lucasSeriesIteration(int n) { - int previous = 2; - int current = 1; - for (int i = 1; i < n; i++) { - int next = previous + current; - previous = current; - current = next; - } - return previous; + /** + * Calculate nth number of lucas series(2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, ....) using + * iteration + * + * @param n nth + * @return nth number of lucas series + */ + public static int lucasSeriesIteration(int n) { + int previous = 2; + int current = 1; + for (int i = 1; i < n; i++) { + int next = previous + current; + previous = current; + current = next; } + return previous; + } } diff --git a/Maths/MaxValue.java b/Maths/MaxValue.java index d163bd3cfdc1..504f87bc20a8 100644 --- a/Maths/MaxValue.java +++ b/Maths/MaxValue.java @@ -4,32 +4,29 @@ public class MaxValue { - /** - * Driver Code - */ - public static void main(String[] args) { - Random rand = new Random(); + /** Driver Code */ + public static void main(String[] args) { + Random rand = new Random(); - /* test 100 times using rand numbers */ - for (int i = 1; i <= 100; ++i) { - /* generate number from -50 to 49 */ - int a = rand.nextInt(100) - 50; - int b = rand.nextInt(100) - 50; - assert max(a, b) == Math.max(a, b); - } + /* test 100 times using rand numbers */ + for (int i = 1; i <= 100; ++i) { + /* generate number from -50 to 49 */ + int a = rand.nextInt(100) - 50; + int b = rand.nextInt(100) - 50; + assert max(a, b) == Math.max(a, b); } + } - /** - * Returns the greater of two {@code int} values. That is, the - * result is the argument closer to the value of - * {@link Integer#MAX_VALUE}. If the arguments have the same value, - * the result is that same value. - * - * @param a an argument. - * @param b another argument. - * @return the larger of {@code a} and {@code b}. - */ - public static int max(int a, int b) { - return a >= b ? a : b; - } + /** + * Returns the greater of two {@code int} values. That is, the result is the argument closer to + * the value of {@link Integer#MAX_VALUE}. If the arguments have the same value, the result is + * that same value. + * + * @param a an argument. + * @param b another argument. + * @return the larger of {@code a} and {@code b}. + */ + public static int max(int a, int b) { + return a >= b ? a : b; + } } diff --git a/Maths/Median.java b/Maths/Median.java index 849535838d7a..b0b011232a3c 100644 --- a/Maths/Median.java +++ b/Maths/Median.java @@ -2,27 +2,27 @@ import java.util.Arrays; -/** - * Wikipedia: https://en.wikipedia.org/wiki/Median - */ +/** Wikipedia: https://en.wikipedia.org/wiki/Median */ public class Median { - public static void main(String[] args) { - assert median(new int[]{0}) == 0; - assert median(new int[]{1, 2}) == 1.5; - assert median(new int[]{4, 1, 3, 2}) == 2.5; - assert median(new int[]{1, 3, 3, 6, 7, 8, 9}) == 6; - assert median(new int[]{1, 2, 3, 4, 5, 6, 8, 9}) == 4.5; - } + public static void main(String[] args) { + assert median(new int[] {0}) == 0; + assert median(new int[] {1, 2}) == 1.5; + assert median(new int[] {4, 1, 3, 2}) == 2.5; + assert median(new int[] {1, 3, 3, 6, 7, 8, 9}) == 6; + assert median(new int[] {1, 2, 3, 4, 5, 6, 8, 9}) == 4.5; + } - /** - * Calculate average median - * - * @param values number series - * @return median of given {@code values} - */ - public static double median(int[] values) { - Arrays.sort(values); - int length = values.length; - return length % 2 == 0 ? (values[length / 2] + values[length / 2 - 1]) / 2.0 : values[length / 2]; - } + /** + * Calculate average median + * + * @param values number series + * @return median of given {@code values} + */ + public static double median(int[] values) { + Arrays.sort(values); + int length = values.length; + return length % 2 == 0 + ? (values[length / 2] + values[length / 2 - 1]) / 2.0 + : values[length / 2]; + } } diff --git a/Maths/MinValue.java b/Maths/MinValue.java index 1e92169fce51..3bb4b5434113 100644 --- a/Maths/MinValue.java +++ b/Maths/MinValue.java @@ -4,32 +4,29 @@ public class MinValue { - /** - * Driver Code - */ - public static void main(String[] args) { - Random rand = new Random(); + /** Driver Code */ + public static void main(String[] args) { + Random rand = new Random(); - /* test 100 times using rand numbers */ - for (int i = 1; i <= 100; ++i) { - /* generate number from -50 to 49 */ - int a = rand.nextInt(100) - 50; - int b = rand.nextInt(100) - 50; - assert min(a, b) == Math.min(a, b); - } + /* test 100 times using rand numbers */ + for (int i = 1; i <= 100; ++i) { + /* generate number from -50 to 49 */ + int a = rand.nextInt(100) - 50; + int b = rand.nextInt(100) - 50; + assert min(a, b) == Math.min(a, b); } + } - /** - * Returns the smaller of two {@code int} values. That is, - * the result the argument closer to the value of - * {@link Integer#MIN_VALUE}. If the arguments have the same - * value, the result is that same value. - * - * @param a an argument. - * @param b another argument. - * @return the smaller of {@code a} and {@code b}. - */ - public static int min(int a, int b) { - return a <= b ? a : b; - } + /** + * Returns the smaller of two {@code int} values. That is, the result the argument closer to the + * value of {@link Integer#MIN_VALUE}. If the arguments have the same value, the result is that + * same value. + * + * @param a an argument. + * @param b another argument. + * @return the smaller of {@code a} and {@code b}. + */ + public static int min(int a, int b) { + return a <= b ? a : b; + } } diff --git a/Maths/Mode.java b/Maths/Mode.java index d43ea16e8646..5d28c8c8c4bf 100644 --- a/Maths/Mode.java +++ b/Maths/Mode.java @@ -7,57 +7,53 @@ /* * Find the mode of an array of numbers - * - * The mode of an array of numbers is the most frequently occurring number in the array, + * + * The mode of an array of numbers is the most frequently occurring number in the array, * or the most frequently occurring numbers if there are multiple numbers with the same frequency */ public class Mode { - - public static void main(String[] args) { - - /* Test array of integers */ - assert (mode(new int[]{})) == null; - assert Arrays.equals(mode(new int[]{5}), new int[]{5}); - assert Arrays.equals(mode(new int[]{1, 2, 3, 4, 5}), new int[]{1, 2, 3, 4, 5}); - assert Arrays.equals(mode(new int[]{7, 9, 9, 4, 5, 6, 7, 7, 8}), new int[]{7}); - assert Arrays.equals(mode(new int[]{7, 9, 9, 4, 5, 6, 7, 7, 9}), new int[]{7, 9}); - - } - - /* - * Find the mode of an array of integers - * - * @param numbers array of integers - * @return mode of the array - */ - public static int[] mode(int[] numbers) { - - if(numbers.length == 0) return null; - - HashMap count = new HashMap<>(); - - for(int num : numbers) { - if(count.containsKey(num)) { - - count.put(num, count.get(num) + 1); - - } else { - - count.put(num, 1); - - } - - } - - int max = Collections.max(count.values()); - ArrayList modes = new ArrayList<>(); - - for(int num : count.keySet()) { - if(count.get(num) == max) { - modes.add(num); - } - } - return modes.stream().mapToInt(n -> n).toArray(); - } - + + public static void main(String[] args) { + + /* Test array of integers */ + assert (mode(new int[] {})) == null; + assert Arrays.equals(mode(new int[] {5}), new int[] {5}); + assert Arrays.equals(mode(new int[] {1, 2, 3, 4, 5}), new int[] {1, 2, 3, 4, 5}); + assert Arrays.equals(mode(new int[] {7, 9, 9, 4, 5, 6, 7, 7, 8}), new int[] {7}); + assert Arrays.equals(mode(new int[] {7, 9, 9, 4, 5, 6, 7, 7, 9}), new int[] {7, 9}); + } + + /* + * Find the mode of an array of integers + * + * @param numbers array of integers + * @return mode of the array + */ + public static int[] mode(int[] numbers) { + + if (numbers.length == 0) return null; + + HashMap count = new HashMap<>(); + + for (int num : numbers) { + if (count.containsKey(num)) { + + count.put(num, count.get(num) + 1); + + } else { + + count.put(num, 1); + } + } + + int max = Collections.max(count.values()); + ArrayList modes = new ArrayList<>(); + + for (int num : count.keySet()) { + if (count.get(num) == max) { + modes.add(num); + } + } + return modes.stream().mapToInt(n -> n).toArray(); + } } diff --git a/Maths/NumberOfDigits.java b/Maths/NumberOfDigits.java index 9e760727ae8b..acc9f8c91cb0 100644 --- a/Maths/NumberOfDigits.java +++ b/Maths/NumberOfDigits.java @@ -1,62 +1,59 @@ package Maths; -/** - * Find the number of digits in a number. - */ +/** Find the number of digits in a number. */ public class NumberOfDigits { - public static void main(String[] args) { - int[] numbers = {0, 12, 123, 1234, -12345, 123456, 1234567, 12345678, 123456789}; - for (int i = 0; i < numbers.length; ++i) { - assert numberOfDigits(numbers[i]) == i + 1; - assert numberOfDigitsFast(numbers[i]) == i + 1; - assert numberOfDigitsFaster(numbers[i]) == i + 1; - assert numberOfDigitsRecursion(numbers[i]) == i + 1; - } + public static void main(String[] args) { + int[] numbers = {0, 12, 123, 1234, -12345, 123456, 1234567, 12345678, 123456789}; + for (int i = 0; i < numbers.length; ++i) { + assert numberOfDigits(numbers[i]) == i + 1; + assert numberOfDigitsFast(numbers[i]) == i + 1; + assert numberOfDigitsFaster(numbers[i]) == i + 1; + assert numberOfDigitsRecursion(numbers[i]) == i + 1; } + } - /** - * Find the number of digits in a number. - * - * @param number number to find - * @return number of digits of given number - */ - private static int numberOfDigits(int number) { - int digits = 0; - do { - digits++; - number /= 10; - } while (number != 0); - return digits; - } + /** + * Find the number of digits in a number. + * + * @param number number to find + * @return number of digits of given number + */ + private static int numberOfDigits(int number) { + int digits = 0; + do { + digits++; + number /= 10; + } while (number != 0); + return digits; + } - /** - * Find the number of digits in a number fast version. - * - * @param number number to find - * @return number of digits of given number - */ - private static int numberOfDigitsFast(int number) { - return number == 0 ? 1 : (int) Math.floor(Math.log10(Math.abs(number)) + 1); - } + /** + * Find the number of digits in a number fast version. + * + * @param number number to find + * @return number of digits of given number + */ + private static int numberOfDigitsFast(int number) { + return number == 0 ? 1 : (int) Math.floor(Math.log10(Math.abs(number)) + 1); + } + /** + * Find the number of digits in a number faster version. + * + * @param number number to find + * @return number of digits of given number + */ + private static int numberOfDigitsFaster(int number) { + return number < 0 ? (-number + "").length() : (number + "").length(); + } - /** - * Find the number of digits in a number faster version. - * - * @param number number to find - * @return number of digits of given number - */ - private static int numberOfDigitsFaster(int number) { - return number < 0 ? (-number + "").length() : (number + "").length(); - } - - /** - * Find the number of digits in a number using recursion. - * - * @param number number to find - * @return number of digits of given number - */ - private static int numberOfDigitsRecursion(int number) { - return number / 10 == 0 ? 1 : 1 + numberOfDigitsRecursion(number / 10); - } + /** + * Find the number of digits in a number using recursion. + * + * @param number number to find + * @return number of digits of given number + */ + private static int numberOfDigitsRecursion(int number) { + return number / 10 == 0 ? 1 : 1 + numberOfDigitsRecursion(number / 10); + } } diff --git a/Maths/PalindromeNumber.java b/Maths/PalindromeNumber.java index 2916c753e67a..08c4ba01bea7 100644 --- a/Maths/PalindromeNumber.java +++ b/Maths/PalindromeNumber.java @@ -1,30 +1,30 @@ package Maths; public class PalindromeNumber { - public static void main(String[] args) { + public static void main(String[] args) { - assert isPalindrome(12321); - assert !isPalindrome(1234); - assert isPalindrome(1); - } + assert isPalindrome(12321); + assert !isPalindrome(1234); + assert isPalindrome(1); + } - /** - * Check if {@code n} is palindrome number or not - * - * @param number the number - * @return {@code true} if {@code n} is palindrome number, otherwise {@code false} - */ - public static boolean isPalindrome(int number) { - if (number < 0) { - throw new IllegalArgumentException(number + ""); - } - int numberCopy = number; - int reverseNumber = 0; - while (numberCopy != 0) { - int remainder = numberCopy % 10; - reverseNumber = reverseNumber * 10 + remainder; - numberCopy /= 10; - } - return number == reverseNumber; + /** + * Check if {@code n} is palindrome number or not + * + * @param number the number + * @return {@code true} if {@code n} is palindrome number, otherwise {@code false} + */ + public static boolean isPalindrome(int number) { + if (number < 0) { + throw new IllegalArgumentException(number + ""); + } + int numberCopy = number; + int reverseNumber = 0; + while (numberCopy != 0) { + int remainder = numberCopy % 10; + reverseNumber = reverseNumber * 10 + remainder; + numberCopy /= 10; } + return number == reverseNumber; + } } diff --git a/Maths/ParseInteger.java b/Maths/ParseInteger.java index c9c11528c1dc..cf9c9efc88fd 100644 --- a/Maths/ParseInteger.java +++ b/Maths/ParseInteger.java @@ -1,33 +1,33 @@ package Maths; public class ParseInteger { - public static void main(String[] args) { - assert parseInt("123") == Integer.parseInt("123"); - assert parseInt("-123") == Integer.parseInt("-123"); - assert parseInt("0123") == Integer.parseInt("0123"); - assert parseInt("+123") == Integer.parseInt("+123"); - } + public static void main(String[] args) { + assert parseInt("123") == Integer.parseInt("123"); + assert parseInt("-123") == Integer.parseInt("-123"); + assert parseInt("0123") == Integer.parseInt("0123"); + assert parseInt("+123") == Integer.parseInt("+123"); + } - /** - * Parse a string to integer - * - * @param s the string - * @return the integer value represented by the argument in decimal. - * @throws NumberFormatException if the {@code string} does not contain a parsable integer. - */ - public static int parseInt(String s) { - if (s == null || s.length() == 0) { - throw new NumberFormatException("null"); - } - boolean isNegative = s.charAt(0) == '-'; - boolean isPositive = s.charAt(0) == '+'; - int number = 0; - for (int i = isNegative ? 1 : isPositive ? 1 : 0, length = s.length(); i < length; ++i) { - if (!Character.isDigit(s.charAt(i))) { - throw new NumberFormatException("s=" + s); - } - number = number * 10 + s.charAt(i) - '0'; - } - return isNegative ? -number : number; + /** + * Parse a string to integer + * + * @param s the string + * @return the integer value represented by the argument in decimal. + * @throws NumberFormatException if the {@code string} does not contain a parsable integer. + */ + public static int parseInt(String s) { + if (s == null || s.length() == 0) { + throw new NumberFormatException("null"); + } + boolean isNegative = s.charAt(0) == '-'; + boolean isPositive = s.charAt(0) == '+'; + int number = 0; + for (int i = isNegative ? 1 : isPositive ? 1 : 0, length = s.length(); i < length; ++i) { + if (!Character.isDigit(s.charAt(i))) { + throw new NumberFormatException("s=" + s); + } + number = number * 10 + s.charAt(i) - '0'; } + return isNegative ? -number : number; + } } diff --git a/Maths/PerfectCube.java b/Maths/PerfectCube.java index 1db0dc3e9002..2ecb8e805a42 100644 --- a/Maths/PerfectCube.java +++ b/Maths/PerfectCube.java @@ -1,27 +1,24 @@ package Maths; -/** - * https://en.wikipedia.org/wiki/Cube_(algebra) - */ +/** https://en.wikipedia.org/wiki/Cube_(algebra) */ public class PerfectCube { - public static void main(String[] args) { - assert !isPerfectCube(-1); - assert isPerfectCube(0); - assert isPerfectCube(1); - assert !isPerfectCube(4); - assert isPerfectCube(8); - assert isPerfectCube(27); + public static void main(String[] args) { + assert !isPerfectCube(-1); + assert isPerfectCube(0); + assert isPerfectCube(1); + assert !isPerfectCube(4); + assert isPerfectCube(8); + assert isPerfectCube(27); + } - } - - /** - * Check if a number is perfect cube or not - * - * @param number number to check - * @return {@code true} if {@code number} is perfect cube, otherwise {@code false} - */ - public static boolean isPerfectCube(int number) { - int a = (int) Math.pow(number, 1.0 / 3); - return a * a * a == number; - } + /** + * Check if a number is perfect cube or not + * + * @param number number to check + * @return {@code true} if {@code number} is perfect cube, otherwise {@code false} + */ + public static boolean isPerfectCube(int number) { + int a = (int) Math.pow(number, 1.0 / 3); + return a * a * a == number; + } } diff --git a/Maths/PerfectNumber.java b/Maths/PerfectNumber.java index ceaf0b2bca3e..de56c4175c02 100644 --- a/Maths/PerfectNumber.java +++ b/Maths/PerfectNumber.java @@ -1,33 +1,32 @@ package Maths; /** - * In number theory, a perfect number is a positive integer that is equal to the sum of - * its positive divisors, excluding the number itself. For instance, 6 has divisors 1, 2 and 3 - * (excluding itself), and 1 + 2 + 3 = 6, so 6 is a perfect number. - *

- * link:https://en.wikipedia.org/wiki/Perfect_number - *

+ * In number theory, a perfect number is a positive integer that is equal to the sum of its positive + * divisors, excluding the number itself. For instance, 6 has divisors 1, 2 and 3 (excluding + * itself), and 1 + 2 + 3 = 6, so 6 is a perfect number. + * + *

link:https://en.wikipedia.org/wiki/Perfect_number */ public class PerfectNumber { - public static void main(String[] args) { - assert isPerfectNumber(6); /* 1 + 2 + 3 == 6 */ - assert !isPerfectNumber(8); /* 1 + 2 + 4 != 8 */ - assert isPerfectNumber(28); /* 1 + 2 + 4 + 7 + 14 == 28 */ - } + public static void main(String[] args) { + assert isPerfectNumber(6); /* 1 + 2 + 3 == 6 */ + assert !isPerfectNumber(8); /* 1 + 2 + 4 != 8 */ + assert isPerfectNumber(28); /* 1 + 2 + 4 + 7 + 14 == 28 */ + } - /** - * Check if {@code number} is perfect number or not - * - * @param number the number - * @return {@code true} if {@code number} is perfect number, otherwise false - */ - public static boolean isPerfectNumber(int number) { - int sum = 0; /* sum of its positive divisors */ - for (int i = 1; i < number; ++i) { - if (number % i == 0) { - sum += i; - } - } - return sum == number; + /** + * Check if {@code number} is perfect number or not + * + * @param number the number + * @return {@code true} if {@code number} is perfect number, otherwise false + */ + public static boolean isPerfectNumber(int number) { + int sum = 0; /* sum of its positive divisors */ + for (int i = 1; i < number; ++i) { + if (number % i == 0) { + sum += i; + } } + return sum == number; + } } diff --git a/Maths/PerfectSquare.java b/Maths/PerfectSquare.java index 7484b2fdaba7..aef645e2ed2b 100644 --- a/Maths/PerfectSquare.java +++ b/Maths/PerfectSquare.java @@ -1,25 +1,23 @@ package Maths; -/** - * https://en.wikipedia.org/wiki/Perfect_square - */ +/** https://en.wikipedia.org/wiki/Perfect_square */ public class PerfectSquare { - public static void main(String[] args) { - assert !isPerfectSquare(-1); - assert !isPerfectSquare(3); - assert !isPerfectSquare(5); - assert isPerfectSquare(9); - assert isPerfectSquare(100); - } + public static void main(String[] args) { + assert !isPerfectSquare(-1); + assert !isPerfectSquare(3); + assert !isPerfectSquare(5); + assert isPerfectSquare(9); + assert isPerfectSquare(100); + } - /** - * Check if a number is perfect square number - * - * @param number the number to be checked - * @return true if {@code number} is perfect square, otherwise false - */ - public static boolean isPerfectSquare(int number) { - int sqrt = (int) Math.sqrt(number); - return sqrt * sqrt == number; - } -} \ No newline at end of file + /** + * Check if a number is perfect square number + * + * @param number the number to be checked + * @return true if {@code number} is perfect square, otherwise false + */ + public static boolean isPerfectSquare(int number) { + int sqrt = (int) Math.sqrt(number); + return sqrt * sqrt == number; + } +} diff --git a/Maths/Pow.java b/Maths/Pow.java index ac58fbbbe7cd..6af5446510af 100644 --- a/Maths/Pow.java +++ b/Maths/Pow.java @@ -1,27 +1,26 @@ package Maths; -//POWER (exponentials) Examples (a^b) +// POWER (exponentials) Examples (a^b) public class Pow { - public static void main(String[] args) { - assert pow(2, 0) == Math.pow(2, 0); // == 1 - assert pow(0, 2) == Math.pow(0, 2); // == 0 - assert pow(2, 10) == Math.pow(2, 10); // == 1024 - assert pow(10, 2) == Math.pow(10, 2); // == 100 - } + public static void main(String[] args) { + assert pow(2, 0) == Math.pow(2, 0); // == 1 + assert pow(0, 2) == Math.pow(0, 2); // == 0 + assert pow(2, 10) == Math.pow(2, 10); // == 1024 + assert pow(10, 2) == Math.pow(10, 2); // == 100 + } - /** - * Returns the value of the first argument raised to the power of the - * second argument - * - * @param a the base. - * @param b the exponent. - * @return the value {@code a}{@code b}. - */ - public static long pow(int a, int b) { - long result = 1; - for (int i = 1; i <= b; i++) { - result *= a; - } - return result; + /** + * Returns the value of the first argument raised to the power of the second argument + * + * @param a the base. + * @param b the exponent. + * @return the value {@code a}{@code b}. + */ + public static long pow(int a, int b) { + long result = 1; + for (int i = 1; i <= b; i++) { + result *= a; } + return result; + } } diff --git a/Maths/PowRecursion.java b/Maths/PowRecursion.java index dab336b306fe..598fc724e54a 100644 --- a/Maths/PowRecursion.java +++ b/Maths/PowRecursion.java @@ -1,22 +1,21 @@ package Maths; public class PowRecursion { - public static void main(String[] args) { - assert Double.compare(pow(2, 0), Math.pow(2, 0)) == 0; - assert Double.compare(pow(0, 2), Math.pow(0, 2)) == 0; - assert Double.compare(pow(2, 10), Math.pow(2, 10)) == 0; - assert Double.compare(pow(10, 2), Math.pow(10, 2)) == 0; - } + public static void main(String[] args) { + assert Double.compare(pow(2, 0), Math.pow(2, 0)) == 0; + assert Double.compare(pow(0, 2), Math.pow(0, 2)) == 0; + assert Double.compare(pow(2, 10), Math.pow(2, 10)) == 0; + assert Double.compare(pow(10, 2), Math.pow(10, 2)) == 0; + } - /** - * Returns the value of the first argument raised to the power of the - * second argument - * - * @param a the base. - * @param b the exponent. - * @return the value {@code a}{@code b}. - */ - public static long pow(int a, int b) { - return b == 0 ? 1 : a * pow(a, b - 1); - } -} \ No newline at end of file + /** + * Returns the value of the first argument raised to the power of the second argument + * + * @param a the base. + * @param b the exponent. + * @return the value {@code a}{@code b}. + */ + public static long pow(int a, int b) { + return b == 0 ? 1 : a * pow(a, b - 1); + } +} diff --git a/Maths/PowerOfTwoOrNot.java b/Maths/PowerOfTwoOrNot.java index d03151bcbbb7..329f64d139f2 100644 --- a/Maths/PowerOfTwoOrNot.java +++ b/Maths/PowerOfTwoOrNot.java @@ -1,28 +1,23 @@ package Maths; -/** - * A utility to check if a given number is power of two or not. - * For example 8,16 etc. - */ - +/** A utility to check if a given number is power of two or not. For example 8,16 etc. */ public class PowerOfTwoOrNot { - public static void main(String[] args) { - assert !checkIfPowerOfTwoOrNot(0); - assert checkIfPowerOfTwoOrNot(1); - assert checkIfPowerOfTwoOrNot(8); - assert checkIfPowerOfTwoOrNot(16); - assert checkIfPowerOfTwoOrNot(1024); - } - + public static void main(String[] args) { + assert !checkIfPowerOfTwoOrNot(0); + assert checkIfPowerOfTwoOrNot(1); + assert checkIfPowerOfTwoOrNot(8); + assert checkIfPowerOfTwoOrNot(16); + assert checkIfPowerOfTwoOrNot(1024); + } - /** - * Checks whether given number is power of two or not. - * - * @param number the number to check - * @return {@code true} if given number is power of two, otherwise {@code false} - */ - public static boolean checkIfPowerOfTwoOrNot(int number) { - return number != 0 && ((number & (number - 1)) == 0); - } + /** + * Checks whether given number is power of two or not. + * + * @param number the number to check + * @return {@code true} if given number is power of two, otherwise {@code false} + */ + public static boolean checkIfPowerOfTwoOrNot(int number) { + return number != 0 && ((number & (number - 1)) == 0); + } } diff --git a/Maths/PrimeCheck.java b/Maths/PrimeCheck.java index c972aa8c3e5a..6ea901a8a73e 100644 --- a/Maths/PrimeCheck.java +++ b/Maths/PrimeCheck.java @@ -3,36 +3,36 @@ import java.util.Scanner; public class PrimeCheck { - public static void main(String[] args) { - Scanner scanner = new Scanner(System.in); + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); - System.out.print("Enter a number: "); - int n = scanner.nextInt(); - if (isPrime(n)) { - System.out.println(n + " is a prime number"); - } else { - System.out.println(n + " is not a prime number"); - } - scanner.close(); + System.out.print("Enter a number: "); + int n = scanner.nextInt(); + if (isPrime(n)) { + System.out.println(n + " is a prime number"); + } else { + System.out.println(n + " is not a prime number"); } + scanner.close(); + } - /*** - * Checks if a number is prime or not - * @param n the number - * @return {@code true} if {@code n} is prime - */ - public static boolean isPrime(int n) { - if (n == 2) { - return true; - } - if (n < 2 || n % 2 == 0) { - return false; - } - for (int i = 3, limit = (int) Math.sqrt(n); i <= limit; i += 2) { - if (n % i == 0) { - return false; - } - } - return true; + /*** + * Checks if a number is prime or not + * @param n the number + * @return {@code true} if {@code n} is prime + */ + public static boolean isPrime(int n) { + if (n == 2) { + return true; } + if (n < 2 || n % 2 == 0) { + return false; + } + for (int i = 3, limit = (int) Math.sqrt(n); i <= limit; i += 2) { + if (n % i == 0) { + return false; + } + } + return true; + } } diff --git a/Maths/PrimeFactorization.java b/Maths/PrimeFactorization.java index bba2057d8ea9..79e12a7dc49b 100644 --- a/Maths/PrimeFactorization.java +++ b/Maths/PrimeFactorization.java @@ -1,36 +1,32 @@ package Maths; -import java.lang.Math; import java.util.Scanner; public class PrimeFactorization { - public static void main(String[] args){ - System.out.println("## all prime factors ##"); - Scanner scanner = new Scanner(System.in); - System.out.print("Enter a number: "); - int n = scanner.nextInt(); - System.out.print(("printing factors of " + n + " : ")); - pfactors(n); - scanner.close(); - } - public static void pfactors(int n){ + public static void main(String[] args) { + System.out.println("## all prime factors ##"); + Scanner scanner = new Scanner(System.in); + System.out.print("Enter a number: "); + int n = scanner.nextInt(); + System.out.print(("printing factors of " + n + " : ")); + pfactors(n); + scanner.close(); + } - while (n%2==0) - { - System.out.print(2 + " "); - n /= 2; - } + public static void pfactors(int n) { - for (int i=3; i<= Math.sqrt(n); i+=2) - { - while (n%i == 0) - { - System.out.print(i + " "); - n /= i; - } - } + while (n % 2 == 0) { + System.out.print(2 + " "); + n /= 2; + } - if(n > 2) - System.out.print(n); + for (int i = 3; i <= Math.sqrt(n); i += 2) { + while (n % i == 0) { + System.out.print(i + " "); + n /= i; + } } + + if (n > 2) System.out.print(n); + } } diff --git a/Maths/PythagoreanTriple.java b/Maths/PythagoreanTriple.java index 4eae9615fe04..5aaf95c7550e 100644 --- a/Maths/PythagoreanTriple.java +++ b/Maths/PythagoreanTriple.java @@ -1,32 +1,30 @@ package Maths; -/** - * https://en.wikipedia.org/wiki/Pythagorean_triple - * - */ +/** https://en.wikipedia.org/wiki/Pythagorean_triple */ public class PythagoreanTriple { - public static void main(String[] args) { - assert isPythagTriple(3,4,5); - assert isPythagTriple(5,12,13); - assert isPythagTriple(6,8,10); - assert !isPythagTriple(10,20,30); - assert !isPythagTriple(6,8,100); - assert !isPythagTriple(-1,-1,1); - } - - /** - * Check if a,b,c are a Pythagorean Triple - * - * @param a x/y component length of a right triangle - * @param b y/x component length of a right triangle - * @param c hypotenuse length of a right triangle - * @return boolean true if a, b, c satisfy the Pythagorean theorem, otherwise false - */ - public static boolean isPythagTriple(int a, int b, int c) { - if(a <= 0 || b <= 0 || c <= 0) { - return false; - } else { - return (a * a) + (b * b) == (c * c); - } - } + public static void main(String[] args) { + assert isPythagTriple(3, 4, 5); + assert isPythagTriple(5, 12, 13); + assert isPythagTriple(6, 8, 10); + assert !isPythagTriple(10, 20, 30); + assert !isPythagTriple(6, 8, 100); + assert !isPythagTriple(-1, -1, 1); + } + + /** + * Check if a,b,c are a Pythagorean Triple + * + * @param a x/y component length of a right triangle + * @param b y/x component length of a right triangle + * @param c hypotenuse length of a right triangle + * @return boolean true if a, b, c satisfy the Pythagorean theorem, otherwise + * false + */ + public static boolean isPythagTriple(int a, int b, int c) { + if (a <= 0 || b <= 0 || c <= 0) { + return false; + } else { + return (a * a) + (b * b) == (c * c); + } + } } diff --git a/Maths/SumOfArithmeticSeries.java b/Maths/SumOfArithmeticSeries.java index 5d03c2308d30..01e7c3a0357c 100644 --- a/Maths/SumOfArithmeticSeries.java +++ b/Maths/SumOfArithmeticSeries.java @@ -1,40 +1,40 @@ package Maths; /** - *

- * In mathematics, an arithmetic progression (AP) or arithmetic sequence is a sequence of numbers such that the - * difference between the consecutive terms is constant. Difference here means the second minus the first. - * For instance, the sequence 5, 7, 9, 11, 13, 15, . . . is an arithmetic progression with common difference of 2. - *

- * Wikipedia: https://en.wikipedia.org/wiki/Arithmetic_progression + * In mathematics, an arithmetic progression (AP) or arithmetic sequence is a sequence of numbers + * such that the difference between the consecutive terms is constant. Difference here means the + * second minus the first. For instance, the sequence 5, 7, 9, 11, 13, 15, . . . is an arithmetic + * progression with common difference of 2. + * + *

Wikipedia: https://en.wikipedia.org/wiki/Arithmetic_progression */ public class SumOfArithmeticSeries { - public static void main(String[] args) { + public static void main(String[] args) { - /* 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 */ - assert Double.compare(55.0, sumOfSeries(1, 1, 10)) == 0; + /* 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 */ + assert Double.compare(55.0, sumOfSeries(1, 1, 10)) == 0; - /* 1 + 3 + 5 + 7 + 9 + 11 + 13 + 15 + 17 + 19 */ - assert Double.compare(100.0, sumOfSeries(1, 2, 10)) == 0; + /* 1 + 3 + 5 + 7 + 9 + 11 + 13 + 15 + 17 + 19 */ + assert Double.compare(100.0, sumOfSeries(1, 2, 10)) == 0; - /* 1 + 11 + 21 + 31 + 41 + 51 + 61 + 71 + 81 + 91 */ - assert Double.compare(460.0, sumOfSeries(1, 10, 10)) == 0; + /* 1 + 11 + 21 + 31 + 41 + 51 + 61 + 71 + 81 + 91 */ + assert Double.compare(460.0, sumOfSeries(1, 10, 10)) == 0; - /* 0.1 + 0.2 + 0.3 + 0.4 + 0.5 + 0.6 + 0.7 + 0.8 + 0.9 + 1.0 */ - assert Double.compare(5.5, sumOfSeries(0.1, 0.1, 10)) == 0; + /* 0.1 + 0.2 + 0.3 + 0.4 + 0.5 + 0.6 + 0.7 + 0.8 + 0.9 + 1.0 */ + assert Double.compare(5.5, sumOfSeries(0.1, 0.1, 10)) == 0; - assert Double.compare(49600.0, sumOfSeries(1, 10, 100)) == 0; - } + assert Double.compare(49600.0, sumOfSeries(1, 10, 100)) == 0; + } - /** - * Calculate sum of arithmetic series - * - * @param firstTerm the initial term of an arithmetic series - * @param commonDiff the common difference of an arithmetic series - * @param numOfTerms the total terms of an arithmetic series - * @return sum of given arithmetic series - */ - private static double sumOfSeries(double firstTerm, double commonDiff, int numOfTerms) { - return numOfTerms / 2.0 * (2 * firstTerm + (numOfTerms - 1) * commonDiff); - } -} \ No newline at end of file + /** + * Calculate sum of arithmetic series + * + * @param firstTerm the initial term of an arithmetic series + * @param commonDiff the common difference of an arithmetic series + * @param numOfTerms the total terms of an arithmetic series + * @return sum of given arithmetic series + */ + private static double sumOfSeries(double firstTerm, double commonDiff, int numOfTerms) { + return numOfTerms / 2.0 * (2 * firstTerm + (numOfTerms - 1) * commonDiff); + } +} diff --git a/Maths/SumOfDigits.java b/Maths/SumOfDigits.java index baa798a39e5d..11b3726a9ddf 100644 --- a/Maths/SumOfDigits.java +++ b/Maths/SumOfDigits.java @@ -1,62 +1,56 @@ package Maths; public class SumOfDigits { - public static void main(String[] args) { - assert - sumOfDigits(-123) == 6 - && sumOfDigitsRecursion(-123) == 6 - && sumOfDigitsFast(-123) == 6; + public static void main(String[] args) { + assert sumOfDigits(-123) == 6 && sumOfDigitsRecursion(-123) == 6 && sumOfDigitsFast(-123) == 6; - assert sumOfDigits(0) == 0 - && sumOfDigitsRecursion(0) == 0 - && sumOfDigitsFast(0) == 0; + assert sumOfDigits(0) == 0 && sumOfDigitsRecursion(0) == 0 && sumOfDigitsFast(0) == 0; + assert sumOfDigits(12345) == 15 + && sumOfDigitsRecursion(12345) == 15 + && sumOfDigitsFast(12345) == 15; + } - assert sumOfDigits(12345) == 15 - && sumOfDigitsRecursion(12345) == 15 - && sumOfDigitsFast(12345) == 15; + /** + * Calculate the sum of digits of a number + * + * @param number the number contains digits + * @return sum of digits of given {@code number} + */ + public static int sumOfDigits(int number) { + number = number < 0 ? -number : number; /* calculate abs value */ + int sum = 0; + while (number != 0) { + sum += number % 10; + number /= 10; } + return sum; + } - /** - * Calculate the sum of digits of a number - * - * @param number the number contains digits - * @return sum of digits of given {@code number} - */ - public static int sumOfDigits(int number) { - number = number < 0 ? -number : number; /* calculate abs value */ - int sum = 0; - while (number != 0) { - sum += number % 10; - number /= 10; - } - return sum; - } - - /** - * Calculate the sum of digits of a number using recursion - * - * @param number the number contains digits - * @return sum of digits of given {@code number} - */ - public static int sumOfDigitsRecursion(int number) { - number = number < 0 ? -number : number; /* calculate abs value */ - return number < 10 ? number : number % 10 + sumOfDigitsRecursion(number / 10); - } + /** + * Calculate the sum of digits of a number using recursion + * + * @param number the number contains digits + * @return sum of digits of given {@code number} + */ + public static int sumOfDigitsRecursion(int number) { + number = number < 0 ? -number : number; /* calculate abs value */ + return number < 10 ? number : number % 10 + sumOfDigitsRecursion(number / 10); + } - /** - * Calculate the sum of digits of a number using char array - * - * @param number the number contains digits - * @return sum of digits of given {@code number} - */ - public static int sumOfDigitsFast(int number) { - number = number < 0 ? -number : number; /* calculate abs value */ - char[] digits = (number + "").toCharArray(); - int sum = 0; - for (int i = 0; i < digits.length; ++i) { - sum += digits[i] - '0'; - } - return sum; + /** + * Calculate the sum of digits of a number using char array + * + * @param number the number contains digits + * @return sum of digits of given {@code number} + */ + public static int sumOfDigitsFast(int number) { + number = number < 0 ? -number : number; /* calculate abs value */ + char[] digits = (number + "").toCharArray(); + int sum = 0; + for (int i = 0; i < digits.length; ++i) { + sum += digits[i] - '0'; } + return sum; + } } diff --git a/Maths/VampireNumber.java b/Maths/VampireNumber.java index 056ce681a4ae..e09dd0bb0cf8 100644 --- a/Maths/VampireNumber.java +++ b/Maths/VampireNumber.java @@ -2,93 +2,77 @@ import java.util.ArrayList; import java.util.Collections; -import java.util.List; /** - n number theory, a vampire number (or true vampire number) is a composite natural number with an even number of digits, - that can be factored into two natural numbers each with half as many digits as the original number - and not both with trailing zeroes, where the two factors contain precisely - all the digits of the original number, in any order, counting multiplicity. - The first vampire number is 1260 = 21 × 60. - * * - *

- * * link: https://en.wikipedia.org/wiki/Vampire_number - * *

- *

+ * n number theory, a vampire number (or true vampire number) is a composite natural number with an + * even number of digits, that can be factored into two natural numbers each with half as many + * digits as the original number and not both with trailing zeroes, where the two factors contain + * precisely all the digits of the original number, in any order, counting multiplicity. The first + * vampire number is 1260 = 21 × 60. * * + *

* link: https://en.wikipedia.org/wiki/Vampire_number * + * + *

*/ - - - - - - - public class VampireNumber { - public static void main(String[] args) { - - test(10,1000); - } - - static void test(int startValue, int stopValue) { - int countofRes = 1; - StringBuilder res = new StringBuilder(); + public static void main(String[] args) { + test(10, 1000); + } - for (int i = startValue; i <= stopValue; i++) { - for (int j = i; j <= stopValue; j++) { - // System.out.println(i+ " "+ j); - if (isVampireNumber(i, j,true)) { - countofRes++; - res.append("" + countofRes + ": = ( " + i + "," + j + " = " + i*j + ")" + "\n"); - } - } - } - System.out.println(res); - } - - - - - static boolean isVampireNumber(int a, int b, boolean noPseudoVamireNumbers ) { - - // this is for pseudoVampireNumbers pseudovampire number need not be of length n/2 digits for example - // 126 = 6 x 21 - if (noPseudoVamireNumbers) { - if (a * 10 <= b || b * 10 <= a) { - return false; - } - } - - String mulDigits = splitIntoDigits(a*b,0); - String faktorDigits = splitIntoDigits(a,b); - - return mulDigits.equals(faktorDigits); - } + static void test(int startValue, int stopValue) { + int countofRes = 1; + StringBuilder res = new StringBuilder(); + for (int i = startValue; i <= stopValue; i++) { + for (int j = i; j <= stopValue; j++) { + // System.out.println(i+ " "+ j); + if (isVampireNumber(i, j, true)) { + countofRes++; + res.append("" + countofRes + ": = ( " + i + "," + j + " = " + i * j + ")" + "\n"); + } + } + } + System.out.println(res); + } + + static boolean isVampireNumber(int a, int b, boolean noPseudoVamireNumbers) { + + // this is for pseudoVampireNumbers pseudovampire number need not be of length n/2 digits for + // example + // 126 = 6 x 21 + if (noPseudoVamireNumbers) { + if (a * 10 <= b || b * 10 <= a) { + return false; + } + } + String mulDigits = splitIntoDigits(a * b, 0); + String faktorDigits = splitIntoDigits(a, b); -// methode to Split the numbers to Digits - static String splitIntoDigits(int num, int num2) { + return mulDigits.equals(faktorDigits); + } - StringBuilder res = new StringBuilder(); + // methode to Split the numbers to Digits + static String splitIntoDigits(int num, int num2) { - ArrayList digits = new ArrayList<>(); - while (num > 0) { - digits.add(num%10); - num /= 10; - } - while (num2 > 0) { - digits.add(num2%10); - num2/= 10; - } - Collections.sort(digits); - for (int i : digits) { - res.append(i); - } + StringBuilder res = new StringBuilder(); + ArrayList digits = new ArrayList<>(); + while (num > 0) { + digits.add(num % 10); + num /= 10; + } + while (num2 > 0) { + digits.add(num2 % 10); + num2 /= 10; + } + Collections.sort(digits); + for (int i : digits) { + res.append(i); + } - return res.toString(); - } + return res.toString(); + } } diff --git a/MinimizingLateness/MinimizingLateness.java b/MinimizingLateness/MinimizingLateness.java index 46e6fb4e06d7..cf06a0d44a70 100644 --- a/MinimizingLateness/MinimizingLateness.java +++ b/MinimizingLateness/MinimizingLateness.java @@ -1,6 +1,5 @@ package MinimizingLateness; - import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; @@ -8,52 +7,54 @@ public class MinimizingLateness { - private static class Schedule { // Schedule class - int t = 0; // Time required for the operation to be performed - int d = 0; // Time the job should be completed - int s = 0; // Start time of the task - int f = 0; // End time of the operation + private static class Schedule { // Schedule class + int t = 0; // Time required for the operation to be performed + int d = 0; // Time the job should be completed + int s = 0; // Start time of the task + int f = 0; // End time of the operation - public Schedule(int t, int d) { - this.t = t; - this.d = d; - } + public Schedule(int t, int d) { + this.t = t; + this.d = d; } + } - public static void main(String[] args) throws IOException { - StringTokenizer token; + public static void main(String[] args) throws IOException { + StringTokenizer token; - BufferedReader in = new BufferedReader(new FileReader("MinimizingLateness/lateness_data.txt")); - String ch = in.readLine(); - if (ch == null || ch.isEmpty()) { - in.close(); - return; - } - int indexCount = Integer.parseInt(ch); - System.out.println("Input Data : "); - System.out.println(indexCount); // number of operations - Schedule[] array = new Schedule[indexCount]; // Create an array to hold the operation - int i = 0; - while ((ch = in.readLine()) != null) { - token = new StringTokenizer(ch, " "); - // Include the time required for the operation to be performed in the array and the time it should be completed. - array[i] = new Schedule(Integer.parseInt(token.nextToken()), Integer.parseInt(token.nextToken())); - i++; - System.out.println(array[i - 1].t + " " + array[i - 1].d); - } + BufferedReader in = new BufferedReader(new FileReader("MinimizingLateness/lateness_data.txt")); + String ch = in.readLine(); + if (ch == null || ch.isEmpty()) { + in.close(); + return; + } + int indexCount = Integer.parseInt(ch); + System.out.println("Input Data : "); + System.out.println(indexCount); // number of operations + Schedule[] array = new Schedule[indexCount]; // Create an array to hold the operation + int i = 0; + while ((ch = in.readLine()) != null) { + token = new StringTokenizer(ch, " "); + // Include the time required for the operation to be performed in the array and the time it + // should be completed. + array[i] = + new Schedule(Integer.parseInt(token.nextToken()), Integer.parseInt(token.nextToken())); + i++; + System.out.println(array[i - 1].t + " " + array[i - 1].d); + } - int tryTime = 0; // Total time worked - int lateness = 0; // Lateness - for (int j = 0; j < indexCount - 1; j++) { - array[j].s = tryTime; // Start time of the task - array[j].f = tryTime + array[j].t; // Time finished - tryTime = tryTime + array[j].t; // Add total work time - // Lateness - lateness = lateness + Math.max(0, tryTime - array[j].d); - } - System.out.println(); - System.out.println("Output Data : "); - System.out.println(lateness); - in.close(); + int tryTime = 0; // Total time worked + int lateness = 0; // Lateness + for (int j = 0; j < indexCount - 1; j++) { + array[j].s = tryTime; // Start time of the task + array[j].f = tryTime + array[j].t; // Time finished + tryTime = tryTime + array[j].t; // Add total work time + // Lateness + lateness = lateness + Math.max(0, tryTime - array[j].d); } + System.out.println(); + System.out.println("Output Data : "); + System.out.println(lateness); + in.close(); + } } diff --git a/Misc/MedianOfRunningArray.java b/Misc/MedianOfRunningArray.java index 32bbf51947a1..21485e62f00a 100644 --- a/Misc/MedianOfRunningArray.java +++ b/Misc/MedianOfRunningArray.java @@ -3,50 +3,44 @@ import java.util.Collections; import java.util.PriorityQueue; - -/** - * @author shrutisheoran - */ +/** @author shrutisheoran */ public class MedianOfRunningArray { - private PriorityQueue p1; - private PriorityQueue p2; - - //Constructor - public MedianOfRunningArray() { - this.p1 = new PriorityQueue<>(Collections.reverseOrder()); //Max Heap - this.p2 = new PriorityQueue<>(); //Min Heap - } - - /* - Inserting lower half of array to max Heap - and upper half to min heap - */ - public void insert(Integer e) { - p2.add(e); - if (p2.size() - p1.size() > 1) - p1.add(p2.remove()); - } - + private PriorityQueue p1; + private PriorityQueue p2; + + // Constructor + public MedianOfRunningArray() { + this.p1 = new PriorityQueue<>(Collections.reverseOrder()); // Max Heap + this.p2 = new PriorityQueue<>(); // Min Heap + } + + /* + Inserting lower half of array to max Heap + and upper half to min heap + */ + public void insert(Integer e) { + p2.add(e); + if (p2.size() - p1.size() > 1) p1.add(p2.remove()); + } + + /* + Returns median at any given point + */ + public Integer median() { + if (p1.size() == p2.size()) return (p1.peek() + p2.peek()) / 2; + return p1.size() > p2.size() ? p1.peek() : p2.peek(); + } + + public static void main(String[] args) { /* - Returns median at any given point + Testing the median function */ - public Integer median() { - if (p1.size() == p2.size()) - return (p1.peek() + p2.peek()) / 2; - return p1.size() > p2.size() ? p1.peek() : p2.peek(); - } - public static void main(String[] args) { - /* - Testing the median function - */ - - MedianOfRunningArray p = new MedianOfRunningArray(); - int arr[] = {10, 7, 4, 9, 2, 3, 11, 17, 14}; - for (int i = 0; i < 9; i++) { - p.insert(arr[i]); - System.out.print(p.median() + " "); - } + MedianOfRunningArray p = new MedianOfRunningArray(); + int arr[] = {10, 7, 4, 9, 2, 3, 11, 17, 14}; + for (int i = 0; i < 9; i++) { + p.insert(arr[i]); + System.out.print(p.median() + " "); } - -} \ No newline at end of file + } +} diff --git a/Misc/PalindromePrime.java b/Misc/PalindromePrime.java index 77a918c32297..50b115de81c1 100644 --- a/Misc/PalindromePrime.java +++ b/Misc/PalindromePrime.java @@ -4,44 +4,44 @@ public class PalindromePrime { - public static void main(String[] args) { // Main funtion - Scanner in = new Scanner(System.in); - System.out.println("Enter the quantity of First Palindromic Primes you want"); - int n = in.nextInt(); // Input of how many first pallindromic prime we want - functioning(n); // calling function - functioning - in.close(); - } + public static void main(String[] args) { // Main funtion + Scanner in = new Scanner(System.in); + System.out.println("Enter the quantity of First Palindromic Primes you want"); + int n = in.nextInt(); // Input of how many first pallindromic prime we want + functioning(n); // calling function - functioning + in.close(); + } - public static boolean prime(int num) { // checking if number is prime or not - for (int divisor = 3; divisor <= Math.sqrt(num); divisor += 2) { - if (num % divisor == 0) { - return false; // false if not prime - } - } - return true; // True if prime + public static boolean prime(int num) { // checking if number is prime or not + for (int divisor = 3; divisor <= Math.sqrt(num); divisor += 2) { + if (num % divisor == 0) { + return false; // false if not prime + } } + return true; // True if prime + } - public static int reverse(int n) { // Returns the reverse of the number - int reverse = 0; - while (n != 0) { - reverse *= 10; - reverse += n % 10; - n /= 10; - } - return reverse; + public static int reverse(int n) { // Returns the reverse of the number + int reverse = 0; + while (n != 0) { + reverse *= 10; + reverse += n % 10; + n /= 10; } + return reverse; + } - public static void functioning(int y) { - if (y == 0) return; - System.out.print(2 + "\n"); // print the first Palindromic Prime - int count = 1; - int num = 3; - while (count < y) { - if (num == reverse(num) && prime(num)) { // number is prime and it's reverse is same - count++; // counts check when to terminate while loop - System.out.print(num + "\n"); // print the Palindromic Prime - } - num += 2; // inrease iterator value by two - } + public static void functioning(int y) { + if (y == 0) return; + System.out.print(2 + "\n"); // print the first Palindromic Prime + int count = 1; + int num = 3; + while (count < y) { + if (num == reverse(num) && prime(num)) { // number is prime and it's reverse is same + count++; // counts check when to terminate while loop + System.out.print(num + "\n"); // print the Palindromic Prime + } + num += 2; // inrease iterator value by two } + } } diff --git a/Others/BestFit.java b/Others/BestFit.java index 71814d22b9f1..bfe775be8475 100644 --- a/Others/BestFit.java +++ b/Others/BestFit.java @@ -2,88 +2,95 @@ import java.util.ArrayList; -/** - * @author Dekas Dimitrios - */ +/** @author Dekas Dimitrios */ public class BestFit { - private static final int NO_ALLOCATION = -255; // if a process has been allocated in position -255, - // it means that it has not been actually allocated. + private static final int NO_ALLOCATION = + -255; // if a process has been allocated in position -255, + // it means that it has not been actually allocated. - /** - * Method to find the maximum valued element of an array filled with positive integers. - * - * @param array: an array filled with positive integers. - * @return the maximum valued element of the array. - */ - private static int findMaxElement(int[] array) { - int max = -1; - for (int value : array) { - if (value > max) { - max = value; - } - } - return max; + /** + * Method to find the maximum valued element of an array filled with positive integers. + * + * @param array: an array filled with positive integers. + * @return the maximum valued element of the array. + */ + private static int findMaxElement(int[] array) { + int max = -1; + for (int value : array) { + if (value > max) { + max = value; + } } + return max; + } - /** - * Method to find the index of the memory block that is going to fit the given process based on the best fit algorithm. - * - * @param blocks: the array with the available memory blocks. - * @param process: the size of the process. - * @return the index of the block that fits, or -255 if no such block exists. - */ - private static int findBestFit(int[] blockSizes, int processSize) { - // Initialize minDiff with an unreachable value by a difference between a blockSize and the processSize. - int minDiff = findMaxElement(blockSizes); - int index = NO_ALLOCATION; // If there is no block that can fit the process, return NO_ALLOCATION as the result. - for(int i=0 ; i < blockSizes.length ; i++) { // Find the most fitting memory block for the given process. - if(blockSizes[i] - processSize < minDiff && blockSizes[i] - processSize >= 0) { - minDiff = blockSizes[i] - processSize; - index = i; - } - } - return index; + /** + * Method to find the index of the memory block that is going to fit the given process based on + * the best fit algorithm. + * + * @param blocks: the array with the available memory blocks. + * @param process: the size of the process. + * @return the index of the block that fits, or -255 if no such block exists. + */ + private static int findBestFit(int[] blockSizes, int processSize) { + // Initialize minDiff with an unreachable value by a difference between a blockSize and the + // processSize. + int minDiff = findMaxElement(blockSizes); + int index = + NO_ALLOCATION; // If there is no block that can fit the process, return NO_ALLOCATION as the + // result. + for (int i = 0; + i < blockSizes.length; + i++) { // Find the most fitting memory block for the given process. + if (blockSizes[i] - processSize < minDiff && blockSizes[i] - processSize >= 0) { + minDiff = blockSizes[i] - processSize; + index = i; + } } + return index; + } - /** - * Method to allocate memory to blocks according to the best fit - * algorithm. It should return an ArrayList of Integers, where the - * index is the process ID (zero-indexed) and the value is the block - * number (also zero-indexed). - * - * @param sizeOfBlocks: an int array that contains the sizes of the memory blocks available. - * @param sizeOfProcesses: an int array that contains the sizes of the processes we need memory blocks for. - * @return the ArrayList filled with Integers repressenting the memory allocation that took place. - */ - static ArrayList bestFit(int[] sizeOfBlocks, int[] sizeOfProcesses) { - // The array list responsible for saving the memory allocations done by the best-fit algorithm - ArrayList memAlloc = new ArrayList<>(); - // Do this for every process - for(int processSize : sizeOfProcesses) { - int chosenBlockIdx = findBestFit(sizeOfBlocks, processSize); // Find the index of the memory block going to be used - memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list - if(chosenBlockIdx != NO_ALLOCATION) { // Only if a block was chosen to store the process in it, - sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size - } - } - return memAlloc; + /** + * Method to allocate memory to blocks according to the best fit algorithm. It should return an + * ArrayList of Integers, where the index is the process ID (zero-indexed) and the value is the + * block number (also zero-indexed). + * + * @param sizeOfBlocks: an int array that contains the sizes of the memory blocks available. + * @param sizeOfProcesses: an int array that contains the sizes of the processes we need memory + * blocks for. + * @return the ArrayList filled with Integers repressenting the memory allocation that took place. + */ + static ArrayList bestFit(int[] sizeOfBlocks, int[] sizeOfProcesses) { + // The array list responsible for saving the memory allocations done by the best-fit algorithm + ArrayList memAlloc = new ArrayList<>(); + // Do this for every process + for (int processSize : sizeOfProcesses) { + int chosenBlockIdx = + findBestFit( + sizeOfBlocks, processSize); // Find the index of the memory block going to be used + memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list + if (chosenBlockIdx + != NO_ALLOCATION) { // Only if a block was chosen to store the process in it, + sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size + } } + return memAlloc; + } - /** - * Method to print the memory allocated. - * - * @param memAllocation: an ArrayList of Integer representing the memory allocation done by the bestFit method. - */ - public static void printMemoryAllocation(ArrayList memAllocation) { - System.out.println("Process No.\tBlock No."); - System.out.println("===========\t========="); - for (int i = 0; i < memAllocation.size(); i++) { - System.out.print(" " + i + "\t\t"); - if (memAllocation.get(i) != NO_ALLOCATION) - System.out.print(memAllocation.get(i)); - else - System.out.print("Not Allocated"); - System.out.println(); - } + /** + * Method to print the memory allocated. + * + * @param memAllocation: an ArrayList of Integer representing the memory allocation done by the + * bestFit method. + */ + public static void printMemoryAllocation(ArrayList memAllocation) { + System.out.println("Process No.\tBlock No."); + System.out.println("===========\t========="); + for (int i = 0; i < memAllocation.size(); i++) { + System.out.print(" " + i + "\t\t"); + if (memAllocation.get(i) != NO_ALLOCATION) System.out.print(memAllocation.get(i)); + else System.out.print("Not Allocated"); + System.out.println(); } -} \ No newline at end of file + } +} diff --git a/Others/BrianKernighanAlgorithm.java b/Others/BrianKernighanAlgorithm.java index a35234f0e2af..8767bee42d44 100644 --- a/Others/BrianKernighanAlgorithm.java +++ b/Others/BrianKernighanAlgorithm.java @@ -4,46 +4,37 @@ /** * @author Nishita Aggarwal - *

- * Brian Kernighan’s Algorithm - *

- * algorithm to count the number of set bits in a given number - *

- * Subtraction of 1 from a number toggles all the bits (from right to left) till the rightmost set bit(including the - * rightmost set bit). - * So if we subtract a number by 1 and do bitwise & with itself i.e. (n & (n-1)), we unset the rightmost set bit. - *

- * If we do n & (n-1) in a loop and count the no of times loop executes we get the set bit count. - *

- *

- * Time Complexity: O(logn) + *

Brian Kernighan’s Algorithm + *

algorithm to count the number of set bits in a given number + *

Subtraction of 1 from a number toggles all the bits (from right to left) till the + * rightmost set bit(including the rightmost set bit). So if we subtract a number by 1 and do + * bitwise & with itself i.e. (n & (n-1)), we unset the rightmost set bit. + *

If we do n & (n-1) in a loop and count the no of times loop executes we get the set bit + * count. + *

+ *

Time Complexity: O(logn) */ - - public class BrianKernighanAlgorithm { - /** - * @param num: number in which we count the set bits - * @return int: Number of set bits - */ - static int countSetBits(int num) { - int cnt = 0; - while (num != 0) { - num = num & (num - 1); - cnt++; - } - return cnt; + /** + * @param num: number in which we count the set bits + * @return int: Number of set bits + */ + static int countSetBits(int num) { + int cnt = 0; + while (num != 0) { + num = num & (num - 1); + cnt++; } + return cnt; + } - - /** - * @param args : command line arguments - */ - public static void main(String args[]) { - Scanner sc = new Scanner(System.in); - int num = sc.nextInt(); - int setBitCount = countSetBits(num); - System.out.println(setBitCount); - sc.close(); - } + /** @param args : command line arguments */ + public static void main(String args[]) { + Scanner sc = new Scanner(System.in); + int num = sc.nextInt(); + int setBitCount = countSetBits(num); + System.out.println(setBitCount); + sc.close(); + } } diff --git a/Others/CRC32.java b/Others/CRC32.java index 80eb3d5c730c..23712eef164a 100644 --- a/Others/CRC32.java +++ b/Others/CRC32.java @@ -2,30 +2,26 @@ import java.util.BitSet; -/** - * Generates a crc32 checksum for a given string or byte array - */ +/** Generates a crc32 checksum for a given string or byte array */ public class CRC32 { - public static void main(String[] args) { - System.out.println(Integer.toHexString(crc32("Hello World"))); - } + public static void main(String[] args) { + System.out.println(Integer.toHexString(crc32("Hello World"))); + } - public static int crc32(String str) { - return crc32(str.getBytes()); - } + public static int crc32(String str) { + return crc32(str.getBytes()); + } - public static int crc32(byte[] data) { - BitSet bitSet = BitSet.valueOf(data); - int crc32 = 0xFFFFFFFF; // initial value - for (int i = 0; i < data.length * 8; i++) { - if (((crc32 >>> 31) & 1) != (bitSet.get(i) ? 1 : 0)) - crc32 = (crc32 << 1) ^ 0x04C11DB7; // xor with polynomial - else - crc32 = (crc32 << 1); - } - crc32 = Integer.reverse(crc32); // result reflect - return crc32 ^ 0xFFFFFFFF; // final xor value + public static int crc32(byte[] data) { + BitSet bitSet = BitSet.valueOf(data); + int crc32 = 0xFFFFFFFF; // initial value + for (int i = 0; i < data.length * 8; i++) { + if (((crc32 >>> 31) & 1) != (bitSet.get(i) ? 1 : 0)) + crc32 = (crc32 << 1) ^ 0x04C11DB7; // xor with polynomial + else crc32 = (crc32 << 1); } - + crc32 = Integer.reverse(crc32); // result reflect + return crc32 ^ 0xFFFFFFFF; // final xor value + } } diff --git a/Others/CRCAlgorithm.java b/Others/CRCAlgorithm.java index d53e3a02c2e3..3729a5ed5a33 100644 --- a/Others/CRCAlgorithm.java +++ b/Others/CRCAlgorithm.java @@ -4,200 +4,190 @@ import java.util.Random; import java.util.concurrent.ThreadLocalRandom; -/** - * @author dimgrichr - */ +/** @author dimgrichr */ public class CRCAlgorithm { - private int correctMess; + private int correctMess; - private int wrongMess; + private int wrongMess; - private int wrongMessCaught; + private int wrongMessCaught; - private int wrongMessNotCaught; + private int wrongMessNotCaught; - private int messSize; + private int messSize; - private double ber; + private double ber; - private boolean messageChanged; + private boolean messageChanged; - private ArrayList message; + private ArrayList message; - private ArrayList dividedMessage; + private ArrayList dividedMessage; - private ArrayList p; + private ArrayList p; - private Random randomGenerator; + private Random randomGenerator; - - /** - * The algorithm's main constructor. - * The most significant variables, used in the algorithm, - * are set in their initial values. - * - * @param str The binary number P, in a string form, which is used by the CRC algorithm - * @param size The size of every transmitted message - * @param ber The Bit Error Rate - */ - public CRCAlgorithm(String str, int size, double ber) { - messageChanged = false; - message = new ArrayList<>(); - messSize = size; - dividedMessage = new ArrayList<>(); - p = new ArrayList<>(); - for (int i = 0; i < str.length(); i++) { - p.add(Character.getNumericValue(str.charAt(i))); - } - randomGenerator = new Random(); - correctMess = 0; - wrongMess = 0; - wrongMessCaught = 0; - wrongMessNotCaught = 0; - this.ber = ber; - } - - - /** - * Returns the counter wrongMess - * - * @return wrongMess, the number of Wrong Messages - */ - public int getWrongMess() { - return wrongMess; - } - - /** - * Returns the counter wrongMessCaught - * - * @return wrongMessCaught, the number of wrong messages, which are caught by the CRC algoriithm - */ - public int getWrongMessCaught() { - return wrongMessCaught; - } - - /** - * Returns the counter wrongMessNotCaught - * - * @return wrongMessNotCaught, the number of wrong messages, which are not caught by the CRC algorithm - */ - public int getWrongMessNotCaught() { - return wrongMessNotCaught; - } - - /** - * Returns the counter correctMess - * - * @return correctMess, the number of the Correct Messages - */ - public int getCorrectMess() { - return correctMess; + /** + * The algorithm's main constructor. The most significant variables, used in the algorithm, are + * set in their initial values. + * + * @param str The binary number P, in a string form, which is used by the CRC algorithm + * @param size The size of every transmitted message + * @param ber The Bit Error Rate + */ + public CRCAlgorithm(String str, int size, double ber) { + messageChanged = false; + message = new ArrayList<>(); + messSize = size; + dividedMessage = new ArrayList<>(); + p = new ArrayList<>(); + for (int i = 0; i < str.length(); i++) { + p.add(Character.getNumericValue(str.charAt(i))); } - - /** - * Resets some of the object's values, used on the main function, - * so that it can be re-used, in order not to waste too much memory and time, - * by creating new objects. - */ - public void refactor() { - messageChanged = false; - message = new ArrayList<>(); - dividedMessage = new ArrayList<>(); + randomGenerator = new Random(); + correctMess = 0; + wrongMess = 0; + wrongMessCaught = 0; + wrongMessNotCaught = 0; + this.ber = ber; + } + + /** + * Returns the counter wrongMess + * + * @return wrongMess, the number of Wrong Messages + */ + public int getWrongMess() { + return wrongMess; + } + + /** + * Returns the counter wrongMessCaught + * + * @return wrongMessCaught, the number of wrong messages, which are caught by the CRC algoriithm + */ + public int getWrongMessCaught() { + return wrongMessCaught; + } + + /** + * Returns the counter wrongMessNotCaught + * + * @return wrongMessNotCaught, the number of wrong messages, which are not caught by the CRC + * algorithm + */ + public int getWrongMessNotCaught() { + return wrongMessNotCaught; + } + + /** + * Returns the counter correctMess + * + * @return correctMess, the number of the Correct Messages + */ + public int getCorrectMess() { + return correctMess; + } + + /** + * Resets some of the object's values, used on the main function, so that it can be re-used, in + * order not to waste too much memory and time, by creating new objects. + */ + public void refactor() { + messageChanged = false; + message = new ArrayList<>(); + dividedMessage = new ArrayList<>(); + } + + /** + * Random messages, consisted of 0's and 1's, are generated, so that they can later be transmitted + */ + public void generateRandomMess() { + for (int i = 0; i < messSize; i++) { + int x = ThreadLocalRandom.current().nextInt(0, 2); + message.add(x); } - - /** - * Random messages, consisted of 0's and 1's, - * are generated, so that they can later be transmitted - */ - public void generateRandomMess() { - for (int i = 0; i < messSize; i++) { - int x = ThreadLocalRandom.current().nextInt(0, 2); - message.add(x); - } + } + + /** + * The most significant part of the CRC algorithm. The message is divided by P, so the + * dividedMessage ArrayList is created. If check == true, the dividedMessaage is + * examined, in order to see if it contains any 1's. If it does, the message is considered to be + * wrong by the receiver,so the variable wrongMessCaught changes. If it does not, it is accepted, + * so one of the variables correctMess, wrongMessNotCaught, changes. If check == false, the + * diviided Message is added at the end of the ArrayList message. + * + * @param check the variable used to determine, if the message is going to be checked from the + * receiver if true, it is checked otherwise, it is not + */ + public void divideMessageWithP(boolean check) { + ArrayList x = new ArrayList<>(); + ArrayList k = (ArrayList) message.clone(); + if (!check) { + for (int i = 0; i < p.size() - 1; i++) { + k.add(0); + } } - - /** - * The most significant part of the CRC algorithm. - * The message is divided by P, so the dividedMessage ArrayList is created. - * If check == true, the dividedMessaage is examined, in order to see if it contains any 1's. - * If it does, the message is considered to be wrong by the receiver,so the variable wrongMessCaught changes. - * If it does not, it is accepted, so one of the variables correctMess, wrongMessNotCaught, changes. - * If check == false, the diviided Message is added at the end of the ArrayList message. - * - * @param check the variable used to determine, if the message is going to be checked from the receiver - * if true, it is checked - * otherwise, it is not - */ - public void divideMessageWithP(boolean check) { - ArrayList x = new ArrayList<>(); - ArrayList k = (ArrayList) message.clone(); - if (!check) { - for (int i = 0; i < p.size() - 1; i++) { - k.add(0); - } + while (!k.isEmpty()) { + while (x.size() < p.size() && !k.isEmpty()) { + x.add(k.get(0)); + k.remove(0); + } + if (x.size() == p.size()) { + for (int i = 0; i < p.size(); i++) { + if (x.get(i) == p.get(i)) { + x.set(i, 0); + } else { + x.set(i, 1); + } } - while (!k.isEmpty()) { - while (x.size() < p.size() && !k.isEmpty()) { - x.add(k.get(0)); - k.remove(0); - } - if (x.size() == p.size()) { - for (int i = 0; i < p.size(); i++) { - if (x.get(i) == p.get(i)) { - x.set(i, 0); - } else { - x.set(i, 1); - } - } - for (int i = 0; i < x.size() && x.get(i) != 1; i++) { - x.remove(0); - } - } + for (int i = 0; i < x.size() && x.get(i) != 1; i++) { + x.remove(0); } - dividedMessage = (ArrayList) x.clone(); - if (!check) { - for (int z : dividedMessage) { - message.add(z); - } + } + } + dividedMessage = (ArrayList) x.clone(); + if (!check) { + for (int z : dividedMessage) { + message.add(z); + } + } else { + if (dividedMessage.contains(1) && messageChanged) { + wrongMessCaught++; + } else if (!dividedMessage.contains(1) && messageChanged) { + wrongMessNotCaught++; + } else if (!messageChanged) { + correctMess++; + } + } + } + + /** + * Once the message is transmitted, some of it's elements, is possible to change from 1 to 0, or + * from 0 to 1, because of the Bit Error Rate (ber). For every element of the message, a random + * double number is created. If that number is smaller than ber, then the spesific element + * changes. On the other hand, if it's bigger than ber, it does not. Based on these changes. the + * boolean variable messageChanged, gets the value: true, or false. + */ + public void changeMess() { + for (int y : message) { + double x = randomGenerator.nextDouble(); + while (x < 0.0000 || x > 1.00000) { + x = randomGenerator.nextDouble(); + } + if (x < ber) { + messageChanged = true; + if (y == 1) { + message.set(message.indexOf(y), 0); } else { - if (dividedMessage.contains(1) && messageChanged) { - wrongMessCaught++; - } else if (!dividedMessage.contains(1) && messageChanged) { - wrongMessNotCaught++; - } else if (!messageChanged) { - correctMess++; - } + message.set(message.indexOf(y), 1); } + } } - - /** - * Once the message is transmitted, some of it's elements, - * is possible to change from 1 to 0, or from 0 to 1, - * because of the Bit Error Rate (ber). - * For every element of the message, a random double number is created. - * If that number is smaller than ber, then the spesific element changes. - * On the other hand, if it's bigger than ber, it does not. - * Based on these changes. the boolean variable messageChanged, gets the value: - * true, or false. - */ - public void changeMess() { - for (int y : message) { - double x = randomGenerator.nextDouble(); - while (x < 0.0000 || x > 1.00000) { - x = randomGenerator.nextDouble(); - } - if (x < ber) { - messageChanged = true; - if (y == 1) { - message.set(message.indexOf(y), 0); - } else { - message.set(message.indexOf(y), 1); - } - } - } - if (messageChanged) { - wrongMess++; - } + if (messageChanged) { + wrongMess++; } + } } diff --git a/Others/CountChar.java b/Others/CountChar.java index 8f37217ed5f9..9136a4e686d0 100644 --- a/Others/CountChar.java +++ b/Others/CountChar.java @@ -4,21 +4,21 @@ public class CountChar { - public static void main(String[] args) { - Scanner input = new Scanner(System.in); - System.out.print("Enter your text: "); - String str = input.nextLine(); - input.close(); - System.out.println("There are " + CountCharacters(str) + " characters."); - } + public static void main(String[] args) { + Scanner input = new Scanner(System.in); + System.out.print("Enter your text: "); + String str = input.nextLine(); + input.close(); + System.out.println("There are " + CountCharacters(str) + " characters."); + } - /** - * Count non space character in string - * - * @param str String to count the characters - * @return number of character in the specified string - */ - private static int CountCharacters(String str) { - return str.replaceAll("\\s", "").length(); - } + /** + * Count non space character in string + * + * @param str String to count the characters + * @return number of character in the specified string + */ + private static int CountCharacters(String str) { + return str.replaceAll("\\s", "").length(); + } } diff --git a/Others/CountWords.java b/Others/CountWords.java index f1caf9a87734..746b027ebd59 100644 --- a/Others/CountWords.java +++ b/Others/CountWords.java @@ -3,46 +3,42 @@ import java.util.Scanner; /** - * You enter a string into this program, and it will return how many words were - * in that particular string + * You enter a string into this program, and it will return how many words were in that particular + * string * * @author Marcus */ public class CountWords { - public static void main(String[] args) { - Scanner input = new Scanner(System.in); - System.out.println("Enter your text: "); - String str = input.nextLine(); + public static void main(String[] args) { + Scanner input = new Scanner(System.in); + System.out.println("Enter your text: "); + String str = input.nextLine(); - System.out.println("Your text has " + wordCount(str) + " word(s)"); - System.out.println("Your text has " + secondaryWordCount(str) + " word(s)"); - input.close(); - } + System.out.println("Your text has " + wordCount(str) + " word(s)"); + System.out.println("Your text has " + secondaryWordCount(str) + " word(s)"); + input.close(); + } - private static int wordCount(String s) { - if (s == null || s.isEmpty()) - return 0; - return s.trim().split("[\\s]+").length; - } + private static int wordCount(String s) { + if (s == null || s.isEmpty()) return 0; + return s.trim().split("[\\s]+").length; + } - /** - * counts the number of words in a sentence but ignores all potential - * non-alphanumeric characters that do not represent a word. runs in O(n) where - * n is the length of s - * - * @param s String: sentence with word(s) - * @return int: number of words - */ - private static int secondaryWordCount(String s) { - if (s == null || s.isEmpty()) - return 0; - StringBuilder sb = new StringBuilder(); - for (char c : s.toCharArray()) { - if (Character.isLetter(c) || Character.isDigit(c)) - sb.append(c); - } - s = sb.toString(); - return s.trim().split("[\\s]+").length; + /** + * counts the number of words in a sentence but ignores all potential non-alphanumeric characters + * that do not represent a word. runs in O(n) where n is the length of s + * + * @param s String: sentence with word(s) + * @return int: number of words + */ + private static int secondaryWordCount(String s) { + if (s == null || s.isEmpty()) return 0; + StringBuilder sb = new StringBuilder(); + for (char c : s.toCharArray()) { + if (Character.isLetter(c) || Character.isDigit(c)) sb.append(c); } + s = sb.toString(); + return s.trim().split("[\\s]+").length; + } } diff --git a/Others/Dijkstra.java b/Others/Dijkstra.java index b1a0987d0245..913f25b3eb2b 100644 --- a/Others/Dijkstra.java +++ b/Others/Dijkstra.java @@ -1,219 +1,200 @@ package Others; - /** - * Dijkstra's algorithm,is a graph search algorithm that solves the single-source - * shortest path problem for a graph with nonnegative edge path costs, producing - * a shortest path tree. - *

- * NOTE: The inputs to Dijkstra's algorithm are a directed and weighted graph consisting - * of 2 or more nodes, generally represented by an adjacency matrix or list, and a start node. - *

- * Original source of code: https://rosettacode.org/wiki/Dijkstra%27s_algorithm#Java - * Also most of the comments are from RosettaCode. + * Dijkstra's algorithm,is a graph search algorithm that solves the single-source shortest path + * problem for a graph with nonnegative edge path costs, producing a shortest path tree. + * + *

NOTE: The inputs to Dijkstra's algorithm are a directed and weighted graph consisting of 2 or + * more nodes, generally represented by an adjacency matrix or list, and a start node. + * + *

Original source of code: https://rosettacode.org/wiki/Dijkstra%27s_algorithm#Java Also most of + * the comments are from RosettaCode. */ - import java.util.*; public class Dijkstra { - private static final Graph.Edge[] GRAPH = { - // Distance from node "a" to node "b" is 7. - // In the current Graph there is no way to move the other way (e,g, from "b" to "a"), - // a new edge would be needed for that - new Graph.Edge("a", "b", 7), - new Graph.Edge("a", "c", 9), - new Graph.Edge("a", "f", 14), - new Graph.Edge("b", "c", 10), - new Graph.Edge("b", "d", 15), - new Graph.Edge("c", "d", 11), - new Graph.Edge("c", "f", 2), - new Graph.Edge("d", "e", 6), - new Graph.Edge("e", "f", 9), - }; - private static final String START = "a"; - private static final String END = "e"; - - /** - * main function - * Will run the code with "GRAPH" that was defined above. - */ - public static void main(String[] args) { - Graph g = new Graph(GRAPH); - g.dijkstra(START); - g.printPath(END); - //g.printAllPaths(); - } + private static final Graph.Edge[] GRAPH = { + // Distance from node "a" to node "b" is 7. + // In the current Graph there is no way to move the other way (e,g, from "b" to "a"), + // a new edge would be needed for that + new Graph.Edge("a", "b", 7), + new Graph.Edge("a", "c", 9), + new Graph.Edge("a", "f", 14), + new Graph.Edge("b", "c", 10), + new Graph.Edge("b", "d", 15), + new Graph.Edge("c", "d", 11), + new Graph.Edge("c", "f", 2), + new Graph.Edge("d", "e", 6), + new Graph.Edge("e", "f", 9), + }; + private static final String START = "a"; + private static final String END = "e"; + + /** main function Will run the code with "GRAPH" that was defined above. */ + public static void main(String[] args) { + Graph g = new Graph(GRAPH); + g.dijkstra(START); + g.printPath(END); + // g.printAllPaths(); + } } class Graph { - // mapping of vertex names to Vertex objects, built from a set of Edges - private final Map graph; - - /** - * One edge of the graph (only used by Graph constructor) - */ - public static class Edge { - public final String v1, v2; - public final int dist; - - public Edge(String v1, String v2, int dist) { - this.v1 = v1; - this.v2 = v2; - this.dist = dist; - } + // mapping of vertex names to Vertex objects, built from a set of Edges + private final Map graph; + + /** One edge of the graph (only used by Graph constructor) */ + public static class Edge { + public final String v1, v2; + public final int dist; + + public Edge(String v1, String v2, int dist) { + this.v1 = v1; + this.v2 = v2; + this.dist = dist; + } + } + + /** One vertex of the graph, complete with mappings to neighbouring vertices */ + public static class Vertex implements Comparable { + public final String name; + // MAX_VALUE assumed to be infinity + public int dist = Integer.MAX_VALUE; + public Vertex previous = null; + public final Map neighbours = new HashMap<>(); + + public Vertex(String name) { + this.name = name; } - /** - * One vertex of the graph, complete with mappings to neighbouring vertices - */ - public static class Vertex implements Comparable { - public final String name; - // MAX_VALUE assumed to be infinity - public int dist = Integer.MAX_VALUE; - public Vertex previous = null; - public final Map neighbours = new HashMap<>(); - - public Vertex(String name) { - this.name = name; - } - - private void printPath() { - if (this == this.previous) { - System.out.printf("%s", this.name); - } else if (this.previous == null) { - System.out.printf("%s(unreached)", this.name); - } else { - this.previous.printPath(); - System.out.printf(" -> %s(%d)", this.name, this.dist); - } - } - - public int compareTo(Vertex other) { - if (dist == other.dist) - return name.compareTo(other.name); + private void printPath() { + if (this == this.previous) { + System.out.printf("%s", this.name); + } else if (this.previous == null) { + System.out.printf("%s(unreached)", this.name); + } else { + this.previous.printPath(); + System.out.printf(" -> %s(%d)", this.name, this.dist); + } + } - return Integer.compare(dist, other.dist); - } + public int compareTo(Vertex other) { + if (dist == other.dist) return name.compareTo(other.name); - @Override - public boolean equals(Object object) { - if (this == object) return true; - if (object == null || getClass() != object.getClass()) return false; - if (!super.equals(object)) return false; + return Integer.compare(dist, other.dist); + } - Vertex vertex = (Vertex) object; + @Override + public boolean equals(Object object) { + if (this == object) return true; + if (object == null || getClass() != object.getClass()) return false; + if (!super.equals(object)) return false; - if (dist != vertex.dist) return false; - if (name != null ? !name.equals(vertex.name) : vertex.name != null) return false; - if (previous != null ? !previous.equals(vertex.previous) : vertex.previous != null) return false; - if (neighbours != null ? !neighbours.equals(vertex.neighbours) : vertex.neighbours != null) return false; + Vertex vertex = (Vertex) object; - return true; - } + if (dist != vertex.dist) return false; + if (name != null ? !name.equals(vertex.name) : vertex.name != null) return false; + if (previous != null ? !previous.equals(vertex.previous) : vertex.previous != null) + return false; + if (neighbours != null ? !neighbours.equals(vertex.neighbours) : vertex.neighbours != null) + return false; - @Override - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (name != null ? name.hashCode() : 0); - result = 31 * result + dist; - result = 31 * result + (previous != null ? previous.hashCode() : 0); - result = 31 * result + (neighbours != null ? neighbours.hashCode() : 0); - return result; - } + return true; + } - @Override - public String toString() { - return "(" + name + ", " + dist + ")"; - } + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (name != null ? name.hashCode() : 0); + result = 31 * result + dist; + result = 31 * result + (previous != null ? previous.hashCode() : 0); + result = 31 * result + (neighbours != null ? neighbours.hashCode() : 0); + return result; } - /** - * Builds a graph from a set of edges - */ - public Graph(Edge[] edges) { - graph = new HashMap<>(edges.length); + @Override + public String toString() { + return "(" + name + ", " + dist + ")"; + } + } - // one pass to find all vertices - for (Edge e : edges) { - if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1)); - if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2)); - } + /** Builds a graph from a set of edges */ + public Graph(Edge[] edges) { + graph = new HashMap<>(edges.length); - // another pass to set neighbouring vertices - for (Edge e : edges) { - graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist); - // graph.get(e.v2).neighbours.put(graph.get(e.v1), e.dist); // also do this for an undirected graph - } + // one pass to find all vertices + for (Edge e : edges) { + if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1)); + if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2)); } - /** - * Runs dijkstra using a specified source vertex - */ - public void dijkstra(String startName) { - if (!graph.containsKey(startName)) { - System.err.printf("Graph doesn't contain start vertex \"%s\"%n", startName); - return; - } - final Vertex source = graph.get(startName); - NavigableSet q = new TreeSet<>(); - - // set-up vertices - for (Vertex v : graph.values()) { - v.previous = v == source ? source : null; - v.dist = v == source ? 0 : Integer.MAX_VALUE; - q.add(v); - } - - dijkstra(q); + // another pass to set neighbouring vertices + for (Edge e : edges) { + graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist); + // graph.get(e.v2).neighbours.put(graph.get(e.v1), e.dist); // also do this for an undirected + // graph } + } - /** - * Implementation of dijkstra's algorithm using a binary heap. - */ - private void dijkstra(final NavigableSet q) { - Vertex u, v; - while (!q.isEmpty()) { - // vertex with shortest distance (first iteration will return source) - u = q.pollFirst(); - if (u.dist == Integer.MAX_VALUE) - break; // we can ignore u (and any other remaining vertices) since they are unreachable - - // look at distances to each neighbour - for (Map.Entry a : u.neighbours.entrySet()) { - v = a.getKey(); // the neighbour in this iteration - - final int alternateDist = u.dist + a.getValue(); - if (alternateDist < v.dist) { // shorter path to neighbour found - q.remove(v); - v.dist = alternateDist; - v.previous = u; - q.add(v); - } - } - } + /** Runs dijkstra using a specified source vertex */ + public void dijkstra(String startName) { + if (!graph.containsKey(startName)) { + System.err.printf("Graph doesn't contain start vertex \"%s\"%n", startName); + return; + } + final Vertex source = graph.get(startName); + NavigableSet q = new TreeSet<>(); + + // set-up vertices + for (Vertex v : graph.values()) { + v.previous = v == source ? source : null; + v.dist = v == source ? 0 : Integer.MAX_VALUE; + q.add(v); } - /** - * Prints a path from the source to the specified vertex - */ - public void printPath(String endName) { - if (!graph.containsKey(endName)) { - System.err.printf("Graph doesn't contain end vertex \"%s\"%n", endName); - return; + dijkstra(q); + } + + /** Implementation of dijkstra's algorithm using a binary heap. */ + private void dijkstra(final NavigableSet q) { + Vertex u, v; + while (!q.isEmpty()) { + // vertex with shortest distance (first iteration will return source) + u = q.pollFirst(); + if (u.dist == Integer.MAX_VALUE) + break; // we can ignore u (and any other remaining vertices) since they are unreachable + + // look at distances to each neighbour + for (Map.Entry a : u.neighbours.entrySet()) { + v = a.getKey(); // the neighbour in this iteration + + final int alternateDist = u.dist + a.getValue(); + if (alternateDist < v.dist) { // shorter path to neighbour found + q.remove(v); + v.dist = alternateDist; + v.previous = u; + q.add(v); } - - graph.get(endName).printPath(); - System.out.println(); + } } + } - /** - * Prints the path from the source to every vertex (output order is not guaranteed) - */ - public void printAllPaths() { - for (Vertex v : graph.values()) { - v.printPath(); - System.out.println(); - } + /** Prints a path from the source to the specified vertex */ + public void printPath(String endName) { + if (!graph.containsKey(endName)) { + System.err.printf("Graph doesn't contain end vertex \"%s\"%n", endName); + return; } -} \ No newline at end of file + graph.get(endName).printPath(); + System.out.println(); + } + + /** Prints the path from the source to every vertex (output order is not guaranteed) */ + public void printAllPaths() { + for (Vertex v : graph.values()) { + v.printPath(); + System.out.println(); + } + } +} diff --git a/Others/EulersFunction.java b/Others/EulersFunction.java index 0f848442bc92..1e7efeafbd0b 100644 --- a/Others/EulersFunction.java +++ b/Others/EulersFunction.java @@ -2,26 +2,27 @@ /** * You can read more about Euler's totient function - *

- * See https://en.wikipedia.org/wiki/Euler%27s_totient_function + * + *

See https://en.wikipedia.org/wiki/Euler%27s_totient_function */ public class EulersFunction { - // This method returns us number of x that (x < n) and gcd(x, n) == 1 in O(sqrt(n)) time complexity; - public static int getEuler(int n) { - int result = n; - for (int i = 2; i * i <= n; i++) { - if (n % i == 0) { - while (n % i == 0) n /= i; - result -= result / i; - } - } - if (n > 1) result -= result / n; - return result; + // This method returns us number of x that (x < n) and gcd(x, n) == 1 in O(sqrt(n)) time + // complexity; + public static int getEuler(int n) { + int result = n; + for (int i = 2; i * i <= n; i++) { + if (n % i == 0) { + while (n % i == 0) n /= i; + result -= result / i; + } } + if (n > 1) result -= result / n; + return result; + } - public static void main(String[] args) { - for (int i = 1; i < 100; i++) { - System.out.println(getEuler(i)); - } + public static void main(String[] args) { + for (int i = 1; i < 100; i++) { + System.out.println(getEuler(i)); } + } } diff --git a/Others/FibToN.java b/Others/FibToN.java index 03aad56fd833..479e895729c4 100644 --- a/Others/FibToN.java +++ b/Others/FibToN.java @@ -3,31 +3,29 @@ import java.util.Scanner; /** - * Fibonacci sequence, and characterized by the fact that every number - * after the first two is the sum of the two preceding ones. - *

- * Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21,... - *

- * Source for the explanation: https://en.wikipedia.org/wiki/Fibonacci_number + * Fibonacci sequence, and characterized by the fact that every number after the first two is the + * sum of the two preceding ones. + * + *

Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21,... + * + *

Source for the explanation: https://en.wikipedia.org/wiki/Fibonacci_number */ - public class FibToN { - public static void main(String[] args) { - //take input - Scanner scn = new Scanner(System.in); - int N = scn.nextInt(); - // print all Fibonacci numbers that are smaller than your given input N - int first = 0, second = 1; - scn.close(); - while (first <= N) { - //print first fibo 0 then add second fibo into it while updating second as well + public static void main(String[] args) { + // take input + Scanner scn = new Scanner(System.in); + int N = scn.nextInt(); + // print all Fibonacci numbers that are smaller than your given input N + int first = 0, second = 1; + scn.close(); + while (first <= N) { + // print first fibo 0 then add second fibo into it while updating second as well - System.out.println(first); + System.out.println(first); - int next = first + second; - first = second; - second = next; - } + int next = first + second; + first = second; + second = next; } - + } } diff --git a/Others/FirstFit.java b/Others/FirstFit.java index 61a25b422017..06cea111c54d 100644 --- a/Others/FirstFit.java +++ b/Others/FirstFit.java @@ -2,69 +2,71 @@ import java.util.ArrayList; -/** - * @author Dekas Dimitrios - */ +/** @author Dekas Dimitrios */ public class FirstFit { - private static final int NO_ALLOCATION = -255; // if a process has been allocated in position -255, - // it means that it has not been actually allocated. + private static final int NO_ALLOCATION = + -255; // if a process has been allocated in position -255, + // it means that it has not been actually allocated. - /** - * Method to find the index of the memory block that is going to fit the given process based on the first fit algorithm. - * - * @param blocks: the array with the available memory blocks. - * @param process: the size of the process. - * @return the index of the block that fits, or -255 if no such block exists. - */ - private static int findFirstFit(int[] blockSizes, int processSize) { - for(int i=0 ; i < blockSizes.length ; i++) { - if(blockSizes[i] >= processSize) { - return i; - } - } - // If there is not a block that can fit the process, return -255 as the result - return NO_ALLOCATION; + /** + * Method to find the index of the memory block that is going to fit the given process based on + * the first fit algorithm. + * + * @param blocks: the array with the available memory blocks. + * @param process: the size of the process. + * @return the index of the block that fits, or -255 if no such block exists. + */ + private static int findFirstFit(int[] blockSizes, int processSize) { + for (int i = 0; i < blockSizes.length; i++) { + if (blockSizes[i] >= processSize) { + return i; + } } + // If there is not a block that can fit the process, return -255 as the result + return NO_ALLOCATION; + } - /** - * Method to allocate memory to blocks according to the first fit - * algorithm. It should return an ArrayList of Integers, where the - * index is the process ID (zero-indexed) and the value is the block - * number (also zero-indexed). - * - * @param sizeOfBlocks: an int array that contains the sizes of the memory blocks available. - * @param sizeOfProcesses: an int array that contains the sizes of the processes we need memory blocks for. - * @return the ArrayList filled with Integers repressenting the memory allocation that took place. - */ - static ArrayList firstFit(int[] sizeOfBlocks, int[] sizeOfProcesses) { - // The array list responsible for saving the memory allocations done by the first-fit algorithm - ArrayList memAlloc = new ArrayList<>(); - // Do this for every process - for(int processSize : sizeOfProcesses) { - int chosenBlockIdx = findFirstFit(sizeOfBlocks, processSize); // Find the index of the memory block going to be used - memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list - if(chosenBlockIdx != NO_ALLOCATION) { // Only if a block was chosen to store the process in it, - sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size - } - } - return memAlloc; + /** + * Method to allocate memory to blocks according to the first fit algorithm. It should return an + * ArrayList of Integers, where the index is the process ID (zero-indexed) and the value is the + * block number (also zero-indexed). + * + * @param sizeOfBlocks: an int array that contains the sizes of the memory blocks available. + * @param sizeOfProcesses: an int array that contains the sizes of the processes we need memory + * blocks for. + * @return the ArrayList filled with Integers repressenting the memory allocation that took place. + */ + static ArrayList firstFit(int[] sizeOfBlocks, int[] sizeOfProcesses) { + // The array list responsible for saving the memory allocations done by the first-fit algorithm + ArrayList memAlloc = new ArrayList<>(); + // Do this for every process + for (int processSize : sizeOfProcesses) { + int chosenBlockIdx = + findFirstFit( + sizeOfBlocks, processSize); // Find the index of the memory block going to be used + memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list + if (chosenBlockIdx + != NO_ALLOCATION) { // Only if a block was chosen to store the process in it, + sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size + } } + return memAlloc; + } - /** - * Method to print the memory allocated. - * - * @param memAllocation: an ArrayList of Integer representing the memory allocation done by the firstFit method. - */ - public static void printMemoryAllocation(ArrayList memAllocation) { - System.out.println("Process No.\tBlock No."); - System.out.println("===========\t========="); - for (int i = 0; i < memAllocation.size(); i++) { - System.out.print(" " + i + "\t\t"); - if (memAllocation.get(i) != NO_ALLOCATION) - System.out.print(memAllocation.get(i)); - else - System.out.print("Not Allocated"); - System.out.println(); - } + /** + * Method to print the memory allocated. + * + * @param memAllocation: an ArrayList of Integer representing the memory allocation done by the + * firstFit method. + */ + public static void printMemoryAllocation(ArrayList memAllocation) { + System.out.println("Process No.\tBlock No."); + System.out.println("===========\t========="); + for (int i = 0; i < memAllocation.size(); i++) { + System.out.print(" " + i + "\t\t"); + if (memAllocation.get(i) != NO_ALLOCATION) System.out.print(memAllocation.get(i)); + else System.out.print("Not Allocated"); + System.out.println(); } -} \ No newline at end of file + } +} diff --git a/Others/FloydTriangle.java b/Others/FloydTriangle.java index 70479dd24e63..73b988f72398 100644 --- a/Others/FloydTriangle.java +++ b/Others/FloydTriangle.java @@ -2,18 +2,17 @@ import java.util.Scanner; - 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: "); - int r = sc.nextInt(), n = 0; - sc.close(); - for (int i = 0; i < r; i++) { - for (int j = 0; j <= i; j++) { - System.out.print(++n + " "); - } - System.out.println(); - } + 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: "); + int r = sc.nextInt(), n = 0; + sc.close(); + for (int i = 0; i < r; i++) { + for (int j = 0; j <= i; j++) { + System.out.print(++n + " "); + } + System.out.println(); } + } } diff --git a/Others/GuassLegendre.java b/Others/GuassLegendre.java index 409f626478ba..a1df3e22b346 100644 --- a/Others/GuassLegendre.java +++ b/Others/GuassLegendre.java @@ -1,46 +1,41 @@ package Others; -import java.lang.Math; /** - * Guass Legendre Algorithm - * ref https://en.wikipedia.org/wiki/Gauss–Legendre_algorithm + * Guass Legendre Algorithm ref https://en.wikipedia.org/wiki/Gauss–Legendre_algorithm * * @author AKS1996 */ public class GuassLegendre { - public static void main(String[] args) { - for (int i = 1; i <= 3; ++i) - System.out.println(pi(i)); - - } - - static double pi(int l) { - /* - * l: No of loops to run - */ - - double a = 1, b = Math.pow(2, -0.5), t = 0.25, p = 1; - for (int i = 0; i < l; ++i) { - double temp[] = update(a, b, t, p); - a = temp[0]; - b = temp[1]; - t = temp[2]; - p = temp[3]; - } - - return Math.pow(a + b, 2) / (4 * t); + public static void main(String[] args) { + for (int i = 1; i <= 3; ++i) System.out.println(pi(i)); + } + + static double pi(int l) { + /* + * l: No of loops to run + */ + + double a = 1, b = Math.pow(2, -0.5), t = 0.25, p = 1; + for (int i = 0; i < l; ++i) { + double temp[] = update(a, b, t, p); + a = temp[0]; + b = temp[1]; + t = temp[2]; + p = temp[3]; } - static double[] update(double a, double b, double t, double p) { - double values[] = new double[4]; - values[0] = (a + b) / 2; - values[1] = Math.sqrt(a * b); - values[2] = t - p * Math.pow(a - values[0], 2); - values[3] = 2 * p; + return Math.pow(a + b, 2) / (4 * t); + } - return values; - } + static double[] update(double a, double b, double t, double p) { + double values[] = new double[4]; + values[0] = (a + b) / 2; + values[1] = Math.sqrt(a * b); + values[2] = t - p * Math.pow(a - values[0], 2); + values[3] = 2 * p; + return values; + } } diff --git a/Others/InsertDeleteInArray.java b/Others/InsertDeleteInArray.java index dfb702847275..20d81462136f 100644 --- a/Others/InsertDeleteInArray.java +++ b/Others/InsertDeleteInArray.java @@ -4,46 +4,45 @@ public class InsertDeleteInArray { - public static void main(String[] args) { - Scanner s = new Scanner(System.in); // Input statement - System.out.println("Enter the size of the array"); - int size = s.nextInt(); - int a[] = new int[size]; - int i; + public static void main(String[] args) { + Scanner s = new Scanner(System.in); // Input statement + System.out.println("Enter the size of the array"); + int size = s.nextInt(); + int a[] = new int[size]; + int i; - // To enter the initial elements - for (i = 0; i < size; i++) { - System.out.println("Enter the element"); - a[i] = s.nextInt(); - } + // To enter the initial elements + for (i = 0; i < size; i++) { + System.out.println("Enter the element"); + a[i] = s.nextInt(); + } - // To insert a new element(we are creating a new array) - System.out.println("Enter the index at which the element should be inserted"); - int insert_pos = s.nextInt(); - System.out.println("Enter the element to be inserted"); - int ins = s.nextInt(); - int size2 = size + 1; - int b[] = new int[size2]; - for (i = 0; i < size2; i++) { - if (i <= insert_pos) { - b[i] = a[i]; - } else { - b[i] = a[i - 1]; - } - } - b[insert_pos] = ins; - for (i = 0; i < size2; i++) { - System.out.println(b[i]); - } + // To insert a new element(we are creating a new array) + System.out.println("Enter the index at which the element should be inserted"); + int insert_pos = s.nextInt(); + System.out.println("Enter the element to be inserted"); + int ins = s.nextInt(); + int size2 = size + 1; + int b[] = new int[size2]; + for (i = 0; i < size2; i++) { + if (i <= insert_pos) { + b[i] = a[i]; + } else { + b[i] = a[i - 1]; + } + } + b[insert_pos] = ins; + for (i = 0; i < size2; i++) { + System.out.println(b[i]); + } - // To delete an element given the index - System.out.println("Enter the index at which element is to be deleted"); - int del_pos = s.nextInt(); - for (i = del_pos; i < size2 - 1; i++) { - b[i] = b[i + 1]; - } - for (i = 0; i < size2 - 1; i++) - System.out.println(b[i]); - s.close(); + // To delete an element given the index + System.out.println("Enter the index at which element is to be deleted"); + int del_pos = s.nextInt(); + for (i = del_pos; i < size2 - 1; i++) { + b[i] = b[i + 1]; } + for (i = 0; i < size2 - 1; i++) System.out.println(b[i]); + s.close(); + } } diff --git a/Others/KMP.java b/Others/KMP.java index e883076759ff..c221edf3f353 100644 --- a/Others/KMP.java +++ b/Others/KMP.java @@ -1,57 +1,53 @@ package Others; -/** - * Implementation of Knuth–Morris–Pratt algorithm - * Usage: see the main function for an example - */ +/** Implementation of Knuth–Morris–Pratt algorithm Usage: see the main function for an example */ public class KMP { - //a working example - public static void main(String[] args) { - final String haystack = "AAAAABAAABA"; //This is the full string - final String needle = "AAAA"; //This is the substring that we want to find - KMPmatcher(haystack, needle); + // a working example + public static void main(String[] args) { + final String haystack = "AAAAABAAABA"; // This is the full string + final String needle = "AAAA"; // This is the substring that we want to find + KMPmatcher(haystack, needle); + } + + // find the starting index in string haystack[] that matches the search word P[] + public static void KMPmatcher(final String haystack, final String needle) { + final int m = haystack.length(); + final int n = needle.length(); + final int[] pi = computePrefixFunction(needle); + int q = 0; + for (int i = 0; i < m; i++) { + while (q > 0 && haystack.charAt(i) != needle.charAt(q)) { + q = pi[q - 1]; + } + + if (haystack.charAt(i) == needle.charAt(q)) { + q++; + } + + if (q == n) { + System.out.println("Pattern starts: " + (i + 1 - n)); + q = pi[q - 1]; + } } - - // find the starting index in string haystack[] that matches the search word P[] - public static void KMPmatcher(final String haystack, final String needle) { - final int m = haystack.length(); - final int n = needle.length(); - final int[] pi = computePrefixFunction(needle); - int q = 0; - for (int i = 0; i < m; i++) { - while (q > 0 && haystack.charAt(i) != needle.charAt(q)) { - q = pi[q - 1]; - } - - if (haystack.charAt(i) == needle.charAt(q)) { - q++; - } - - if (q == n) { - System.out.println("Pattern starts: " + (i + 1 - n)); - q = pi[q - 1]; - } - } - } - - // return the prefix function - private static int[] computePrefixFunction(final String P) { - final int n = P.length(); - final int[] pi = new int[n]; - pi[0] = 0; - int q = 0; - for (int i = 1; i < n; i++) { - while (q > 0 && P.charAt(q) != P.charAt(i)) { - q = pi[q - 1]; - } - - if (P.charAt(q) == P.charAt(i)) { - q++; - } - - pi[i] = q; - - } - return pi; + } + + // return the prefix function + private static int[] computePrefixFunction(final String P) { + final int n = P.length(); + final int[] pi = new int[n]; + pi[0] = 0; + int q = 0; + for (int i = 1; i < n; i++) { + while (q > 0 && P.charAt(q) != P.charAt(i)) { + q = pi[q - 1]; + } + + if (P.charAt(q) == P.charAt(i)) { + q++; + } + + pi[i] = q; } -} \ No newline at end of file + return pi; + } +} diff --git a/Others/Krishnamurthy.java b/Others/Krishnamurthy.java index f2f3533a7549..d7a48522537f 100644 --- a/Others/Krishnamurthy.java +++ b/Others/Krishnamurthy.java @@ -3,28 +3,25 @@ import java.util.Scanner; class Krishnamurthy { - static int fact(int n) { - int i, p = 1; - for (i = n; i >= 1; i--) - p = p * i; - return p; - } + static int fact(int n) { + int i, p = 1; + for (i = n; i >= 1; i--) p = p * i; + return p; + } - public static void main(String args[]) { - Scanner sc = new Scanner(System.in); - int a, b, s = 0; - System.out.print("Enter the number : "); - a = sc.nextInt(); - int n = a; - while (a > 0) { - b = a % 10; - s = s + fact(b); - a = a / 10; - } - if (s == n) - System.out.print(n + " is a krishnamurthy number"); - else - System.out.print(n + " is not a krishnamurthy number"); - sc.close(); + public static void main(String args[]) { + Scanner sc = new Scanner(System.in); + int a, b, s = 0; + System.out.print("Enter the number : "); + a = sc.nextInt(); + int n = a; + while (a > 0) { + b = a % 10; + s = s + fact(b); + a = a / 10; } + if (s == n) System.out.print(n + " is a krishnamurthy number"); + else System.out.print(n + " is not a krishnamurthy number"); + sc.close(); + } } diff --git a/Others/LinearCongruentialGenerator.java b/Others/LinearCongruentialGenerator.java index 7ce224e0e9fe..d735d6a663e0 100644 --- a/Others/LinearCongruentialGenerator.java +++ b/Others/LinearCongruentialGenerator.java @@ -8,53 +8,55 @@ */ public class LinearCongruentialGenerator { - private double a, c, m, previousValue; + 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. + * 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; - } + /*** + * 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; - } + /** + * 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()); - } + 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()); } + } } diff --git a/Others/LowestBasePalindrome.java b/Others/LowestBasePalindrome.java index 2f8831100d3d..b6d169887524 100644 --- a/Others/LowestBasePalindrome.java +++ b/Others/LowestBasePalindrome.java @@ -4,144 +4,139 @@ import java.util.Scanner; /** - * Class for finding the lowest base in which a given integer is a palindrome. - * Includes auxiliary methods for converting between bases and reversing strings. - *

- * NOTE: There is potential for error, see note at line 63. + * Class for finding the lowest base in which a given integer is a palindrome. Includes auxiliary + * methods for converting between bases and reversing strings. + * + *

NOTE: There is potential for error, see note at line 63. * * @author RollandMichael * @version 2017.09.28 */ public class LowestBasePalindrome { - public static void main(String[] args) { - Scanner in = new Scanner(System.in); - int n = 0; - while (true) { - try { - System.out.print("Enter number: "); - n = in.nextInt(); - break; - } catch (InputMismatchException e) { - System.out.println("Invalid input!"); - in.next(); - } - } - System.out.println(n + " is a palindrome in base " + lowestBasePalindrome(n)); - System.out.println(base2base(Integer.toString(n), 10, lowestBasePalindrome(n))); - in.close(); + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + int n = 0; + while (true) { + try { + System.out.print("Enter number: "); + n = in.nextInt(); + break; + } catch (InputMismatchException e) { + System.out.println("Invalid input!"); + in.next(); + } } + System.out.println(n + " is a palindrome in base " + lowestBasePalindrome(n)); + System.out.println(base2base(Integer.toString(n), 10, lowestBasePalindrome(n))); + in.close(); + } - /** - * Given a number in base 10, returns the lowest base in which the - * number is represented by a palindrome (read the same left-to-right - * and right-to-left). - * - * @param num A number in base 10. - * @return The lowest base in which num is a palindrome. - */ - public static int lowestBasePalindrome(int num) { - int base, num2 = num; - int digit; - char digitC; - boolean foundBase = false; - String newNum = ""; - String digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + /** + * Given a number in base 10, returns the lowest base in which the number is represented by a + * palindrome (read the same left-to-right and right-to-left). + * + * @param num A number in base 10. + * @return The lowest base in which num is a palindrome. + */ + public static int lowestBasePalindrome(int num) { + int base, num2 = num; + int digit; + char digitC; + boolean foundBase = false; + String newNum = ""; + String digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; - while (!foundBase) { - // Try from bases 2 to num-1 - for (base = 2; base < num2; base++) { - newNum = ""; - while (num > 0) { - // Obtain the first digit of n in the current base, - // which is equivalent to the integer remainder of (n/base). - // The next digit is obtained by dividing n by the base and - // continuing the process of getting the remainder. This is done - // until n is <=0 and the number in the new base is obtained. - digit = (num % base); - num /= base; - // If the digit isn't in the set of [0-9][A-Z] (beyond base 36), its character - // form is just its value in ASCII. + while (!foundBase) { + // Try from bases 2 to num-1 + for (base = 2; base < num2; base++) { + newNum = ""; + while (num > 0) { + // Obtain the first digit of n in the current base, + // which is equivalent to the integer remainder of (n/base). + // The next digit is obtained by dividing n by the base and + // continuing the process of getting the remainder. This is done + // until n is <=0 and the number in the new base is obtained. + digit = (num % base); + num /= base; + // If the digit isn't in the set of [0-9][A-Z] (beyond base 36), its character + // form is just its value in ASCII. - // NOTE: This may cause problems, as the capital letters are ASCII values - // 65-90. It may cause false positives when one digit is, for instance 10 and assigned - // 'A' from the character array and the other is 65 and also assigned 'A'. + // NOTE: This may cause problems, as the capital letters are ASCII values + // 65-90. It may cause false positives when one digit is, for instance 10 and assigned + // 'A' from the character array and the other is 65 and also assigned 'A'. - // Regardless, the character is added to the representation of n - // in the current base. - if (digit >= digits.length()) { - digitC = (char) (digit); - newNum += digitC; - continue; - } - newNum += digits.charAt(digit); - } - // Num is assigned back its original value for the next iteration. - num = num2; - // Auxiliary method reverses the number. - String reverse = reverse(newNum); - // If the number is read the same as its reverse, then it is a palindrome. - // The current base is returned. - if (reverse.equals(newNum)) { - foundBase = true; - return base; - } - } + // Regardless, the character is added to the representation of n + // in the current base. + if (digit >= digits.length()) { + digitC = (char) (digit); + newNum += digitC; + continue; + } + newNum += digits.charAt(digit); } - // If all else fails, n is always a palindrome in base n-1. ("11") - return num - 1; + // Num is assigned back its original value for the next iteration. + num = num2; + // Auxiliary method reverses the number. + String reverse = reverse(newNum); + // If the number is read the same as its reverse, then it is a palindrome. + // The current base is returned. + if (reverse.equals(newNum)) { + foundBase = true; + return base; + } + } } + // If all else fails, n is always a palindrome in base n-1. ("11") + return num - 1; + } - private static String reverse(String str) { - String reverse = ""; - for (int i = str.length() - 1; i >= 0; i--) { - reverse += str.charAt(i); - } - return reverse; + private static String reverse(String str) { + String reverse = ""; + for (int i = str.length() - 1; i >= 0; i--) { + reverse += str.charAt(i); } + return reverse; + } - private 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; i < n.length(); i++) { - // store the character in charB1 - charB1 = n.charAt(i); - // if it is a non-number, convert it to a decimal value >9 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; - } + private 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; i < n.length(); i++) { + // store the character in charB1 + charB1 = n.charAt(i); + // if it is a non-number, convert it to a decimal value >9 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. + // 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; + // 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; + } } diff --git a/Others/PasswordGen.java b/Others/PasswordGen.java index c41768ad0685..018cffe6bacd 100644 --- a/Others/PasswordGen.java +++ b/Others/PasswordGen.java @@ -1,47 +1,44 @@ package Others; +import java.util.ArrayList; import java.util.Collections; -import java.util.Random; import java.util.List; -import java.util.ArrayList; - +import java.util.Random; /** - * Creates a random password from ASCII letters - * Given password length bounds + * Creates a random password from ASCII letters Given password length bounds * * @author AKS1996 * @date 2017.10.25 */ class PasswordGen { - public static void main(String args[]) { - String password = generatePassword(8, 16); - System.out.print("Password: " + password); - } + public static void main(String args[]) { + String password = generatePassword(8, 16); + System.out.print("Password: " + password); + } - static String generatePassword(int min_length, int max_length) { - Random random = new Random(); + static String generatePassword(int min_length, int max_length) { + Random random = new Random(); - String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; - String lower = "abcdefghijklmnopqrstuvwxyz"; - String numbers = "0123456789"; - String specialChars = "!@#$%^&*(){}?"; + String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + String lower = "abcdefghijklmnopqrstuvwxyz"; + String numbers = "0123456789"; + String specialChars = "!@#$%^&*(){}?"; - String allChars = upper + lower + numbers + specialChars; + String allChars = upper + lower + numbers + specialChars; - List letters = new ArrayList(); - for (char c : allChars.toCharArray()) - letters.add(c); + List letters = new ArrayList(); + for (char c : allChars.toCharArray()) letters.add(c); - // Inbuilt method to randomly shuffle a elements of a list - Collections.shuffle(letters); - StringBuilder password = new StringBuilder(); + // Inbuilt method to randomly shuffle a elements of a list + Collections.shuffle(letters); + StringBuilder password = new StringBuilder(); - // Note that size of the password is also random - for (int i = random.nextInt(max_length - min_length) + min_length; i > 0; --i) { - password .append( letters.get(random.nextInt(letters.size()))); - } - - return password.toString(); + // Note that size of the password is also random + for (int i = random.nextInt(max_length - min_length) + min_length; i > 0; --i) { + password.append(letters.get(random.nextInt(letters.size()))); } + + return password.toString(); + } } diff --git a/Others/PerlinNoise.java b/Others/PerlinNoise.java index f0e7f63dae31..4c1ad993a134 100644 --- a/Others/PerlinNoise.java +++ b/Others/PerlinNoise.java @@ -4,164 +4,165 @@ import java.util.Scanner; /** - * For detailed info and implementation see: Perlin-Noise + * For detailed info and implementation see: Perlin-Noise */ public class PerlinNoise { - /** - * @param width width of noise array - * @param height height of noise array - * @param octaveCount numbers of layers used for blending noise - * @param persistence value of impact each layer get while blending - * @param seed used for randomizer - * @return float array containing calculated "Perlin-Noise" values - */ - static float[][] generatePerlinNoise(int width, int height, int octaveCount, float persistence, long seed) { - final float[][] base = new float[width][height]; - final float[][] perlinNoise = new float[width][height]; - final float[][][] noiseLayers = new float[octaveCount][][]; - - Random random = new Random(seed); - //fill base array with random values as base for noise - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { - base[x][y] = random.nextFloat(); - } - } + /** + * @param width width of noise array + * @param height height of noise array + * @param octaveCount numbers of layers used for blending noise + * @param persistence value of impact each layer get while blending + * @param seed used for randomizer + * @return float array containing calculated "Perlin-Noise" values + */ + static float[][] generatePerlinNoise( + int width, int height, int octaveCount, float persistence, long seed) { + final float[][] base = new float[width][height]; + final float[][] perlinNoise = new float[width][height]; + final float[][][] noiseLayers = new float[octaveCount][][]; + + Random random = new Random(seed); + // fill base array with random values as base for noise + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + base[x][y] = random.nextFloat(); + } + } - //calculate octaves with different roughness - for (int octave = 0; octave < octaveCount; octave++) { - noiseLayers[octave] = generatePerlinNoiseLayer(base, width, height, octave); - } + // calculate octaves with different roughness + for (int octave = 0; octave < octaveCount; octave++) { + noiseLayers[octave] = generatePerlinNoiseLayer(base, width, height, octave); + } - float amplitude = 1f; - float totalAmplitude = 0f; - - //calculate perlin noise by blending each layer together with specific persistence - for (int octave = octaveCount - 1; octave >= 0; octave--) { - amplitude *= persistence; - totalAmplitude += amplitude; - - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { - //adding each value of the noise layer to the noise - //by increasing amplitude the rougher noises will have more impact - perlinNoise[x][y] += noiseLayers[octave][x][y] * amplitude; - } - } - } + float amplitude = 1f; + float totalAmplitude = 0f; - //normalize values so that they stay between 0..1 - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { - perlinNoise[x][y] /= totalAmplitude; - } - } + // calculate perlin noise by blending each layer together with specific persistence + for (int octave = octaveCount - 1; octave >= 0; octave--) { + amplitude *= persistence; + totalAmplitude += amplitude; - return perlinNoise; - } - - /** - * @param base base random float array - * @param width width of noise array - * @param height height of noise array - * @param octave current layer - * @return float array containing calculated "Perlin-Noise-Layer" values - */ - static float[][] generatePerlinNoiseLayer(float[][] base, int width, int height, int octave) { - float[][] perlinNoiseLayer = new float[width][height]; - - //calculate period (wavelength) for different shapes - int period = 1 << octave; //2^k - float frequency = 1f / period; // 1/2^k - - for (int x = 0; x < width; x++) { - //calculates the horizontal sampling indices - int x0 = (x / period) * period; - int x1 = (x0 + period) % width; - float horizintalBlend = (x - x0) * frequency; - - for (int y = 0; y < height; y++) { - //calculates the vertical sampling indices - int y0 = (y / period) * period; - int y1 = (y0 + period) % height; - float verticalBlend = (y - y0) * frequency; - - //blend top corners - float top = interpolate(base[x0][y0], base[x1][y0], horizintalBlend); - - //blend bottom corners - float bottom = interpolate(base[x0][y1], base[x1][y1], horizintalBlend); - - //blend top and bottom interpolation to get the final blend value for this cell - perlinNoiseLayer[x][y] = interpolate(top, bottom, verticalBlend); - } + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + // adding each value of the noise layer to the noise + // by increasing amplitude the rougher noises will have more impact + perlinNoise[x][y] += noiseLayers[octave][x][y] * amplitude; } - - return perlinNoiseLayer; + } } - /** - * @param a value of point a - * @param b value of point b - * @param alpha determine which value has more impact (closer to 0 -> a, closer to 1 -> b) - * @return interpolated value - */ - static float interpolate(float a, float b, float alpha) { - return a * (1 - alpha) + alpha * b; + // normalize values so that they stay between 0..1 + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + perlinNoise[x][y] /= totalAmplitude; + } } - public static void main(String[] args) { - Scanner in = new Scanner(System.in); - - final int width; - final int height; - final int octaveCount; - final float persistence; - final long seed; - final String charset; - final float[][] perlinNoise; - - System.out.println("Width (int): "); - width = in.nextInt(); - - System.out.println("Height (int): "); - height = in.nextInt(); - - System.out.println("Octave count (int): "); - octaveCount = in.nextInt(); - - System.out.println("Persistence (float): "); - persistence = in.nextFloat(); - - System.out.println("Seed (long): "); - seed = in.nextLong(); - - System.out.println("Charset (String): "); - charset = in.next(); - - - perlinNoise = generatePerlinNoise(width, height, octaveCount, persistence, seed); - final char[] chars = charset.toCharArray(); - final int length = chars.length; - final float step = 1f / length; - //output based on charset - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { - float value = step; - float noiseValue = perlinNoise[x][y]; - - for (char c : chars) { - if (noiseValue <= value) { - System.out.print(c); - break; - } - - value += step; - } - } + return perlinNoise; + } + + /** + * @param base base random float array + * @param width width of noise array + * @param height height of noise array + * @param octave current layer + * @return float array containing calculated "Perlin-Noise-Layer" values + */ + static float[][] generatePerlinNoiseLayer(float[][] base, int width, int height, int octave) { + float[][] perlinNoiseLayer = new float[width][height]; + + // calculate period (wavelength) for different shapes + int period = 1 << octave; // 2^k + float frequency = 1f / period; // 1/2^k + + for (int x = 0; x < width; x++) { + // calculates the horizontal sampling indices + int x0 = (x / period) * period; + int x1 = (x0 + period) % width; + float horizintalBlend = (x - x0) * frequency; + + for (int y = 0; y < height; y++) { + // calculates the vertical sampling indices + int y0 = (y / period) * period; + int y1 = (y0 + period) % height; + float verticalBlend = (y - y0) * frequency; + + // blend top corners + float top = interpolate(base[x0][y0], base[x1][y0], horizintalBlend); + + // blend bottom corners + float bottom = interpolate(base[x0][y1], base[x1][y1], horizintalBlend); + + // blend top and bottom interpolation to get the final blend value for this cell + perlinNoiseLayer[x][y] = interpolate(top, bottom, verticalBlend); + } + } - System.out.println(); + return perlinNoiseLayer; + } + + /** + * @param a value of point a + * @param b value of point b + * @param alpha determine which value has more impact (closer to 0 -> a, closer to 1 -> b) + * @return interpolated value + */ + static float interpolate(float a, float b, float alpha) { + return a * (1 - alpha) + alpha * b; + } + + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + + final int width; + final int height; + final int octaveCount; + final float persistence; + final long seed; + final String charset; + final float[][] perlinNoise; + + System.out.println("Width (int): "); + width = in.nextInt(); + + System.out.println("Height (int): "); + height = in.nextInt(); + + System.out.println("Octave count (int): "); + octaveCount = in.nextInt(); + + System.out.println("Persistence (float): "); + persistence = in.nextFloat(); + + System.out.println("Seed (long): "); + seed = in.nextLong(); + + System.out.println("Charset (String): "); + charset = in.next(); + + perlinNoise = generatePerlinNoise(width, height, octaveCount, persistence, seed); + final char[] chars = charset.toCharArray(); + final int length = chars.length; + final float step = 1f / length; + // output based on charset + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + float value = step; + float noiseValue = perlinNoise[x][y]; + + for (char c : chars) { + if (noiseValue <= value) { + System.out.print(c); + break; + } + + value += step; } - in.close(); + } + + System.out.println(); } + in.close(); + } } diff --git a/Others/QueueUsingTwoStacks.java b/Others/QueueUsingTwoStacks.java index d138f71aabfb..104f6b922088 100644 --- a/Others/QueueUsingTwoStacks.java +++ b/Others/QueueUsingTwoStacks.java @@ -5,156 +5,146 @@ /** * This implements Queue using two Stacks. * - * Big O Runtime: - * insert(): O(1) - * remove(): O(1) amortized - * isEmpty(): O(1) + *

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. + *

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 (https://www.github.com/sahilb2) - * */ class QueueWithStack { - // 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 QueueWithStack() { - 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(); - } - - /** - * Peek at the element from the front of the queue - * - * @return the front element of the queue - */ - public Object peekFront() { - 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.peek(); + // 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 QueueWithStack() { + 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()); + } } - - /** - * Peek at the element from the back of the queue - * - * @return the back element of the queue - */ - public Object peekBack() { - return this.inStack.peek(); - } - - /** - * Returns true if the queue is empty - * - * @return true if the queue is empty - */ - public boolean isEmpty() { - return (this.inStack.isEmpty() && this.outStack.isEmpty()); + return this.outStack.pop(); + } + + /** + * Peek at the element from the front of the queue + * + * @return the front element of the queue + */ + public Object peekFront() { + 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.peek(); + } + + /** + * Peek at the element from the back of the queue + * + * @return the back element of the queue + */ + public Object peekBack() { + return this.inStack.peek(); + } + + /** + * Returns true if the queue is empty + * + * @return true if the queue is empty + */ + public boolean isEmpty() { + return (this.inStack.isEmpty() && this.outStack.isEmpty()); + } } /** * This class is the example for the Queue class * * @author sahilb2 (https://www.github.com/sahilb2) - * */ public class QueueUsingTwoStacks { - /** - * Main method - * - * @param args Command line arguments - */ - public static void main(String args[]){ - QueueWithStack myQueue = new QueueWithStack(); - myQueue.insert(1); - System.out.println(myQueue.peekBack()); //Will print 1 - // instack: [(top) 1] - // outStack: [] - myQueue.insert(2); - System.out.println(myQueue.peekBack()); //Will print 2 - // instack: [(top) 2, 1] - // outStack: [] - myQueue.insert(3); - System.out.println(myQueue.peekBack()); //Will print 3 - // instack: [(top) 3, 2, 1] - // outStack: [] - myQueue.insert(4); - System.out.println(myQueue.peekBack()); //Will print 4 - // instack: [(top) 4, 3, 2, 1] - // outStack: [] - - System.out.println(myQueue.isEmpty()); //Will print false - - System.out.println(myQueue.remove()); //Will print 1 - System.out.println(myQueue.peekBack()); //Will print NULL - // instack: [] - // outStack: [(top) 2, 3, 4] - - myQueue.insert(5); - System.out.println(myQueue.peekFront()); //Will print 2 - // instack: [(top) 5] - // outStack: [(top) 2, 3, 4] - - myQueue.remove(); - System.out.println(myQueue.peekFront()); //Will print 3 - // instack: [(top) 5] - // outStack: [(top) 3, 4] - myQueue.remove(); - System.out.println(myQueue.peekFront()); //Will print 4 - // instack: [(top) 5] - // outStack: [(top) 4] - myQueue.remove(); - // instack: [(top) 5] - // outStack: [] - System.out.println(myQueue.peekFront()); //Will print 5 - // instack: [] - // outStack: [(top) 5] - myQueue.remove(); - // instack: [] - // outStack: [] - - System.out.println(myQueue.isEmpty()); //Will print true - - } + /** + * Main method + * + * @param args Command line arguments + */ + public static void main(String args[]) { + QueueWithStack myQueue = new QueueWithStack(); + myQueue.insert(1); + System.out.println(myQueue.peekBack()); // Will print 1 + // instack: [(top) 1] + // outStack: [] + myQueue.insert(2); + System.out.println(myQueue.peekBack()); // Will print 2 + // instack: [(top) 2, 1] + // outStack: [] + myQueue.insert(3); + System.out.println(myQueue.peekBack()); // Will print 3 + // instack: [(top) 3, 2, 1] + // outStack: [] + myQueue.insert(4); + System.out.println(myQueue.peekBack()); // Will print 4 + // instack: [(top) 4, 3, 2, 1] + // outStack: [] + + System.out.println(myQueue.isEmpty()); // Will print false + + System.out.println(myQueue.remove()); // Will print 1 + System.out.println(myQueue.peekBack()); // Will print NULL + // instack: [] + // outStack: [(top) 2, 3, 4] + + myQueue.insert(5); + System.out.println(myQueue.peekFront()); // Will print 2 + // instack: [(top) 5] + // outStack: [(top) 2, 3, 4] + + myQueue.remove(); + System.out.println(myQueue.peekFront()); // Will print 3 + // instack: [(top) 5] + // outStack: [(top) 3, 4] + myQueue.remove(); + System.out.println(myQueue.peekFront()); // Will print 4 + // instack: [(top) 5] + // outStack: [(top) 4] + myQueue.remove(); + // instack: [(top) 5] + // outStack: [] + System.out.println(myQueue.peekFront()); // Will print 5 + // instack: [] + // outStack: [(top) 5] + myQueue.remove(); + // instack: [] + // outStack: [] + + System.out.println(myQueue.isEmpty()); // Will print true + } } diff --git a/Others/RabinKarp.java b/Others/RabinKarp.java index ba1e6869db0a..7dafa00c7874 100644 --- a/Others/RabinKarp.java +++ b/Others/RabinKarp.java @@ -1,84 +1,79 @@ -/** - * @author Prateek Kumar Oraon (https://github.com/prateekKrOraon) - */ +/** @author Prateek Kumar Oraon (https://github.com/prateekKrOraon) */ import java.util.Scanner; -import java.lang.Math; -//An implementation of Rabin-Karp string matching algorithm -//Program will simply end if there is no match +// An implementation of Rabin-Karp string matching algorithm +// Program will simply end if there is no match public class RabinKarp { - public static Scanner scanner = null; - public final static int d = 256; + public static Scanner scanner = null; + public static final int d = 256; - public static void main(String[] args){ + public static void main(String[] args) { - scanner = new Scanner(System.in); - System.out.println("Enter String"); - String text = scanner.nextLine(); - System.out.println("Enter pattern"); - String pattern = scanner.nextLine(); + scanner = new Scanner(System.in); + System.out.println("Enter String"); + String text = scanner.nextLine(); + System.out.println("Enter pattern"); + String pattern = scanner.nextLine(); - int q = 101; - searchPat(text,pattern,q); + int q = 101; + searchPat(text, pattern, q); + } + private static void searchPat(String text, String pattern, int q) { + + int m = pattern.length(); + int n = text.length(); + int t = 0; + int p = 0; + int h = 1; + int j = 0; + int i = 0; + + h = (int) Math.pow(d, m - 1) % q; + + for (i = 0; i < m; i++) { + // hash value is calculated for each character and then added with the hash value of the next + // character for pattern + // as well as the text for length equal to the length of pattern + p = (d * p + pattern.charAt(i)) % q; + t = (d * t + text.charAt(i)) % q; } - private static void searchPat(String text, String pattern, int q) { + for (i = 0; i <= n - m; i++) { - int m = pattern.length(); - int n = text.length(); - int t = 0; - int p = 0; - int h = 1; - int j = 0; - int i = 0; + // if the calculated hash value of the pattern and text matches then + // all the characters of the pattern is matched with the text of length equal to length of the + // pattern + // if all matches then pattern exist in string + // if not then the hash value of the first character of the text is subtracted and hash value + // of the next character after the end + // of the evaluated characters is added + if (p == t) { - h = (int)Math.pow(d,m-1)%q; + // if hash value matches then the individual characters are matched + for (j = 0; j < m; j++) { - for(i =0 ; i< m; i++){ - //hash value is calculated for each character and then added with the hash value of the next character for pattern - // as well as the text for length equal to the length of pattern - p = (d*p + pattern.charAt(i))%q; - t = (d*t + text.charAt(i))%q; + // if not matched then break out of the loop + if (text.charAt(i + j) != pattern.charAt(j)) break; } - for(i=0; i<=n-m;i++){ - - //if the calculated hash value of the pattern and text matches then - //all the characters of the pattern is matched with the text of length equal to length of the pattern - //if all matches then pattern exist in string - //if not then the hash value of the first character of the text is subtracted and hash value of the next character after the end - //of the evaluated characters is added - if(p==t){ - - //if hash value matches then the individual characters are matched - for(j=0;j stack = new Stack<>(); - - //Main function - public static void main(String[] args) { - //To Create a Dummy Stack containing integers from 0-9 - for (int i = 0; i < 10; i++) { - stack.push(i); - } - System.out.println("STACK"); + // Stack + private static Stack stack = new Stack<>(); - //To print that dummy Stack - for (int k = 9; k >= 0; k--) { - System.out.println(k); - } - - //Reverse Function called - reverseUsingRecursion(stack); + // Main function + public static void main(String[] args) { + // To Create a Dummy Stack containing integers from 0-9 + for (int i = 0; i < 10; i++) { + stack.push(i); + } + System.out.println("STACK"); - System.out.println("REVERSED STACK : "); - //To print reversed stack - while (!stack.isEmpty()) { - System.out.println(stack.pop()); - } + // To print that dummy Stack + for (int k = 9; k >= 0; k--) { + System.out.println(k); + } + // Reverse Function called + reverseUsingRecursion(stack); + System.out.println("REVERSED STACK : "); + // To print reversed stack + while (!stack.isEmpty()) { + System.out.println(stack.pop()); } + } - //Function Used to reverse Stack Using Recursion - private static void reverseUsingRecursion(Stack stack) { - if (stack.isEmpty()) // If stack is empty then return - { - return; - } - /* All items are stored in call stack until we reach the end*/ - - int temptop = stack.peek(); - stack.pop(); - reverseUsingRecursion(stack); //Recursion call - insertAtEnd(temptop); // Insert items held in call stack one by one into stack + // Function Used to reverse Stack Using Recursion + private static void reverseUsingRecursion(Stack stack) { + if (stack.isEmpty()) // If stack is empty then return + { + return; } + /* All items are stored in call stack until we reach the end*/ - //Function used to insert element at the end of stack - private static void insertAtEnd(int temptop) { - if (stack.isEmpty()) { - stack.push(temptop); // If stack is empty push the element - } else { - int temp = stack.peek(); /* All the items are stored in call stack until we reach end*/ - stack.pop(); + int temptop = stack.peek(); + stack.pop(); + reverseUsingRecursion(stack); // Recursion call + insertAtEnd(temptop); // Insert items held in call stack one by one into stack + } - insertAtEnd(temptop); //Recursive call + // Function used to insert element at the end of stack + private static void insertAtEnd(int temptop) { + if (stack.isEmpty()) { + stack.push(temptop); // If stack is empty push the element + } else { + int temp = stack.peek(); /* All the items are stored in call stack until we reach end*/ + stack.pop(); - stack.push(temp); - } + insertAtEnd(temptop); // Recursive call + stack.push(temp); } - + } } diff --git a/Others/RootPrecision.java b/Others/RootPrecision.java index 71690a4b2591..4f9f86965c2b 100644 --- a/Others/RootPrecision.java +++ b/Others/RootPrecision.java @@ -4,33 +4,33 @@ public class RootPrecision { - public static void main(String[] args) { - // take input - Scanner scn = new Scanner(System.in); + public static void main(String[] args) { + // take input + Scanner scn = new Scanner(System.in); - // N is the input number - int N = scn.nextInt(); + // N is the input number + int N = scn.nextInt(); - // P is precision value for eg - P is 3 in 2.564 and 5 in 3.80870. - int P = scn.nextInt(); - System.out.println(squareRoot(N, P)); + // P is precision value for eg - P is 3 in 2.564 and 5 in 3.80870. + int P = scn.nextInt(); + System.out.println(squareRoot(N, P)); - scn.close(); - } + scn.close(); + } - public static double squareRoot(int N, int P) { - // rv means return value - double rv; + public static double squareRoot(int N, int P) { + // rv means return value + double rv; - double root = Math.pow(N, 0.5); + double root = Math.pow(N, 0.5); - // calculate precision to power of 10 and then multiply it with root value. - int precision = (int) Math.pow(10, P); - root = root * precision; - /*typecast it into integer then divide by precision and again typecast into double - so as to have decimal points upto P precision */ + // calculate precision to power of 10 and then multiply it with root value. + int precision = (int) Math.pow(10, P); + root = root * precision; + /*typecast it into integer then divide by precision and again typecast into double + so as to have decimal points upto P precision */ - rv = (int) root; - return rv / precision; - } -} \ No newline at end of file + rv = (int) root; + return rv / precision; + } +} diff --git a/Others/SJF.java b/Others/SJF.java index 247f3da0989f..9eb9e1844daf 100644 --- a/Others/SJF.java +++ b/Others/SJF.java @@ -1,182 +1,184 @@ package Others; /** + * + * *

Shortest job first.

- *

Shortest job first (SJF) or shortest job next, is a scheduling policy - * that selects the waiting process with the smallest execution time to execute next - * Shortest Job first has the advantage of having minimum average waiting time among all scheduling algorithms. - * It is a Greedy Algorithm. - * It may cause starvation if shorter processes keep coming. - * This problem has been solved using the concept of aging.

+ * + *

Shortest job first (SJF) or shortest job next, is a scheduling policy that selects the waiting + * process with the smallest execution time to execute next Shortest Job first has the advantage of + * having minimum average waiting time among all scheduling algorithms. It is a Greedy Algorithm. It + * may cause starvation if shorter processes keep coming. This problem has been solved using the + * concept of aging. * * @author shivg7706 * @since 2018/10/27 */ - -import java.util.Scanner; +import java.util.*; import java.util.ArrayList; import java.util.Comparator; -import java.util.*; +import java.util.Scanner; class Process { - public int pid; - public int arrivalTime; - public int burstTime; - public int priority; - public int turnAroundTime; - public int waitTime; - public int remainingTime; + public int pid; + public int arrivalTime; + public int burstTime; + public int priority; + public int turnAroundTime; + public int waitTime; + public int remainingTime; } class Schedule { - private int noOfProcess; - private int timer = 0; - private ArrayList processes; - private ArrayList remainingProcess; - private ArrayList gantChart; - private float burstAll; - private Map> arrivals; - - Schedule() { - Scanner in = new Scanner(System.in); - - processes = new ArrayList(); - remainingProcess = new ArrayList(); - - gantChart = new ArrayList<>(); - arrivals = new HashMap<>(); - - System.out.print("Enter the no. of processes: "); - noOfProcess = in.nextInt(); - System.out.println("Enter the arrival, burst and priority of processes"); - for (int i = 0; i < noOfProcess; i++) { - Process p = new Process(); - p.pid = i; - p.arrivalTime = in.nextInt(); - p.burstTime = in.nextInt(); - p.priority = in.nextInt(); - p.turnAroundTime = 0; - p.waitTime = 0; - p.remainingTime = p.burstTime; - - if (arrivals.get(p.arrivalTime) == null) { - arrivals.put(p.arrivalTime, new ArrayList()); - } - arrivals.get(p.arrivalTime).add(p); - processes.add(p); - burstAll += p.burstTime; - } - in.close(); - + private int noOfProcess; + private int timer = 0; + private ArrayList processes; + private ArrayList remainingProcess; + private ArrayList gantChart; + private float burstAll; + private Map> arrivals; + + Schedule() { + Scanner in = new Scanner(System.in); + + processes = new ArrayList(); + remainingProcess = new ArrayList(); + + gantChart = new ArrayList<>(); + arrivals = new HashMap<>(); + + System.out.print("Enter the no. of processes: "); + noOfProcess = in.nextInt(); + System.out.println("Enter the arrival, burst and priority of processes"); + for (int i = 0; i < noOfProcess; i++) { + Process p = new Process(); + p.pid = i; + p.arrivalTime = in.nextInt(); + p.burstTime = in.nextInt(); + p.priority = in.nextInt(); + p.turnAroundTime = 0; + p.waitTime = 0; + p.remainingTime = p.burstTime; + + if (arrivals.get(p.arrivalTime) == null) { + arrivals.put(p.arrivalTime, new ArrayList()); + } + arrivals.get(p.arrivalTime).add(p); + processes.add(p); + burstAll += p.burstTime; } + in.close(); + } + void startScheduling() { - void startScheduling() { + processes.sort( + new Comparator() { + @Override + public int compare(Process a, Process b) { + return a.arrivalTime - b.arrivalTime; + } + }); + + while (!(arrivals.size() == 0 && remainingProcess.size() == 0)) { + removeFinishedProcess(); + if (arrivals.get(timer) != null) { + remainingProcess.addAll(arrivals.get(timer)); + arrivals.remove(timer); + } + remainingProcess.sort( + new Comparator() { + private int alpha = 6; + private int beta = 1; - processes.sort(new Comparator() { @Override public int compare(Process a, Process b) { - return a.arrivalTime - b.arrivalTime; + int aRem = a.remainingTime; + int bRem = b.remainingTime; + int aprior = a.priority; + int bprior = b.priority; + return (alpha * aRem + beta * aprior) - (alpha * bRem + beta * bprior); } - }); + }); - while (!(arrivals.size() == 0 && remainingProcess.size() == 0)) { - removeFinishedProcess(); - if (arrivals.get(timer) != null) { - remainingProcess.addAll(arrivals.get(timer)); - arrivals.remove(timer); - } - - remainingProcess.sort(new Comparator() { - private int alpha = 6; - private int beta = 1; - - @Override - public int compare(Process a, Process b) { - int aRem = a.remainingTime; - int bRem = b.remainingTime; - int aprior = a.priority; - int bprior = b.priority; - return (alpha * aRem + beta * aprior) - (alpha * bRem + beta * bprior); - } - }); - - int k = timeElapsed(timer); - ageing(k); - timer++; - } - - System.out.println("Total time required: " + (timer - 1)); + int k = timeElapsed(timer); + ageing(k); + timer++; } - void removeFinishedProcess() { - ArrayList completed = new ArrayList(); - for (int i = 0; i < remainingProcess.size(); i++) { - if (remainingProcess.get(i).remainingTime == 0) { - completed.add(i); - } - } - - for (int i = 0; i < completed.size(); i++) { - int pid = remainingProcess.get(completed.get(i)).pid; - processes.get(pid).waitTime = remainingProcess.get(completed.get(i)).waitTime; - remainingProcess.remove(remainingProcess.get(completed.get(i))); - } - + System.out.println("Total time required: " + (timer - 1)); + } + void removeFinishedProcess() { + ArrayList completed = new ArrayList(); + for (int i = 0; i < remainingProcess.size(); i++) { + if (remainingProcess.get(i).remainingTime == 0) { + completed.add(i); + } } - public int timeElapsed(int i) { - if (!remainingProcess.isEmpty()) { - gantChart.add(i, remainingProcess.get(0).pid); - remainingProcess.get(0).remainingTime--; - return 1; - } - return 0; + for (int i = 0; i < completed.size(); i++) { + int pid = remainingProcess.get(completed.get(i)).pid; + processes.get(pid).waitTime = remainingProcess.get(completed.get(i)).waitTime; + remainingProcess.remove(remainingProcess.get(completed.get(i))); } + } - public void ageing(int k) { - for (int i = k; i < remainingProcess.size(); i++) { - remainingProcess.get(i).waitTime++; - if (remainingProcess.get(i).waitTime % 7 == 0) { - remainingProcess.get(i).priority--; - } - } + public int timeElapsed(int i) { + if (!remainingProcess.isEmpty()) { + gantChart.add(i, remainingProcess.get(0).pid); + remainingProcess.get(0).remainingTime--; + return 1; } + return 0; + } + + public void ageing(int k) { + for (int i = k; i < remainingProcess.size(); i++) { + remainingProcess.get(i).waitTime++; + if (remainingProcess.get(i).waitTime % 7 == 0) { + remainingProcess.get(i).priority--; + } + } + } + public void solve() { + System.out.println("Gant chart "); + for (int i = 0; i < gantChart.size(); i++) { + System.out.print(gantChart.get(i) + " "); + } + System.out.println(); - public void solve() { - System.out.println("Gant chart "); - for (int i = 0; i < gantChart.size(); i++) { - System.out.print(gantChart.get(i) + " "); - } - System.out.println(); - - float waitTimeTot = 0; - float tatTime = 0; - - for (int i = 0; i < noOfProcess; i++) { - processes.get(i).turnAroundTime = processes.get(i).waitTime + processes.get(i).burstTime; + float waitTimeTot = 0; + float tatTime = 0; - waitTimeTot += processes.get(i).waitTime; - tatTime += processes.get(i).turnAroundTime; + for (int i = 0; i < noOfProcess; i++) { + processes.get(i).turnAroundTime = processes.get(i).waitTime + processes.get(i).burstTime; - System.out.println("Process no.: " + i + " Wait time: " + processes.get(i).waitTime + " Turn Around Time: " + processes.get(i).turnAroundTime); - } + waitTimeTot += processes.get(i).waitTime; + tatTime += processes.get(i).turnAroundTime; - System.out.println("Average Waiting Time: " + waitTimeTot / noOfProcess); - System.out.println("Average TAT Time: " + tatTime / noOfProcess); - System.out.println("Throughput: " + (float) noOfProcess / (timer - 1)); + System.out.println( + "Process no.: " + + i + + " Wait time: " + + processes.get(i).waitTime + + " Turn Around Time: " + + processes.get(i).turnAroundTime); } + System.out.println("Average Waiting Time: " + waitTimeTot / noOfProcess); + System.out.println("Average TAT Time: " + tatTime / noOfProcess); + System.out.println("Throughput: " + (float) noOfProcess / (timer - 1)); + } } public class SJF { - public static void main(String[] args) { - Schedule s = new Schedule(); - s.startScheduling(); - s.solve(); - } -} \ No newline at end of file + public static void main(String[] args) { + Schedule s = new Schedule(); + s.startScheduling(); + s.solve(); + } +} diff --git a/Others/SieveOfEratosthenes.java b/Others/SieveOfEratosthenes.java index 465e600a59e9..f3759d2fdb56 100644 --- a/Others/SieveOfEratosthenes.java +++ b/Others/SieveOfEratosthenes.java @@ -1,49 +1,44 @@ package Others; -/** - * @author Varun Upadhyay (https://github.com/varunu28) - */ +/** @author Varun Upadhyay (https://github.com/varunu28) */ public class SieveOfEratosthenes { - /** - * This method implements the Sieve of Eratosthenes Algorithm - * - * @param n The number till which we have to check for prime - * Prints all the prime numbers till n - **/ + /** + * This method implements the Sieve of Eratosthenes Algorithm + * + * @param n The number till which we have to check for prime Prints all the prime numbers till n + */ + public static void findPrimesTillN(int n) { + int[] arr = new int[n + 1]; - public static void findPrimesTillN(int n) { - int[] arr = new int[n + 1]; - - for (int i = 0; i <= n; i++) { - arr[i] = 1; - } + for (int i = 0; i <= n; i++) { + arr[i] = 1; + } - arr[0] = arr[1] = 0; + arr[0] = arr[1] = 0; - for (int i = 2; i <= Math.sqrt(n); i++) { - if (arr[i] == 1) { - for (int j = 2; i * j <= n; j++) { - arr[i * j] = 0; - } - } - } - - for (int i = 0; i < n + 1; i++) { - if (arr[i] == 1) { - System.out.print(i + " "); - } + for (int i = 2; i <= Math.sqrt(n); i++) { + if (arr[i] == 1) { + for (int j = 2; i * j <= n; j++) { + arr[i * j] = 0; } + } + } - System.out.println(); + for (int i = 0; i < n + 1; i++) { + if (arr[i] == 1) { + System.out.print(i + " "); + } } - // Driver Program - public static void main(String[] args) { - int n = 100; + System.out.println(); + } - // Prints 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 - findPrimesTillN(n); - } + // Driver Program + public static void main(String[] args) { + int n = 100; + // Prints 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 + findPrimesTillN(n); + } } diff --git a/Others/SkylineProblem.java b/Others/SkylineProblem.java index 31dc961133aa..5be6501c9cc2 100644 --- a/Others/SkylineProblem.java +++ b/Others/SkylineProblem.java @@ -5,129 +5,128 @@ import java.util.Scanner; public class SkylineProblem { - Building[] building; - int count; + Building[] building; + int count; - public void run() { - Scanner sc = new Scanner(System.in); + public void run() { + Scanner sc = new Scanner(System.in); - int num = sc.nextInt(); - this.building = new Building[num]; + int num = sc.nextInt(); + this.building = new Building[num]; - for (int i = 0; i < num; i++) { - String input = sc.next(); - String[] data = input.split(","); - this.add(Integer.parseInt(data[0]), Integer.parseInt(data[1]), Integer.parseInt(data[2])); - } - this.print(this.findSkyline(0, num - 1)); - - sc.close(); + for (int i = 0; i < num; i++) { + String input = sc.next(); + String[] data = input.split(","); + this.add(Integer.parseInt(data[0]), Integer.parseInt(data[1]), Integer.parseInt(data[2])); } + this.print(this.findSkyline(0, num - 1)); - public void add(int left, int height, int right) { - building[count++] = new Building(left, height, right); - } + sc.close(); + } - public void print(ArrayList skyline) { - Iterator it = skyline.iterator(); + public void add(int left, int height, int right) { + building[count++] = new Building(left, height, right); + } - while (it.hasNext()) { - Skyline temp = it.next(); - System.out.print(temp.coordinates + "," + temp.height); - if (it.hasNext()) { - System.out.print(","); - } - } + public void print(ArrayList skyline) { + Iterator it = skyline.iterator(); + while (it.hasNext()) { + Skyline temp = it.next(); + System.out.print(temp.coordinates + "," + temp.height); + if (it.hasNext()) { + System.out.print(","); + } } + } - public ArrayList findSkyline(int start, int end) { - if (start == end) { - ArrayList list = new ArrayList<>(); - list.add(new Skyline(building[start].left, building[start].height)); - list.add(new Skyline(building[end].right, 0)); + public ArrayList findSkyline(int start, int end) { + if (start == end) { + ArrayList list = new ArrayList<>(); + list.add(new Skyline(building[start].left, building[start].height)); + list.add(new Skyline(building[end].right, 0)); - return list; - } + return list; + } - int mid = (start + end) / 2; + int mid = (start + end) / 2; - ArrayList sky1 = this.findSkyline(start, mid); - ArrayList sky2 = this.findSkyline(mid + 1, end); + ArrayList sky1 = this.findSkyline(start, mid); + ArrayList sky2 = this.findSkyline(mid + 1, end); - return this.mergeSkyline(sky1, sky2); - } + return this.mergeSkyline(sky1, sky2); + } - public ArrayList mergeSkyline(ArrayList sky1, ArrayList sky2) { - int currentH1 = 0, currentH2 = 0; - ArrayList skyline = new ArrayList<>(); - int maxH = 0; - - while (!sky1.isEmpty() && !sky2.isEmpty()) { - if (sky1.get(0).coordinates < sky2.get(0).coordinates) { - int currentX = sky1.get(0).coordinates; - currentH1 = sky1.get(0).height; - - if (currentH1 < currentH2) { - sky1.remove(0); - if (maxH != currentH2) skyline.add(new Skyline(currentX, currentH2)); - } else { - maxH = currentH1; - sky1.remove(0); - skyline.add(new Skyline(currentX, currentH1)); - } - } else { - int currentX = sky2.get(0).coordinates; - currentH2 = sky2.get(0).height; - - if (currentH2 < currentH1) { - sky2.remove(0); - if (maxH != currentH1) skyline.add(new Skyline(currentX, currentH1)); - } else { - maxH = currentH2; - sky2.remove(0); - skyline.add(new Skyline(currentX, currentH2)); - } - } - } + public ArrayList mergeSkyline(ArrayList sky1, ArrayList sky2) { + int currentH1 = 0, currentH2 = 0; + ArrayList skyline = new ArrayList<>(); + int maxH = 0; - while (!sky1.isEmpty()) { - skyline.add(sky1.get(0)); - sky1.remove(0); - } + while (!sky1.isEmpty() && !sky2.isEmpty()) { + if (sky1.get(0).coordinates < sky2.get(0).coordinates) { + int currentX = sky1.get(0).coordinates; + currentH1 = sky1.get(0).height; - while (!sky2.isEmpty()) { - skyline.add(sky2.get(0)); - sky2.remove(0); + if (currentH1 < currentH2) { + sky1.remove(0); + if (maxH != currentH2) skyline.add(new Skyline(currentX, currentH2)); + } else { + maxH = currentH1; + sky1.remove(0); + skyline.add(new Skyline(currentX, currentH1)); } - - return skyline; + } else { + int currentX = sky2.get(0).coordinates; + currentH2 = sky2.get(0).height; + + if (currentH2 < currentH1) { + sky2.remove(0); + if (maxH != currentH1) skyline.add(new Skyline(currentX, currentH1)); + } else { + maxH = currentH2; + sky2.remove(0); + skyline.add(new Skyline(currentX, currentH2)); + } + } } - public class Skyline { - public int coordinates; - public int height; + while (!sky1.isEmpty()) { + skyline.add(sky1.get(0)); + sky1.remove(0); + } - public Skyline(int coordinates, int height) { - this.coordinates = coordinates; - this.height = height; - } + while (!sky2.isEmpty()) { + skyline.add(sky2.get(0)); + sky2.remove(0); } - public class Building { - public int left; - public int height; - public int right; + return skyline; + } - public Building(int left, int height, int right) { - this.left = left; - this.height = height; - this.right = right; - } + public class Skyline { + public int coordinates; + public int height; + + public Skyline(int coordinates, int height) { + this.coordinates = coordinates; + this.height = height; } + } - public static void main(String[] args) { - SkylineProblem skylineProblem = new SkylineProblem(); - skylineProblem.run(); + public class Building { + public int left; + public int height; + public int right; + + public Building(int left, int height, int right) { + this.left = left; + this.height = height; + this.right = right; } + } + + public static void main(String[] args) { + SkylineProblem skylineProblem = new SkylineProblem(); + skylineProblem.run(); + } } diff --git a/Others/StackPostfixNotation.java b/Others/StackPostfixNotation.java index 2857199d0401..63b4d3c76a3a 100644 --- a/Others/StackPostfixNotation.java +++ b/Others/StackPostfixNotation.java @@ -3,40 +3,40 @@ import java.util.*; public class StackPostfixNotation { - 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)); - scanner.close(); - } - - // 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); + 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)); + scanner.close(); + } - 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(); + // 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); - 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); - } + 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); } - tokens.close(); - return s.pop(); + + // "+", "-", "*", "/" + } } + tokens.close(); + return s.pop(); + } } diff --git a/Others/StringMatchFiniteAutomata.java b/Others/StringMatchFiniteAutomata.java index 34eb60b70454..a6d3fbab4d62 100644 --- a/Others/StringMatchFiniteAutomata.java +++ b/Others/StringMatchFiniteAutomata.java @@ -1,91 +1,81 @@ -/** - * @author Prateek Kumar Oraon (https://github.com/prateekKrOraon) - */ +/** @author Prateek Kumar Oraon (https://github.com/prateekKrOraon) */ import java.util.Scanner; -//An implementaion of string matching using finite automata -public class StringMatchFiniteAutomata{ - - public static final int CHARS = 256; - public static int[][] FA; - public static Scanner scanner = null; - - public static void main(String[] args){ - - scanner = new Scanner(System.in); - System.out.println("Enter String"); - String text = scanner.nextLine(); - System.out.println("Enter pattern"); - String pat = scanner.nextLine(); - - searchPat(text, pat); - - scanner.close(); - - } - - public static void searchPat(String text, String pat){ - - int m = pat.length(); - int n = text.length(); - - FA = new int[m+1][CHARS]; - - computeFA(pat, m ,FA); - - int state = 0; - for(int i=0;i0; ns--){ - - if(pat.charAt(ns-1) == x){ - - for(int i=0; i 0; ns--) { + + if (pat.charAt(ns - 1) == x) { + + for (int i = 0; i < ns - 1; i++) { + + if (pat.charAt(i) != pat.charAt(state - ns + i + 1)) { + break; + } + + if (i == ns - 1) { + return ns; + } + } + } + } + + return 0; + } +} diff --git a/Others/ThreeSum.java b/Others/ThreeSum.java index 8ac2c13b4c42..9524bb6f54e4 100644 --- a/Others/ThreeSum.java +++ b/Others/ThreeSum.java @@ -1,60 +1,47 @@ package Others; -import java.util.Scanner; import java.util.Arrays; +import java.util.Scanner; /** * To find triplet equals to given sum in complexity O(n*log(n)) - * * - * Array must be sorted + *

Array must be sorted * * @author Ujjawal Joshi * @date 2020.05.18 - * - * Test Cases: - Input: - * 6 //Length of array - 12 3 4 1 6 9 - target=24 - * Output:3 9 12 - * Explanation: There is a triplet (12, 3 and 9) present - in the array whose sum is 24. - * - * - + *

Test Cases: Input: 6 //Length of array 12 3 4 1 6 9 target=24 Output:3 9 12 Explanation: + * There is a triplet (12, 3 and 9) present in the array whose sum is 24. */ - - -class ThreeSum{ - public static void main(String args[]) - { - Scanner sc =new Scanner(System.in); - int n=sc.nextInt(); //Length of an array - - int a[]=new int[n]; - - for(int i=0;i getDictionary() { - Map dictionary = new HashMap<>(); - FileInputStream fis = null; + public Map getDictionary() { + Map dictionary = new HashMap<>(); + FileInputStream fis = null; - try { + try { - fis = new FileInputStream(fileName); // open the file - int in = 0; - String s = ""; // init a empty word - in = fis.read(); // read one character + fis = new FileInputStream(fileName); // open the file + int in = 0; + String s = ""; // init a empty word + in = fis.read(); // read one character - while (-1 != in) { - if (Character.isLetter((char) in)) { - s += (char) in; //if get a letter, append to s - } else { - // this branch means an entire word has just been read - if (s.length() > 0) { - // see whether word exists or not - if (dictionary.containsKey(s)) { - // if exist, count++ - dictionary.put(s, dictionary.get(s) + 1); - } else { - // if not exist, initiate count of this word with 1 - dictionary.put(s, 1); - } - } - s = ""; // reInit a empty word - } - in = fis.read(); - } - return dictionary; - } catch (IOException e) { - e.printStackTrace(); - } finally { - try { - // you always have to close the I/O streams - if (fis != null) - fis.close(); - } catch (IOException e) { - e.printStackTrace(); - } + while (-1 != in) { + if (Character.isLetter((char) in)) { + s += (char) in; // if get a letter, append to s + } else { + // this branch means an entire word has just been read + if (s.length() > 0) { + // see whether word exists or not + if (dictionary.containsKey(s)) { + // if exist, count++ + dictionary.put(s, dictionary.get(s) + 1); + } else { + // if not exist, initiate count of this word with 1 + dictionary.put(s, 1); + } } - return null; + s = ""; // reInit a empty word + } + in = fis.read(); } + return dictionary; + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + // you always have to close the I/O streams + if (fis != null) fis.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + return null; } + } - public static void main(String[] args) { - // you can replace the filePath with yours - CountWords cw = new CountWords("/Users/lisanaaa/Desktop/words.txt"); - Map dictionary = cw.getDictionary(); // get the words dictionary: {word: frequency} + public static void main(String[] args) { + // you can replace the filePath with yours + CountWords cw = new CountWords("/Users/lisanaaa/Desktop/words.txt"); + Map dictionary = + cw.getDictionary(); // get the words dictionary: {word: frequency} - // we change the map to list for convenient sort - List> list = new ArrayList<>(dictionary.entrySet()); + // we change the map to list for convenient sort + List> list = new ArrayList<>(dictionary.entrySet()); - // sort by lambda valueComparator - list.sort(Comparator.comparing( - m -> m.getValue()) - ); + // sort by lambda valueComparator + list.sort(Comparator.comparing(m -> m.getValue())); - Scanner input = new Scanner(System.in); - int k = input.nextInt(); - while (k > list.size()) { - System.out.println("Retype a number, your number is too large"); - input = new Scanner(System.in); - k = input.nextInt(); - } - for (int i = 0; i < k; i++) { - System.out.println(list.get(list.size() - i - 1)); - } - input.close(); + Scanner input = new Scanner(System.in); + int k = input.nextInt(); + while (k > list.size()) { + System.out.println("Retype a number, your number is too large"); + input = new Scanner(System.in); + k = input.nextInt(); + } + for (int i = 0; i < k; i++) { + System.out.println(list.get(list.size() - i - 1)); } + input.close(); + } } - diff --git a/Others/TowerOfHanoi.java b/Others/TowerOfHanoi.java index 5648b3d2823d..c339739cc79e 100644 --- a/Others/TowerOfHanoi.java +++ b/Others/TowerOfHanoi.java @@ -3,22 +3,24 @@ import java.util.Scanner; class TowerOfHanoi { - public static void shift(int n, String startPole, String intermediatePole, String endPole) { - // if n becomes zero the program returns thus ending the loop. - if (n != 0) { - // Shift function is called in recursion for swapping the n-1 disc from the startPole to the intermediatePole - shift(n - 1, startPole, endPole, intermediatePole); - System.out.format("Move %d from %s to %s\n", n, startPole, endPole); // Result Printing - // Shift function is called in recursion for swapping the n-1 disc from the intermediatePole to the endPole - shift(n - 1, intermediatePole, startPole, endPole); - } + public static void shift(int n, String startPole, String intermediatePole, String endPole) { + // if n becomes zero the program returns thus ending the loop. + if (n != 0) { + // Shift function is called in recursion for swapping the n-1 disc from the startPole to the + // intermediatePole + shift(n - 1, startPole, endPole, intermediatePole); + System.out.format("Move %d from %s to %s\n", n, startPole, endPole); // Result Printing + // Shift function is called in recursion for swapping the n-1 disc from the intermediatePole + // to the endPole + shift(n - 1, intermediatePole, startPole, endPole); } + } - public static void main(String[] args) { - System.out.print("Enter number of discs on Pole 1: "); - Scanner scanner = new Scanner(System.in); - int numberOfDiscs = scanner.nextInt(); //input of number of discs on pole 1 - shift(numberOfDiscs, "Pole1", "Pole2", "Pole3"); //Shift function called - scanner.close(); - } + public static void main(String[] args) { + System.out.print("Enter number of discs on Pole 1: "); + Scanner scanner = new Scanner(System.in); + int numberOfDiscs = scanner.nextInt(); // input of number of discs on pole 1 + shift(numberOfDiscs, "Pole1", "Pole2", "Pole3"); // Shift function called + scanner.close(); + } } diff --git a/Others/TwoPointers.java b/Others/TwoPointers.java index 99040b552d98..ee38192d630c 100644 --- a/Others/TwoPointers.java +++ b/Others/TwoPointers.java @@ -4,47 +4,47 @@ /** * The two pointer technique is a useful tool to utilize when searching for pairs in a sorted array. - *

- * link: https://www.geeksforgeeks.org/two-pointers-technique/ + * + *

link: https://www.geeksforgeeks.org/two-pointers-technique/ */ class TwoPointers { - public static void main(String[] args) { - int[] arr = {10, 20, 35, 50, 75, 80}; - int key = 70; - assert isPairedSum(arr, key); /* 20 + 60 == 70 */ + public static void main(String[] args) { + int[] arr = {10, 20, 35, 50, 75, 80}; + int key = 70; + assert isPairedSum(arr, key); /* 20 + 60 == 70 */ - arr = new int[]{1, 2, 3, 4, 5, 6, 7}; - key = 13; - assert isPairedSum(arr, key); /* 6 + 7 == 13 */ + arr = new int[] {1, 2, 3, 4, 5, 6, 7}; + key = 13; + assert isPairedSum(arr, key); /* 6 + 7 == 13 */ - key = 14; - assert !isPairedSum(arr, key); - } + key = 14; + assert !isPairedSum(arr, key); + } - /** - * Given a sorted array arr (sorted in ascending order). - * Find if there exists any pair of elements such that their sum is equal to key. - * - * @param arr the array contains elements - * @param key the number to search - * @return {@code true} if there exists a pair of elements, {@code false} otherwise. - */ - private static boolean isPairedSum(int[] arr, int key) { - /* array sorting is necessary for this algorithm to function correctly */ - Arrays.sort(arr); - int i = 0; /* index of first element */ - int j = arr.length - 1; /* index of last element */ + /** + * Given a sorted array arr (sorted in ascending order). Find if there exists any pair of elements + * such that their sum is equal to key. + * + * @param arr the array contains elements + * @param key the number to search + * @return {@code true} if there exists a pair of elements, {@code false} otherwise. + */ + private static boolean isPairedSum(int[] arr, int key) { + /* array sorting is necessary for this algorithm to function correctly */ + Arrays.sort(arr); + int i = 0; /* index of first element */ + int j = arr.length - 1; /* index of last element */ - while (i < j) { - if (arr[i] + arr[j] == key) { - return true; - } else if (arr[i] + arr[j] < key) { - i++; - } else { - j--; - } - } - return false; + while (i < j) { + if (arr[i] + arr[j] == key) { + return true; + } else if (arr[i] + arr[j] < key) { + i++; + } else { + j--; + } } -} \ No newline at end of file + return false; + } +} diff --git a/Others/WorstFit.java b/Others/WorstFit.java index 0bb6c460b6b9..23753b28fef2 100644 --- a/Others/WorstFit.java +++ b/Others/WorstFit.java @@ -2,75 +2,79 @@ import java.util.ArrayList; -/** - * @author Dekas Dimitrios - */ +/** @author Dekas Dimitrios */ public class WorstFit { - private static final int NO_ALLOCATION = -255; // if a process has been allocated in position -255, - // it means that it has not been actually allocated. + private static final int NO_ALLOCATION = + -255; // if a process has been allocated in position -255, + // it means that it has not been actually allocated. - /** - * Method to find the index of the memory block that is going to fit the given process based on the worst fit algorithm. - * - * @param blocks: the array with the available memory blocks. - * @param process: the size of the process. - * @return the index of the block that fits, or -255 if no such block exists. - */ - private static int findWorstFit(int[] blockSizes, int processSize) { - int max = -1; - int index = -1; - for(int i=0 ; i < blockSizes.length ; i++) { // Find the index of the biggest memory block available. - if(blockSizes[i] > max) { - max = blockSizes[i]; - index = i; - } - } - // If the biggest memory block cannot fit the process, return -255 as the result - if(processSize > blockSizes[index]) { - return NO_ALLOCATION; - } - return index; + /** + * Method to find the index of the memory block that is going to fit the given process based on + * the worst fit algorithm. + * + * @param blocks: the array with the available memory blocks. + * @param process: the size of the process. + * @return the index of the block that fits, or -255 if no such block exists. + */ + private static int findWorstFit(int[] blockSizes, int processSize) { + int max = -1; + int index = -1; + for (int i = 0; + i < blockSizes.length; + i++) { // Find the index of the biggest memory block available. + if (blockSizes[i] > max) { + max = blockSizes[i]; + index = i; + } } + // If the biggest memory block cannot fit the process, return -255 as the result + if (processSize > blockSizes[index]) { + return NO_ALLOCATION; + } + return index; + } - /** - * Method to allocate memory to blocks according to the worst fit - * algorithm. It should return an ArrayList of Integers, where the - * index is the process ID (zero-indexed) and the value is the block - * number (also zero-indexed). - * - * @param sizeOfBlocks: an int array that contains the sizes of the memory blocks available. - * @param sizeOfProcesses: an int array that contains the sizes of the processes we need memory blocks for. - * @return the ArrayList filled with Integers repressenting the memory allocation that took place. - */ - static ArrayList worstFit(int[] sizeOfBlocks, int[] sizeOfProcesses) { - // The array list responsible for saving the memory allocations done by the worst-fit algorithm - ArrayList memAlloc = new ArrayList<>(); - // Do this for every process - for(int processSize : sizeOfProcesses) { - int chosenBlockIdx = findWorstFit(sizeOfBlocks, processSize); // Find the index of the memory block going to be used - memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list - if(chosenBlockIdx != NO_ALLOCATION) { // Only if a block was chosen to store the process in it, - sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size - } - } - return memAlloc; + /** + * Method to allocate memory to blocks according to the worst fit algorithm. It should return an + * ArrayList of Integers, where the index is the process ID (zero-indexed) and the value is the + * block number (also zero-indexed). + * + * @param sizeOfBlocks: an int array that contains the sizes of the memory blocks available. + * @param sizeOfProcesses: an int array that contains the sizes of the processes we need memory + * blocks for. + * @return the ArrayList filled with Integers repressenting the memory allocation that took place. + */ + static ArrayList worstFit(int[] sizeOfBlocks, int[] sizeOfProcesses) { + // The array list responsible for saving the memory allocations done by the worst-fit algorithm + ArrayList memAlloc = new ArrayList<>(); + // Do this for every process + for (int processSize : sizeOfProcesses) { + int chosenBlockIdx = + findWorstFit( + sizeOfBlocks, processSize); // Find the index of the memory block going to be used + memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list + if (chosenBlockIdx + != NO_ALLOCATION) { // Only if a block was chosen to store the process in it, + sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size + } } + return memAlloc; + } - /** - * Method to print the memory allocated. - * - * @param memAllocation: an ArrayList of Integer representing the memory allocation done by the worstFit method. - */ - public static void printMemoryAllocation(ArrayList memAllocation) { - System.out.println("Process No.\tBlock No."); - System.out.println("===========\t========="); - for (int i = 0; i < memAllocation.size(); i++) { - System.out.print(" " + i + "\t\t"); - if (memAllocation.get(i) != NO_ALLOCATION) - System.out.print(memAllocation.get(i)); - else - System.out.print("Not Allocated"); - System.out.println(); - } + /** + * Method to print the memory allocated. + * + * @param memAllocation: an ArrayList of Integer representing the memory allocation done by the + * worstFit method. + */ + public static void printMemoryAllocation(ArrayList memAllocation) { + System.out.println("Process No.\tBlock No."); + System.out.println("===========\t========="); + for (int i = 0; i < memAllocation.size(); i++) { + System.out.print(" " + i + "\t\t"); + if (memAllocation.get(i) != NO_ALLOCATION) System.out.print(memAllocation.get(i)); + else System.out.print("Not Allocated"); + System.out.println(); } -} \ No newline at end of file + } +} diff --git a/ProjectEuler/Problem01.java b/ProjectEuler/Problem01.java index fffb0eca7f35..a19876f86a9e 100644 --- a/ProjectEuler/Problem01.java +++ b/ProjectEuler/Problem01.java @@ -1,51 +1,51 @@ package ProjectEuler; /** - * If we list all the natural numbers below 10 that are multiples of 3 or 5, - * we get 3, 5, 6 and 9. The sum of these multiples is 23. - *

- * Find the sum of all the multiples of 3 or 5 below 1000. - *

- * Link: https://projecteuler.net/problem=1 + * If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. + * The sum of these multiples is 23. + * + *

Find the sum of all the multiples of 3 or 5 below 1000. + * + *

Link: https://projecteuler.net/problem=1 */ public class Problem01 { - public static void main(String[] args) { - int[][] testNumber = { - {3, 0}, - {4, 3}, - {10, 23}, - {1000, 233168}, - {-1, 0} - }; - - for (int[] ints : testNumber) { - assert solution1(ints[0]) == ints[1]; - assert solution2(ints[0]) == ints[1]; - } + public static void main(String[] args) { + int[][] testNumber = { + {3, 0}, + {4, 3}, + {10, 23}, + {1000, 233168}, + {-1, 0} + }; + + for (int[] ints : testNumber) { + assert solution1(ints[0]) == ints[1]; + assert solution2(ints[0]) == ints[1]; } - - private static int solution1(int n) { - int sum = 0; - for (int i = 3; i < n; ++i) { - if (i % 3 == 0 || i % 5 == 0) { - sum += i; - } - } - return sum; + } + + private static int solution1(int n) { + int sum = 0; + for (int i = 3; i < n; ++i) { + if (i % 3 == 0 || i % 5 == 0) { + sum += i; + } } + return sum; + } - private static int solution2(int n) { - int sum = 0; + private static int solution2(int n) { + int sum = 0; - int terms = (n - 1) / 3; - sum += terms * (6 + (terms - 1) * 3) / 2; + int terms = (n - 1) / 3; + sum += terms * (6 + (terms - 1) * 3) / 2; - terms = (n - 1) / 5; - sum += terms * (10 + (terms - 1) * 5) / 2; + terms = (n - 1) / 5; + sum += terms * (10 + (terms - 1) * 5) / 2; - terms = (n - 1) / 15; - sum -= terms * (30 + (terms - 1) * 15) / 2; + terms = (n - 1) / 15; + sum -= terms * (30 + (terms - 1) * 15) / 2; - return sum; - } -} \ No newline at end of file + return sum; + } +} diff --git a/ProjectEuler/Problem02.java b/ProjectEuler/Problem02.java index 5f8d1f051ebe..2d67c54f0353 100644 --- a/ProjectEuler/Problem02.java +++ b/ProjectEuler/Problem02.java @@ -1,43 +1,43 @@ package ProjectEuler; /** - * Each new term in the Fibonacci sequence is generated by adding the previous two terms. - * By starting with 1 and 2, the first 10 terms will be: - *

- * 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... - *

- * By considering the terms in the Fibonacci sequence whose values do not exceed four million, + * Each new term in the Fibonacci sequence is generated by adding the previous two terms. By + * starting with 1 and 2, the first 10 terms will be: + * + *

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... + * + *

By considering the terms in the Fibonacci sequence whose values do not exceed four million, * find the sum of the even-valued terms. - *

- * Link: https://projecteuler.net/problem=2 + * + *

Link: https://projecteuler.net/problem=2 */ public class Problem02 { - public static void main(String[] args) { - int[][] testNumbers = { - {10, 10}, /* 2 + 8 == 10 */ - {15, 10}, /* 2 + 8 == 10 */ - {2, 2}, - {1, 0}, - {89, 44} /* 2 + 8 + 34 == 44 */ - }; + public static void main(String[] args) { + int[][] testNumbers = { + {10, 10}, /* 2 + 8 == 10 */ + {15, 10}, /* 2 + 8 == 10 */ + {2, 2}, + {1, 0}, + {89, 44} /* 2 + 8 + 34 == 44 */ + }; - for (int[] ints : testNumbers) { - assert solution1(ints[0]) == ints[1]; - } + for (int[] ints : testNumbers) { + assert solution1(ints[0]) == ints[1]; } + } - private static int solution1(int n) { - int sum = 0; - int first = 1; - int second = 2; - while (second <= n) { - if (second % 2 == 0) { - sum += second; - } - int temp = first + second; - first = second; - second = temp; - } - return sum; + private static int solution1(int n) { + int sum = 0; + int first = 1; + int second = 2; + while (second <= n) { + if (second % 2 == 0) { + sum += second; + } + int temp = first + second; + first = second; + second = temp; } -} \ No newline at end of file + return sum; + } +} diff --git a/ProjectEuler/Problem04.java b/ProjectEuler/Problem04.java index b9d51f8bbf90..9f9a84bd62ab 100644 --- a/ProjectEuler/Problem04.java +++ b/ProjectEuler/Problem04.java @@ -1,41 +1,41 @@ package ProjectEuler; /** - * A palindromic number reads the same both ways. - * The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. - *

- * Find the largest palindrome made from the product of two 3-digit numbers. - *

- * link: https://projecteuler.net/problem=4 + * A palindromic number reads the same both ways. The largest palindrome made from the product of + * two 2-digit numbers is 9009 = 91 × 99. + * + *

Find the largest palindrome made from the product of two 3-digit numbers. + * + *

link: https://projecteuler.net/problem=4 */ public class Problem04 { - public static void main(String[] args) { + public static void main(String[] args) { - assert solution1(10000) == -1; - assert solution1(20000) == 19591; /* 19591 == 143*137 */ - assert solution1(30000) == 29992; /* 29992 == 184*163 */ - assert solution1(40000) == 39893; /* 39893 == 287*139 */ - assert solution1(50000) == 49894; /* 49894 == 494*101 */ - assert solution1(60000) == 59995; /* 59995 == 355*169 */ - assert solution1(70000) == 69996; /* 69996 == 614*114 */ - assert solution1(80000) == 79897; /* 79897 == 733*109 */ - assert solution1(90000) == 89798; /* 89798 == 761*118 */ - assert solution1(100000) == 99999; /* 100000 == 813*123 */ - } + assert solution1(10000) == -1; + assert solution1(20000) == 19591; /* 19591 == 143*137 */ + assert solution1(30000) == 29992; /* 29992 == 184*163 */ + assert solution1(40000) == 39893; /* 39893 == 287*139 */ + assert solution1(50000) == 49894; /* 49894 == 494*101 */ + assert solution1(60000) == 59995; /* 59995 == 355*169 */ + assert solution1(70000) == 69996; /* 69996 == 614*114 */ + assert solution1(80000) == 79897; /* 79897 == 733*109 */ + assert solution1(90000) == 89798; /* 89798 == 761*118 */ + assert solution1(100000) == 99999; /* 100000 == 813*123 */ + } - private static int solution1(int n) { - for (int i = n - 1; i >= 10000; --i) { - String strNumber = String.valueOf(i); + private static int solution1(int n) { + for (int i = n - 1; i >= 10000; --i) { + String strNumber = String.valueOf(i); - /* Test if strNumber is palindrome */ - if (new StringBuilder(strNumber).reverse().toString().equals(strNumber)) { - for (int divisor = 999; divisor >= 100; --divisor) { - if (i % divisor == 0 && String.valueOf(i / divisor).length() == 3) { - return i; - } - } - } + /* Test if strNumber is palindrome */ + if (new StringBuilder(strNumber).reverse().toString().equals(strNumber)) { + for (int divisor = 999; divisor >= 100; --divisor) { + if (i % divisor == 0 && String.valueOf(i / divisor).length() == 3) { + return i; + } } - return -1; /* not found */ + } } -} \ No newline at end of file + return -1; /* not found */ + } +} diff --git a/ProjectEuler/Problem06.java b/ProjectEuler/Problem06.java index f5361a39ba60..0c1fbecd9026 100644 --- a/ProjectEuler/Problem06.java +++ b/ProjectEuler/Problem06.java @@ -1,46 +1,42 @@ package ProjectEuler; /** - * The sum of the squares of the first ten natural numbers is, - * 1^2 + 2^2 + ... + 10^2 = 385 - * The square of the sum of the first ten natural numbers is, - * (1 + 2 + ... + 10)^2 = 552 = 3025 - * Hence the difference between the sum of the squares of the first ten natural - * numbers and the square of the sum is 3025 − 385 = 2640. - * Find the difference between the sum of the squares of the first N natural - * numbers and the square of the sum. - *

- * link: https://projecteuler.net/problem=6 + * The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385 The + * square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)^2 = 552 = 3025 Hence + * the difference between the sum of the squares of the first ten natural numbers and the square of + * the sum is 3025 − 385 = 2640. Find the difference between the sum of the squares of the first N + * natural numbers and the square of the sum. + * + *

link: https://projecteuler.net/problem=6 */ public class Problem06 { - public static void main(String[] args) { - int[][] testNumbers = { - {10, 2640}, - {15, 13160}, - {20, 41230}, - {50, 1582700} - }; + public static void main(String[] args) { + int[][] testNumbers = { + {10, 2640}, + {15, 13160}, + {20, 41230}, + {50, 1582700} + }; - for (int[] testNumber : testNumbers) { - assert solution1(testNumber[0]) == testNumber[1] - && solutions2(testNumber[0]) == testNumber[1]; - } + for (int[] testNumber : testNumbers) { + assert solution1(testNumber[0]) == testNumber[1] + && solutions2(testNumber[0]) == testNumber[1]; } + } - private static int solution1(int n) { - int sum1 = 0; - int sum2 = 0; - for (int i = 1; i <= n; ++i) { - sum1 += i * i; - sum2 += i; - } - return sum2 * sum2 - sum1; + private static int solution1(int n) { + int sum1 = 0; + int sum2 = 0; + for (int i = 1; i <= n; ++i) { + sum1 += i * i; + sum2 += i; } + return sum2 * sum2 - sum1; + } - - private static int solutions2(int n) { - int sumOfSquares = n * (n + 1) * (2 * n + 1) / 6; - int squareOfSum = (int) Math.pow((n * (n + 1) / 2.0), 2); - return squareOfSum - sumOfSquares; - } -} \ No newline at end of file + private static int solutions2(int n) { + int sumOfSquares = n * (n + 1) * (2 * n + 1) / 6; + int squareOfSum = (int) Math.pow((n * (n + 1) / 2.0), 2); + return squareOfSum - sumOfSquares; + } +} diff --git a/ProjectEuler/Problem07.java b/ProjectEuler/Problem07.java index cba097c156a6..25df143c9513 100644 --- a/ProjectEuler/Problem07.java +++ b/ProjectEuler/Problem07.java @@ -1,59 +1,60 @@ package ProjectEuler; /** - * By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. - *

- * What is the 10 001st prime number? - *

- * link: https://projecteuler.net/problem=7 + * By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is + * 13. + * + *

What is the 10 001st prime number? + * + *

link: https://projecteuler.net/problem=7 */ public class Problem07 { - public static void main(String[] args) { - int[][] testNumbers = { - {1, 2}, - {2, 3}, - {3, 5}, - {4, 7}, - {5, 11}, - {6, 13}, - {20, 71}, - {50, 229}, - {100, 541} - }; - for (int[] number : testNumbers) { - assert solution1(number[0]) == number[1]; - } + public static void main(String[] args) { + int[][] testNumbers = { + {1, 2}, + {2, 3}, + {3, 5}, + {4, 7}, + {5, 11}, + {6, 13}, + {20, 71}, + {50, 229}, + {100, 541} + }; + for (int[] number : testNumbers) { + assert solution1(number[0]) == number[1]; } + } - /*** - * Checks if a number is prime or not - * @param number the number - * @return {@code true} if {@code number} is prime - */ - private static boolean isPrime(int number) { - if (number == 2) { - return true; - } - if (number < 2 || number % 2 == 0) { - return false; - } - for (int i = 3, limit = (int) Math.sqrt(number); i <= limit; i += 2) { - if (number % i == 0) { - return false; - } - } - return true; + /*** + * Checks if a number is prime or not + * @param number the number + * @return {@code true} if {@code number} is prime + */ + private static boolean isPrime(int number) { + if (number == 2) { + return true; } + if (number < 2 || number % 2 == 0) { + return false; + } + for (int i = 3, limit = (int) Math.sqrt(number); i <= limit; i += 2) { + if (number % i == 0) { + return false; + } + } + return true; + } - private static int solution1(int n) { - int count = 0; - int number = 1; + private static int solution1(int n) { + int count = 0; + int number = 1; - while (count != n) { - if (isPrime(++number)) { - count++; - } - } - return number; + while (count != n) { + if (isPrime(++number)) { + count++; + } } -} \ No newline at end of file + return number; + } +} diff --git a/ProjectEuler/Problem09.java b/ProjectEuler/Problem09.java index 5d259d506c5c..b0dbebb940c8 100644 --- a/ProjectEuler/Problem09.java +++ b/ProjectEuler/Problem09.java @@ -2,29 +2,27 @@ /** * A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, - *

- * a^2 + b^2 = c^2 - * For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. - *

- * There exists exactly one Pythagorean triplet for which a + b + c = 1000. - * Find the product abc. - *

- * link: https://projecteuler.net/problem=9 + * + *

a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. + * + *

There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. + * + *

link: https://projecteuler.net/problem=9 */ public class Problem09 { - public static void main(String[] args) { - assert solution1() == 31875000; - } + public static void main(String[] args) { + assert solution1() == 31875000; + } - private static int solution1() { - for (int i = 0; i <= 300; ++i) { - for (int j = 0; j <= 400; ++j) { - int k = 1000 - i - j; - if (i * i + j * j == k * k) { - return i * j * k; - } - } + private static int solution1() { + for (int i = 0; i <= 300; ++i) { + for (int j = 0; j <= 400; ++j) { + int k = 1000 - i - j; + if (i * i + j * j == k * k) { + return i * j * k; } - return -1; /* should not happen */ + } } -} \ No newline at end of file + return -1; /* should not happen */ + } +} diff --git a/ProjectEuler/Problem10.java b/ProjectEuler/Problem10.java index 451948c524dc..a51a22287358 100644 --- a/ProjectEuler/Problem10.java +++ b/ProjectEuler/Problem10.java @@ -2,54 +2,54 @@ /** * The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. - *

- * Find the sum of all the primes below two million. - *

- * link: https://projecteuler.net/problem=10 + * + *

Find the sum of all the primes below two million. + * + *

link: https://projecteuler.net/problem=10 */ public class Problem10 { - public static void main(String[] args) { - long[][] testNumbers = { - {2000000, 142913828922L}, - {10000, 5736396}, - {5000, 1548136}, - {1000, 76127}, - {10, 17}, - {7, 10} - }; + public static void main(String[] args) { + long[][] testNumbers = { + {2000000, 142913828922L}, + {10000, 5736396}, + {5000, 1548136}, + {1000, 76127}, + {10, 17}, + {7, 10} + }; - for (long[] testNumber : testNumbers) { - assert solution1(testNumber[0]) == testNumber[1]; - } + for (long[] testNumber : testNumbers) { + assert solution1(testNumber[0]) == testNumber[1]; } + } - /*** - * Checks if a number is prime or not - * @param n the number - * @return {@code true} if {@code n} is prime - */ - private static boolean isPrime(int n) { - if (n == 2) { - return true; - } - if (n < 2 || n % 2 == 0) { - return false; - } - for (int i = 3, limit = (int) Math.sqrt(n); i <= limit; i += 2) { - if (n % i == 0) { - return false; - } - } - return true; + /*** + * Checks if a number is prime or not + * @param n the number + * @return {@code true} if {@code n} is prime + */ + private static boolean isPrime(int n) { + if (n == 2) { + return true; } + if (n < 2 || n % 2 == 0) { + return false; + } + for (int i = 3, limit = (int) Math.sqrt(n); i <= limit; i += 2) { + if (n % i == 0) { + return false; + } + } + return true; + } - private static long solution1(long n) { - long sum = 0; - for (int i = 2; i < n; ++i) { - if (isPrime(i)) { - sum += i; - } - } - return sum; + private static long solution1(long n) { + long sum = 0; + for (int i = 2; i < n; ++i) { + if (isPrime(i)) { + sum += i; + } } -} \ No newline at end of file + return sum; + } +} diff --git a/ProjectEuler/Problem12.java b/ProjectEuler/Problem12.java index 89ea3e0ac35f..9743bc9d1b86 100644 --- a/ProjectEuler/Problem12.java +++ b/ProjectEuler/Problem12.java @@ -1,66 +1,54 @@ package ProjectEuler; /** - * The sequence of triangle numbers is generated by adding the natural numbers. - * So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. - * The first ten terms would be: - *

- * 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... - *

- * Let us list the factors of the first seven triangle numbers: - *

- * 1: 1 - * 3: 1,3 - * 6: 1,2,3,6 - * 10: 1,2,5,10 - * 15: 1,3,5,15 - * 21: 1,3,7,21 - * 28: 1,2,4,7,14,28 - * We can see that 28 is the first triangle number to have over five divisors. - *

- * What is the value of the first triangle number to have over five hundred divisors? - *

- * link: https://projecteuler.net/problem=12 + * The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle + * number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: + * + *

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... + * + *

Let us list the factors of the first seven triangle numbers: + * + *

1: 1 3: 1,3 6: 1,2,3,6 10: 1,2,5,10 15: 1,3,5,15 21: 1,3,7,21 28: 1,2,4,7,14,28 We can see + * that 28 is the first triangle number to have over five divisors. + * + *

What is the value of the first triangle number to have over five hundred divisors? + * + *

link: https://projecteuler.net/problem=12 */ public class Problem12 { - /** - * Driver Code - */ - public static void main(String[] args) { - assert solution1(500) == 76576500; - } + /** Driver Code */ + public static void main(String[] args) { + assert solution1(500) == 76576500; + } - /* returns the nth triangle number; that is, the sum of all the natural numbers less than, or equal to, n */ - public static int triangleNumber(int n) { - int sum = 0; - for (int i = 0; i <= n; i++) - sum += i; - return sum; - } + /* returns the nth triangle number; that is, the sum of all the natural numbers less than, or equal to, n */ + public static int triangleNumber(int n) { + int sum = 0; + for (int i = 0; i <= n; i++) sum += i; + return sum; + } - public static int solution1(int number) { - int j = 0; // j represents the jth triangle number - int n = 0; // n represents the triangle number corresponding to j - int numberOfDivisors = 0; // number of divisors for triangle number n + public static int solution1(int number) { + int j = 0; // j represents the jth triangle number + int n = 0; // n represents the triangle number corresponding to j + int numberOfDivisors = 0; // number of divisors for triangle number n - while (numberOfDivisors <= number) { + while (numberOfDivisors <= number) { - // resets numberOfDivisors because it's now checking a new triangle number - // and also sets n to be the next triangle number - numberOfDivisors = 0; - j++; - n = triangleNumber(j); + // resets numberOfDivisors because it's now checking a new triangle number + // and also sets n to be the next triangle number + numberOfDivisors = 0; + j++; + n = triangleNumber(j); - // for every number from 1 to the square root of this triangle number, - // count the number of divisors - for (int i = 1; i <= Math.sqrt(n); i++) - if (n % i == 0) - numberOfDivisors++; + // for every number from 1 to the square root of this triangle number, + // count the number of divisors + for (int i = 1; i <= Math.sqrt(n); i++) if (n % i == 0) numberOfDivisors++; - // 1 to the square root of the number holds exactly half of the divisors - // so multiply it by 2 to include the other corresponding half - numberOfDivisors *= 2; - } - return n; + // 1 to the square root of the number holds exactly half of the divisors + // so multiply it by 2 to include the other corresponding half + numberOfDivisors *= 2; } + return n; + } } diff --git a/Searches/BinarySearch.java b/Searches/BinarySearch.java index 8c7e113cc885..b7dc37dc9267 100644 --- a/Searches/BinarySearch.java +++ b/Searches/BinarySearch.java @@ -1,95 +1,91 @@ package Searches; +import static java.lang.String.format; + import java.util.Arrays; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.IntStream; -import static java.lang.String.format; - /** + * Binary search is one of the most popular algorithms The algorithm finds the position of a target + * value within a sorted array * - * - * - * Binary search is one of the most popular algorithms - * The algorithm finds the position of a target value within a sorted array - * - * Worst-case performance O(log n) - * Best-case performance O(1) - * Average performance O(log n) - * Worst-case space complexity O(1) - * + *

Worst-case performance O(log n) Best-case performance O(1) Average performance O(log n) + * Worst-case space complexity O(1) * * @author Varun Upadhyay (https://github.com/varunu28) * @author Podshivalov Nikita (https://github.com/nikitap492) - * * @see SearchAlgorithm * @see IterativeBinarySearch - * */ - class BinarySearch implements SearchAlgorithm { - /** - * - * @param array is an array where the element should be found - * @param key is an element which should be found - * @param is any comparable type - * @return index of the element - */ - @Override - public > int find(T[] array, T key) { - return search(array, key, 0, array.length); - } - - /** - * This method implements the Generic Binary Search - * - * @param array The array to make the binary search - * @param key The number you are looking for - * @param left The lower bound - * @param right The upper bound - * @return the location of the key - **/ - private > int search(T array[], T key, int left, int right){ - if (right < left) return -1; // this means that the key not found - - // find median - int median = (left + right) >>> 1; - int comp = key.compareTo(array[median]); - - if (comp == 0) { - return median; - } else if (comp < 0) { - return search(array, key, left, median - 1); - } else { - return search(array, key, median + 1, right); - } + /** + * @param array is an array where the element should be found + * @param key is an element which should be found + * @param is any comparable type + * @return index of the element + */ + @Override + public > int find(T[] array, T key) { + return search(array, key, 0, array.length); + } + + /** + * This method implements the Generic Binary Search + * + * @param array The array to make the binary search + * @param key The number you are looking for + * @param left The lower bound + * @param right The upper bound + * @return the location of the key + */ + private > int search(T array[], T key, int left, int right) { + if (right < left) return -1; // this means that the key not found + + // find median + int median = (left + right) >>> 1; + int comp = key.compareTo(array[median]); + + if (comp == 0) { + return median; + } else if (comp < 0) { + return search(array, key, left, median - 1); + } else { + return search(array, key, median + 1, right); } + } - // Driver Program - public static void main(String[] args) { - // Just generate data - Random r = ThreadLocalRandom.current(); + // Driver Program + public static void main(String[] args) { + // Just generate data + Random r = ThreadLocalRandom.current(); - int size = 100; - int maxElement = 100000; + int size = 100; + int maxElement = 100000; - Integer[] integers = IntStream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().boxed().toArray(Integer[]::new); + Integer[] integers = + IntStream.generate(() -> r.nextInt(maxElement)) + .limit(size) + .sorted() + .boxed() + .toArray(Integer[]::new); + // The element that should be found + int shouldBeFound = integers[r.nextInt(size - 1)]; - // The element that should be found - int shouldBeFound = integers[r.nextInt(size - 1)]; + BinarySearch search = new BinarySearch(); + int atIndex = search.find(integers, shouldBeFound); - BinarySearch search = new BinarySearch(); - int atIndex = search.find(integers, shouldBeFound); - - System.out.println(format( + System.out.println( + format( "Should be found: %d. Found %d at index %d. An array length %d", - shouldBeFound, integers[atIndex], atIndex, size - )); + shouldBeFound, integers[atIndex], atIndex, size)); - int toCheck = Arrays.binarySearch(integers, shouldBeFound); - System.out.println(format("Found by system method at an index: %d. Is equal: %b", toCheck, toCheck == atIndex)); - } + int toCheck = Arrays.binarySearch(integers, shouldBeFound); + System.out.println( + format( + "Found by system method at an index: %d. Is equal: %b", toCheck, toCheck == atIndex)); + } } diff --git a/Searches/InterpolationSearch.java b/Searches/InterpolationSearch.java index 1b4f64a818b5..50e8686f6ddd 100644 --- a/Searches/InterpolationSearch.java +++ b/Searches/InterpolationSearch.java @@ -1,75 +1,70 @@ package Searches; +import static java.lang.String.format; + import java.util.Arrays; import java.util.Random; import java.util.stream.IntStream; -import static java.lang.String.format; - /** * Interpolation search algorithm implementation - *

- * Worst-case performance O(n) - * Best-case performance O(1) - * Average performance O(log(log(n))) if the elements are uniformly distributed if not O(n) - * Worst-case space complexity O(1) + * + *

Worst-case performance O(n) Best-case performance O(1) Average performance O(log(log(n))) if + * the elements are uniformly distributed if not O(n) Worst-case space complexity O(1) * * @author Podshivalov Nikita (https://github.com/nikitap492) */ class InterpolationSearch { - - /** - * @param array is a sorted array - * @param key is a value what shoulb be found in the array - * @return an index if the array contains the key unless -1 - */ - public int find(int array[], int key) { - // Find indexes of two corners - int start = 0, end = (array.length - 1); - - // Since array is sorted, an element present - // in array must be in range defined by corner - while (start <= end && key >= array[start] && key <= array[end]) { - // Probing the position with keeping - // uniform distribution in mind. - int pos = start + (((end - start) / (array[end] - array[start])) * (key - array[start])); - - // Condition of target found - if (array[pos] == key) - return pos; - - // If key is larger, key is in upper part - if (array[pos] < key) - start = pos + 1; - - // If key is smaller, x is in lower part - else - end = pos - 1; - } - return -1; - } - - // Driver method - public static void main(String[] args) { - Random r = new Random(); - int size = 100; - int maxElement = 100000; - int[] integers = IntStream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray(); - - - //the element that should be found - Integer shouldBeFound = integers[r.nextInt(size - 1)]; - - InterpolationSearch search = new InterpolationSearch(); - int atIndex = search.find(integers, shouldBeFound); - - System.out.println(String.format("Should be found: %d. Found %d at index %d. An array length %d" - , shouldBeFound, integers[atIndex], atIndex, size)); - - - int toCheck = Arrays.binarySearch(integers, shouldBeFound); - System.out.println(format("Found by system method at an index: %d. Is equal: %b", toCheck, toCheck == atIndex)); + /** + * @param array is a sorted array + * @param key is a value what shoulb be found in the array + * @return an index if the array contains the key unless -1 + */ + public int find(int array[], int key) { + // Find indexes of two corners + int start = 0, end = (array.length - 1); + + // Since array is sorted, an element present + // in array must be in range defined by corner + while (start <= end && key >= array[start] && key <= array[end]) { + // Probing the position with keeping + // uniform distribution in mind. + int pos = start + (((end - start) / (array[end] - array[start])) * (key - array[start])); + + // Condition of target found + if (array[pos] == key) return pos; + + // If key is larger, key is in upper part + if (array[pos] < key) start = pos + 1; + + // If key is smaller, x is in lower part + else end = pos - 1; } + return -1; + } + + // Driver method + public static void main(String[] args) { + Random r = new Random(); + int size = 100; + int maxElement = 100000; + int[] integers = IntStream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray(); + + // the element that should be found + Integer shouldBeFound = integers[r.nextInt(size - 1)]; + + InterpolationSearch search = new InterpolationSearch(); + int atIndex = search.find(integers, shouldBeFound); + + System.out.println( + String.format( + "Should be found: %d. Found %d at index %d. An array length %d", + shouldBeFound, integers[atIndex], atIndex, size)); + + int toCheck = Arrays.binarySearch(integers, shouldBeFound); + System.out.println( + format( + "Found by system method at an index: %d. Is equal: %b", toCheck, toCheck == atIndex)); + } } - diff --git a/Searches/IterativeBinarySearch.java b/Searches/IterativeBinarySearch.java index 5a3a6d9e11cc..d41cbc246993 100644 --- a/Searches/IterativeBinarySearch.java +++ b/Searches/IterativeBinarySearch.java @@ -1,79 +1,79 @@ package Searches; +import static java.lang.String.format; + import java.util.Arrays; import java.util.Random; import java.util.stream.Stream; -import static java.lang.String.format; - /** - * Binary search is one of the most popular algorithms - * This class represents iterative version {@link BinarySearch} - * Iterative binary search is likely to have lower constant factors because it doesn't involve the overhead of manipulating the call stack. - * But in java the recursive version can be optimized by the compiler to this version. - *

- * Worst-case performance O(log n) - * Best-case performance O(1) - * Average performance O(log n) - * Worst-case space complexity O(1) + * Binary search is one of the most popular algorithms This class represents iterative version + * {@link BinarySearch} Iterative binary search is likely to have lower constant factors because it + * doesn't involve the overhead of manipulating the call stack. But in java the recursive version + * can be optimized by the compiler to this version. + * + *

Worst-case performance O(log n) Best-case performance O(1) Average performance O(log n) + * Worst-case space complexity O(1) * * @author Gabriele La Greca : https://github.com/thegabriele97 * @author Podshivalov Nikita (https://github.com/nikitap492) * @see SearchAlgorithm * @see BinarySearch */ - public final class IterativeBinarySearch implements SearchAlgorithm { - /** - * This method implements an iterative version of binary search algorithm - * - * @param array a sorted array - * @param key the key to search in array - * @return the index of key in the array or -1 if not found - */ - @Override - public > int find(T[] array, T key) { - int l, r, k, cmp; - - l = 0; - r = array.length - 1; - - while (l <= r) { - k = (l + r) >>> 1; - cmp = key.compareTo(array[k]); - - if (cmp == 0) { - return k; - } else if (cmp < 0) { - r = --k; - } else { - l = ++k; - } - } - - return -1; + /** + * This method implements an iterative version of binary search algorithm + * + * @param array a sorted array + * @param key the key to search in array + * @return the index of key in the array or -1 if not found + */ + @Override + public > int find(T[] array, T key) { + int l, r, k, cmp; + + l = 0; + r = array.length - 1; + + while (l <= r) { + k = (l + r) >>> 1; + cmp = key.compareTo(array[k]); + + if (cmp == 0) { + return k; + } else if (cmp < 0) { + r = --k; + } else { + l = ++k; + } } - //Only a main method for test purpose - public static void main(String[] args) { - Random r = new Random(); - int size = 100; - int maxElement = 100000; - Integer[] integers = Stream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray(Integer[]::new); - - - //the element that should be found - Integer shouldBeFound = integers[r.nextInt(size - 1)]; - - IterativeBinarySearch search = new IterativeBinarySearch(); - int atIndex = search.find(integers, shouldBeFound); - - System.out.println(String.format("Should be found: %d. Found %d at index %d. An array length %d" - , shouldBeFound, integers[atIndex], atIndex, size)); - - - int toCheck = Arrays.binarySearch(integers, shouldBeFound); - System.out.println(format("Found by system method at an index: %d. Is equal: %b", toCheck, toCheck == atIndex)); - } + return -1; + } + + // Only a main method for test purpose + public static void main(String[] args) { + Random r = new Random(); + int size = 100; + int maxElement = 100000; + Integer[] integers = + Stream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray(Integer[]::new); + + // the element that should be found + Integer shouldBeFound = integers[r.nextInt(size - 1)]; + + IterativeBinarySearch search = new IterativeBinarySearch(); + int atIndex = search.find(integers, shouldBeFound); + + System.out.println( + String.format( + "Should be found: %d. Found %d at index %d. An array length %d", + shouldBeFound, integers[atIndex], atIndex, size)); + + int toCheck = Arrays.binarySearch(integers, shouldBeFound); + System.out.println( + format( + "Found by system method at an index: %d. Is equal: %b", toCheck, toCheck == atIndex)); + } } diff --git a/Searches/IterativeTernarySearch.java b/Searches/IterativeTernarySearch.java index 798cf444f47f..7c6adc505f8e 100644 --- a/Searches/IterativeTernarySearch.java +++ b/Searches/IterativeTernarySearch.java @@ -1,83 +1,74 @@ package Searches; +import static java.lang.String.format; + import java.util.Arrays; import java.util.Random; import java.util.stream.Stream; -import static java.lang.String.format; - /** - * A iterative version of a ternary search algorithm - * This is better way to implement the ternary search, because a recursive version adds some overhead to a stack. - * But in java the compile can transform the recursive version to iterative implicitly, - * so there are no much differences between these two algorithms - *

- * Worst-case performance Θ(log3(N)) - * Best-case performance O(1) - * Average performance Θ(log3(N)) - * Worst-case space complexity O(1) + * A iterative version of a ternary search algorithm This is better way to implement the ternary + * search, because a recursive version adds some overhead to a stack. But in java the compile can + * transform the recursive version to iterative implicitly, so there are no much differences between + * these two algorithms + * + *

Worst-case performance Θ(log3(N)) Best-case performance O(1) Average performance Θ(log3(N)) + * Worst-case space complexity O(1) * * @author Podshivalov Nikita (https://github.com/nikitap492) * @see SearchAlgorithm * @see TernarySearch * @since 2018-04-13 */ - public class IterativeTernarySearch implements SearchAlgorithm { + @Override + public > int find(T[] array, T key) { + int left = 0; + int right = array.length - 1; - @Override - public > int find(T[] array, T key) { - int left = 0; - int right = array.length - 1; - - while (right > left) { - - int leftCmp = array[left].compareTo(key); - int rightCmp = array[right].compareTo(key); - if (leftCmp == 0) return left; - if (rightCmp == 0) return right; + while (right > left) { - int leftThird = left + (right - left) / 3 + 1; - int rightThird = right - (right - left) / 3 - 1; + int leftCmp = array[left].compareTo(key); + int rightCmp = array[right].compareTo(key); + if (leftCmp == 0) return left; + if (rightCmp == 0) return right; + int leftThird = left + (right - left) / 3 + 1; + int rightThird = right - (right - left) / 3 - 1; - if (array[leftThird].compareTo(key) <= 0) { - left = leftThird; - } else { - right = rightThird; - } - } - - return -1; + if (array[leftThird].compareTo(key) <= 0) { + left = leftThird; + } else { + right = rightThird; + } } - - public static void main(String[] args) { - //just generate data - Random r = new Random(); - int size = 100; - int maxElement = 100000; - Integer[] integers = Stream.generate(() -> r.nextInt(maxElement)) - .limit(size) - .sorted() - .toArray(Integer[]::new); - - - //the element that should be found - Integer shouldBeFound = integers[r.nextInt(size - 1)]; - - IterativeTernarySearch search = new IterativeTernarySearch(); - int atIndex = search.find(integers, shouldBeFound); - - System.out.println(format("Should be found: %d. Found %d at index %d. An array length %d", - shouldBeFound, integers[atIndex], atIndex, size)); - - int toCheck = Arrays.binarySearch(integers, shouldBeFound); - System.out.println(format("Found by system method at an index: %d. Is equal: %b", - toCheck, toCheck == atIndex)); - - } - - + return -1; + } + + public static void main(String[] args) { + // just generate data + Random r = new Random(); + int size = 100; + int maxElement = 100000; + Integer[] integers = + Stream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray(Integer[]::new); + + // the element that should be found + Integer shouldBeFound = integers[r.nextInt(size - 1)]; + + IterativeTernarySearch search = new IterativeTernarySearch(); + int atIndex = search.find(integers, shouldBeFound); + + System.out.println( + format( + "Should be found: %d. Found %d at index %d. An array length %d", + shouldBeFound, integers[atIndex], atIndex, size)); + + int toCheck = Arrays.binarySearch(integers, shouldBeFound); + System.out.println( + format( + "Found by system method at an index: %d. Is equal: %b", toCheck, toCheck == atIndex)); + } } diff --git a/Searches/JumpSearch.java b/Searches/JumpSearch.java index 897bda6c4f15..87eafe25cbf1 100644 --- a/Searches/JumpSearch.java +++ b/Searches/JumpSearch.java @@ -2,38 +2,39 @@ public class JumpSearch implements SearchAlgorithm { - public static void main(String[] args) { - JumpSearch jumpSearch = new JumpSearch(); - Integer[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - for (int i = 0; i < array.length; i++) { - assert jumpSearch.find(array, i) == i; - } - assert jumpSearch.find(array, -1) == -1; - assert jumpSearch.find(array, 11) == -1; + public static void main(String[] args) { + JumpSearch jumpSearch = new JumpSearch(); + Integer[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + for (int i = 0; i < array.length; i++) { + assert jumpSearch.find(array, i) == i; } + assert jumpSearch.find(array, -1) == -1; + assert jumpSearch.find(array, 11) == -1; + } - /** - * Jump Search algorithm implements - * - * @param array the array contains elements - * @param key to be searched - * @return index of {@code key} if found, otherwise -1 - */ - @Override - public > int find(T[] array, T key) { - int length = array.length; /* length of array */ - int blockSize = (int) Math.sqrt(length); /* block size to be jumped */ + /** + * Jump Search algorithm implements + * + * @param array the array contains elements + * @param key to be searched + * @return index of {@code key} if found, otherwise -1 + */ + @Override + public > int find(T[] array, T key) { + int length = array.length; /* length of array */ + int blockSize = (int) Math.sqrt(length); /* block size to be jumped */ - int limit = blockSize; - while (key.compareTo(array[limit]) > 0 && limit < array.length - 1) { - limit = Math.min(limit + blockSize, array.length - 1); - } + int limit = blockSize; + while (key.compareTo(array[limit]) > 0 && limit < array.length - 1) { + limit = Math.min(limit + blockSize, array.length - 1); + } - for (int i = limit - blockSize; i <= limit; i++) { - if (array[i] == key) { /* execute linear search */ - return i; - } - } - return -1; /* not found */ + for (int i = limit - blockSize; i <= limit; i++) { + if (array[i] == key) { + /* execute linear search */ + return i; + } } + return -1; /* not found */ + } } diff --git a/Searches/LinearSearch.java b/Searches/LinearSearch.java index 8a69b758d6dd..e8da9ab196e8 100644 --- a/Searches/LinearSearch.java +++ b/Searches/LinearSearch.java @@ -4,57 +4,54 @@ import java.util.stream.Stream; /** - * Linear search is the easiest search algorithm - * It works with sorted and unsorted arrays (an binary search works only with sorted array) - * This algorithm just compares all elements of an array to find a value - *

- * Worst-case performance O(n) - * Best-case performance O(1) - * Average performance O(n) - * Worst-case space complexity + * Linear search is the easiest search algorithm It works with sorted and unsorted arrays (an binary + * search works only with sorted array) This algorithm just compares all elements of an array to + * find a value + * + *

Worst-case performance O(n) Best-case performance O(1) Average performance O(n) Worst-case + * space complexity * * @author Varun Upadhyay (https://github.com/varunu28) * @author Podshivalov Nikita (https://github.com/nikitap492) * @see BinarySearch * @see SearchAlgorithm */ - public class LinearSearch implements SearchAlgorithm { - /** - * Generic Linear search method - * - * @param array List to be searched - * @param value Key being searched for - * @return Location of the key - */ - @Override - public > int find(T[] array, T value) { - for (int i = 0; i < array.length; i++) { - if (array[i].compareTo(value) == 0) { - return i; - } - } - return -1; - } - - - public static void main(String[] args) { - //just generate data - Random r = new Random(); - int size = 200; - int maxElement = 100; - Integer[] integers = Stream.generate(() -> r.nextInt(maxElement)).limit(size).toArray(Integer[]::new); - - - //the element that should be found - Integer shouldBeFound = integers[r.nextInt(size - 1)]; - - LinearSearch search = new LinearSearch(); - int atIndex = search.find(integers, shouldBeFound); - - System.out.println(String.format("Should be found: %d. Found %d at index %d. An array length %d" - , shouldBeFound, integers[atIndex], atIndex, size)); + /** + * Generic Linear search method + * + * @param array List to be searched + * @param value Key being searched for + * @return Location of the key + */ + @Override + public > int find(T[] array, T value) { + for (int i = 0; i < array.length; i++) { + if (array[i].compareTo(value) == 0) { + return i; + } } - + return -1; + } + + public static void main(String[] args) { + // just generate data + Random r = new Random(); + int size = 200; + int maxElement = 100; + Integer[] integers = + Stream.generate(() -> r.nextInt(maxElement)).limit(size).toArray(Integer[]::new); + + // the element that should be found + Integer shouldBeFound = integers[r.nextInt(size - 1)]; + + LinearSearch search = new LinearSearch(); + int atIndex = search.find(integers, shouldBeFound); + + System.out.println( + String.format( + "Should be found: %d. Found %d at index %d. An array length %d", + shouldBeFound, integers[atIndex], atIndex, size)); + } } diff --git a/Searches/PerfectBinarySearch.java b/Searches/PerfectBinarySearch.java index 559ecf5d9d15..9399789d091c 100644 --- a/Searches/PerfectBinarySearch.java +++ b/Searches/PerfectBinarySearch.java @@ -2,35 +2,30 @@ import java.util.*; -class PerfectBinarySearch{ +class PerfectBinarySearch { - static int binarySearch(int[] arr, int target) - { - int low = 0 ; - int high = arr.length - 1 ; + static int binarySearch(int[] arr, int target) { + int low = 0; + int high = arr.length - 1; - while(low <= high) { - int mid =(low + high) / 2; + while (low <= high) { + int mid = (low + high) / 2; - if(arr[mid] == target) { - return mid; - } - else if(arr[mid] > target) { - high = mid - 1; - } - else { - low = mid + 1; - } - - } - return -1; + if (arr[mid] == target) { + return mid; + } else if (arr[mid] > target) { + high = mid - 1; + } else { + low = mid + 1; + } } + return -1; + } - public static void main(String[] args) - { - PerfectBinarySearch BinarySearch = new PerfectBinarySearch(); - int[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - assert BinarySearch.binarySearch(array, -1) == -1; - assert BinarySearch.binarySearch(array, 11) == -1; - } + public static void main(String[] args) { + PerfectBinarySearch BinarySearch = new PerfectBinarySearch(); + int[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + assert BinarySearch.binarySearch(array, -1) == -1; + assert BinarySearch.binarySearch(array, 11) == -1; + } } diff --git a/Searches/SaddlebackSearch.java b/Searches/SaddlebackSearch.java index eee2f0bb6559..dca560566477 100644 --- a/Searches/SaddlebackSearch.java +++ b/Searches/SaddlebackSearch.java @@ -3,78 +3,67 @@ import java.util.Scanner; /** - * Program to perform Saddleback Search - * Given a sorted 2D array(elements are sorted across every row and column, assuming ascending order) - * of size n*m we can search a given element in O(n+m) - *

- * we start from bottom left corner - * if the current element is greater than the given element then we move up - * else we move right - * Sample Input: - * 5 5 ->Dimensions - * -10 -5 -3 4 9 - * -6 -2 0 5 10 - * -4 -1 1 6 12 - * 2 3 7 8 13 - * 100 120 130 140 150 - * 140 ->element to be searched - * output: 4 3 // first value is row, second one is column + * Program to perform Saddleback Search Given a sorted 2D array(elements are sorted across every row + * and column, assuming ascending order) of size n*m we can search a given element in O(n+m) + * + *

we start from bottom left corner if the current element is greater than the given element then + * we move up else we move right Sample Input: 5 5 ->Dimensions -10 -5 -3 4 9 -6 -2 0 5 10 -4 -1 1 6 + * 12 2 3 7 8 13 100 120 130 140 150 140 ->element to be searched output: 4 3 // first value is row, + * second one is column * * @author Nishita Aggarwal */ public class SaddlebackSearch { - /** - * This method performs Saddleback Search - * - * @param arr The **Sorted** array in which we will search the element. - * @param row the current row. - * @param col the current column. - * @param key the element that we want to search for. - * @return The index(row and column) of the element if found. - * Else returns -1 -1. - */ - private static int[] find(int arr[][], int row, int col, int key) { + /** + * This method performs Saddleback Search + * + * @param arr The **Sorted** array in which we will search the element. + * @param row the current row. + * @param col the current column. + * @param key the element that we want to search for. + * @return The index(row and column) of the element if found. Else returns -1 -1. + */ + private static int[] find(int arr[][], int row, int col, int key) { - //array to store the answer row and column - int ans[] = {-1, -1}; - if (row < 0 || col >= arr[row].length) { - return ans; - } - if (arr[row][col] == key) { - ans[0] = row; - ans[1] = col; - return ans; - } - //if the current element is greater than the given element then we move up - else if (arr[row][col] > key) { - return find(arr, row - 1, col, key); - } - //else we move right - return find(arr, row, col + 1, key); + // array to store the answer row and column + int ans[] = {-1, -1}; + if (row < 0 || col >= arr[row].length) { + return ans; } - - /** - * Main method - * - * @param args Command line arguments - */ - public static void main(String[] args) { - // TODO Auto-generated method stub - Scanner sc = new Scanner(System.in); - int arr[][]; - int i, j, rows = sc.nextInt(), col = sc.nextInt(); - arr = new int[rows][col]; - for (i = 0; i < rows; i++) { - for (j = 0; j < col; j++) { - arr[i][j] = sc.nextInt(); - } - } - int ele = sc.nextInt(); - //we start from bottom left corner - int ans[] = find(arr, rows - 1, 0, ele); - System.out.println(ans[0] + " " + ans[1]); - sc.close(); + if (arr[row][col] == key) { + ans[0] = row; + ans[1] = col; + return ans; } + // if the current element is greater than the given element then we move up + else if (arr[row][col] > key) { + return find(arr, row - 1, col, key); + } + // else we move right + return find(arr, row, col + 1, key); + } + /** + * Main method + * + * @param args Command line arguments + */ + public static void main(String[] args) { + // TODO Auto-generated method stub + Scanner sc = new Scanner(System.in); + int arr[][]; + int i, j, rows = sc.nextInt(), col = sc.nextInt(); + arr = new int[rows][col]; + for (i = 0; i < rows; i++) { + for (j = 0; j < col; j++) { + arr[i][j] = sc.nextInt(); + } + } + int ele = sc.nextInt(); + // we start from bottom left corner + int ans[] = find(arr, rows - 1, 0, ele); + System.out.println(ans[0] + " " + ans[1]); + sc.close(); + } } diff --git a/Searches/SearchAlgorithm.java b/Searches/SearchAlgorithm.java index 00dce17f0226..1d5262d3a2dd 100644 --- a/Searches/SearchAlgorithm.java +++ b/Searches/SearchAlgorithm.java @@ -4,15 +4,14 @@ * The common interface of most searching algorithms * * @author Podshivalov Nikita (https://github.com/nikitap492) - **/ + */ public interface SearchAlgorithm { - /** - * @param key is an element which should be found - * @param array is an array where the element should be found - * @param Comparable type - * @return first found index of the element - */ - > int find(T array[], T key); - + /** + * @param key is an element which should be found + * @param array is an array where the element should be found + * @param Comparable type + * @return first found index of the element + */ + > int find(T array[], T key); } diff --git a/Searches/TernarySearch.java b/Searches/TernarySearch.java index ced67b0f56e7..20b0c436a98d 100644 --- a/Searches/TernarySearch.java +++ b/Searches/TernarySearch.java @@ -1,99 +1,97 @@ package Searches; +import static java.lang.String.format; import java.util.Arrays; import java.util.Random; import java.util.stream.Stream; -import static java.lang.String.format; - /** - * A ternary search algorithm is a technique in computer science for finding the minimum or maximum of a unimodal function - * The algorithm determines either that the minimum or maximum cannot be in the first third of the domain - * or that it cannot be in the last third of the domain, then repeats on the remaining third. - *

- * Worst-case performance Θ(log3(N)) - * Best-case performance O(1) - * Average performance Θ(log3(N)) - * Worst-case space complexity O(1) + * A ternary search algorithm is a technique in computer science for finding the minimum or maximum + * of a unimodal function The algorithm determines either that the minimum or maximum cannot be in + * the first third of the domain or that it cannot be in the last third of the domain, then repeats + * on the remaining third. + * + *

Worst-case performance Θ(log3(N)) Best-case performance O(1) Average performance Θ(log3(N)) + * Worst-case space complexity O(1) * * @author Podshivalov Nikita (https://github.com/nikitap492) * @see SearchAlgorithm * @see IterativeBinarySearch */ - public class TernarySearch implements SearchAlgorithm { - /** - * @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. - */ - @Override - public > int find(T[] arr, T value) { - return ternarySearch(arr, value, 0, arr.length - 1); + /** + * @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. + */ + @Override + public > int find(T[] arr, T 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. + */ + private > int ternarySearch(T[] arr, T key, int start, int end) { + if (start > end) { + return -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. - */ - private > int ternarySearch(T[] arr, T 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 (key.compareTo(arr[mid1]) == 0) { - return mid1; - } else if (key.compareTo(arr[mid2]) == 0) { - return mid2; - } - - /* Search the first (1/3) rd part of the array.*/ - - else if (key.compareTo(arr[mid1]) < 0) { - return ternarySearch(arr, key, start, --mid1); - } - /* Search 3rd (1/3)rd part of the array */ - - else if (key.compareTo(arr[mid2]) > 0) { - return ternarySearch(arr, key, ++mid2, end); - } - /* Search middle (1/3)rd part of the array */ - - else { - return ternarySearch(arr, key, mid1, mid2); - } + /* 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 (key.compareTo(arr[mid1]) == 0) { + return mid1; + } else if (key.compareTo(arr[mid2]) == 0) { + return mid2; } - public static void main(String[] args) { - //just generate data - Random r = new Random(); - int size = 100; - int maxElement = 100000; - Integer[] integers = Stream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray(Integer[]::new); - + /* Search the first (1/3) rd part of the array.*/ - //the element that should be found - Integer shouldBeFound = integers[r.nextInt(size - 1)]; - - TernarySearch search = new TernarySearch(); - int atIndex = search.find(integers, shouldBeFound); - - System.out.println(format("Should be found: %d. Found %d at index %d. An array length %d" - , shouldBeFound, integers[atIndex], atIndex, size)); + else if (key.compareTo(arr[mid1]) < 0) { + return ternarySearch(arr, key, start, --mid1); + } + /* Search 3rd (1/3)rd part of the array */ - int toCheck = Arrays.binarySearch(integers, shouldBeFound); - System.out.println(format("Found by system method at an index: %d. Is equal: %b", toCheck, toCheck == atIndex)); + else if (key.compareTo(arr[mid2]) > 0) { + return ternarySearch(arr, key, ++mid2, end); + } + /* Search middle (1/3)rd part of the array */ + else { + return ternarySearch(arr, key, mid1, mid2); } -} \ No newline at end of file + } + + public static void main(String[] args) { + // just generate data + Random r = new Random(); + int size = 100; + int maxElement = 100000; + Integer[] integers = + Stream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray(Integer[]::new); + + // the element that should be found + Integer shouldBeFound = integers[r.nextInt(size - 1)]; + + TernarySearch search = new TernarySearch(); + int atIndex = search.find(integers, shouldBeFound); + + System.out.println( + format( + "Should be found: %d. Found %d at index %d. An array length %d", + shouldBeFound, integers[atIndex], atIndex, size)); + + int toCheck = Arrays.binarySearch(integers, shouldBeFound); + System.out.println( + format( + "Found by system method at an index: %d. Is equal: %b", toCheck, toCheck == atIndex)); + } +} diff --git a/Sorts/BitonicSort.java b/Sorts/BitonicSort.java index 195ae1712d48..4888cc070c6f 100644 --- a/Sorts/BitonicSort.java +++ b/Sorts/BitonicSort.java @@ -2,87 +2,73 @@ /* Java program for Bitonic Sort. Note that this program works only when size of input is a power of 2. */ -public class BitonicSort -{ - /* The parameter dir indicates the sorting direction, - ASCENDING or DESCENDING; if (a[i] > a[j]) agrees - with the direction, then a[i] and a[j] are - interchanged. */ - void compAndSwap(int a[], int i, int j, int dir) - { - if ( (a[i] > a[j] && dir == 1) || - (a[i] < a[j] && dir == 0)) - { - // Swapping elements - int temp = a[i]; - a[i] = a[j]; - a[j] = temp; - } +public class BitonicSort { + /* The parameter dir indicates the sorting direction, + ASCENDING or DESCENDING; if (a[i] > a[j]) agrees + with the direction, then a[i] and a[j] are + interchanged. */ + void compAndSwap(int a[], int i, int j, int dir) { + if ((a[i] > a[j] && dir == 1) || (a[i] < a[j] && dir == 0)) { + // Swapping elements + int temp = a[i]; + a[i] = a[j]; + a[j] = temp; } + } - /* It recursively sorts a bitonic sequence in ascending - order, if dir = 1, and in descending order otherwise - (means dir=0). The sequence to be sorted starts at - index position low, the parameter cnt is the number - of elements to be sorted.*/ - void bitonicMerge(int a[], int low, int cnt, int dir) - { - if (cnt>1) - { - int k = cnt/2; - for (int i=low; i 1) { + int k = cnt / 2; + for (int i = low; i < low + k; i++) compAndSwap(a, i, i + k, dir); + bitonicMerge(a, low, k, dir); + bitonicMerge(a, low + k, k, dir); } + } - /* This funcion first produces a bitonic sequence by - recursively sorting its two halves in opposite sorting - orders, and then calls bitonicMerge to make them in - the same order */ - void bitonicSort(int a[], int low, int cnt, int dir) - { - if (cnt>1) - { - int k = cnt/2; + /* This funcion first produces a bitonic sequence by + recursively sorting its two halves in opposite sorting + orders, and then calls bitonicMerge to make them in + the same order */ + void bitonicSort(int a[], int low, int cnt, int dir) { + if (cnt > 1) { + int k = cnt / 2; - // sort in ascending order since dir here is 1 - bitonicSort(a, low, k, 1); + // sort in ascending order since dir here is 1 + bitonicSort(a, low, k, 1); - // sort in descending order since dir here is 0 - bitonicSort(a,low+k, k, 0); + // sort in descending order since dir here is 0 + bitonicSort(a, low + k, k, 0); - // Will merge wole sequence in ascending order - // since dir=1. - bitonicMerge(a, low, cnt, dir); - } + // Will merge wole sequence in ascending order + // since dir=1. + bitonicMerge(a, low, cnt, dir); } + } - /*Caller of bitonicSort for sorting the entire array - of length N in ASCENDING order */ - void sort(int a[], int N, int up) - { - bitonicSort(a, 0, N, up); - } + /*Caller of bitonicSort for sorting the entire array + of length N in ASCENDING order */ + void sort(int a[], int N, int up) { + bitonicSort(a, 0, N, up); + } - /* A utility function to print array of size n */ - static void printArray(int arr[]) - { - int n = arr.length; - for (int i=0; i> boolean isSorted(T[] array) { - for (int i = 0; i < array.length - 1; i++) { - if (SortUtils.less(array[i + 1], array[i])) return false; - } - return true; + private static > boolean isSorted(T[] array) { + for (int i = 0; i < array.length - 1; i++) { + if (SortUtils.less(array[i + 1], array[i])) return false; } + return true; + } - // Randomly shuffles the array - private static void nextPermutation(T[] array) { - int length = array.length; + // Randomly shuffles the array + private static void nextPermutation(T[] array) { + int length = array.length; - for (int i = 0; i < array.length; i++) { - int randomIndex = i + random.nextInt(length - i); - SortUtils.swap(array, randomIndex, i); - } + for (int i = 0; i < array.length; i++) { + int randomIndex = i + random.nextInt(length - i); + SortUtils.swap(array, randomIndex, i); } + } - public > T[] sort(T[] array) { - while (!isSorted(array)) { - nextPermutation(array); - } - return array; + public > T[] sort(T[] array) { + while (!isSorted(array)) { + nextPermutation(array); } + return array; + } - // Driver Program - public static void main(String[] args) { - // Integer Input - Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12}; + // Driver Program + public static void main(String[] args) { + // Integer Input + Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12}; - BogoSort bogoSort = new BogoSort(); + BogoSort bogoSort = new BogoSort(); - // print a sorted array - SortUtils.print(bogoSort.sort(integers)); + // print a sorted array + SortUtils.print(bogoSort.sort(integers)); - // String Input - String[] strings = {"c", "a", "e", "b", "d"}; + // String Input + String[] strings = {"c", "a", "e", "b", "d"}; - SortUtils.print(bogoSort.sort(strings)); - } + SortUtils.print(bogoSort.sort(strings)); + } } diff --git a/Sorts/BubbleSort.java b/Sorts/BubbleSort.java index 7df1fae8a392..80385d24280f 100644 --- a/Sorts/BubbleSort.java +++ b/Sorts/BubbleSort.java @@ -7,47 +7,43 @@ * @author Podshivalov Nikita (https://github.com/nikitap492) * @see SortAlgorithm */ - class BubbleSort implements SortAlgorithm { - /** - * This method implements the Generic Bubble Sort - * - * @param array The array to be sorted - * Sorts the array in ascending order - **/ - - @Override - public > T[] sort(T[] array) { - for (int i = 0, size = array.length; i < size - 1; ++i) { - boolean swapped = false; - for (int j = 0; j < size - 1 - i; ++j) { - if (greater(array[j], array[j + 1])) { - swap(array, j, j + 1); - swapped = true; - } - } - if (!swapped) { - break; - } + /** + * This method implements the Generic Bubble Sort + * + * @param array The array to be sorted Sorts the array in ascending order + */ + @Override + public > T[] sort(T[] array) { + for (int i = 0, size = array.length; i < size - 1; ++i) { + boolean swapped = false; + for (int j = 0; j < size - 1 - i; ++j) { + if (greater(array[j], array[j + 1])) { + swap(array, j, j + 1); + swapped = true; } - return array; + } + if (!swapped) { + break; + } } + return array; + } - // Driver Program - public static void main(String[] args) { + // Driver Program + public static void main(String[] args) { - // Integer Input - Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12}; - BubbleSort bubbleSort = new BubbleSort(); - bubbleSort.sort(integers); + // Integer Input + Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12}; + BubbleSort bubbleSort = new BubbleSort(); + bubbleSort.sort(integers); - // Output => 1, 4, 6, 9, 12, 23, 54, 78, 231 - print(integers); + // Output => 1, 4, 6, 9, 12, 23, 54, 78, 231 + print(integers); - // String Input - String[] strings = {"c", "a", "e", "b", "d"}; - //Output => a, b, c, d, e - print(bubbleSort.sort(strings)); - - } + // String Input + String[] strings = {"c", "a", "e", "b", "d"}; + // Output => a, b, c, d, e + print(bubbleSort.sort(strings)); + } } diff --git a/Sorts/BubbleSortRecursion.java b/Sorts/BubbleSortRecursion.java index 6af7778f199a..ce51b1bfe29c 100644 --- a/Sorts/BubbleSortRecursion.java +++ b/Sorts/BubbleSortRecursion.java @@ -2,54 +2,52 @@ import java.util.Random; -/** - * BubbleSort algorithm implements using recursion - */ +/** BubbleSort algorithm implements using recursion */ public class BubbleSortRecursion implements SortAlgorithm { - public static void main(String[] args) { - Integer[] array = new Integer[10]; + public static void main(String[] args) { + Integer[] array = new Integer[10]; - Random random = new Random(); - /* generate 10 random numbers from -50 to 49 */ - for (int i = 0; i < array.length; ++i) { - array[i] = random.nextInt(100) - 50; - } + Random random = new Random(); + /* generate 10 random numbers from -50 to 49 */ + for (int i = 0; i < array.length; ++i) { + array[i] = random.nextInt(100) - 50; + } - BubbleSortRecursion bubbleSortRecursion = new BubbleSortRecursion(); - bubbleSortRecursion.sort(array); + BubbleSortRecursion bubbleSortRecursion = new BubbleSortRecursion(); + bubbleSortRecursion.sort(array); - /* check array is sorted or not */ - for (int i = 0; i < array.length - 1; ++i) { - assert (array[i].compareTo(array[i + 1]) <= 0); - } + /* check array is sorted or not */ + for (int i = 0; i < array.length - 1; ++i) { + assert (array[i].compareTo(array[i + 1]) <= 0); } + } - /** - * @param unsorted - an array should be sorted - * @return sorted array - */ - @Override - public > T[] sort(T[] unsorted) { - bubbleSort(unsorted, unsorted.length); - return unsorted; - } + /** + * @param unsorted - an array should be sorted + * @return sorted array + */ + @Override + public > T[] sort(T[] unsorted) { + bubbleSort(unsorted, unsorted.length); + return unsorted; + } - /** - * BubbleSort algorithm implements using recursion - * - * @param unsorted array contains elements - * @param len length of given array - */ - private static > void bubbleSort(T[] unsorted, int len) { - boolean swapped = false; /* flag to check if array is sorted or not */ - for (int i = 0; i < len - 1; ++i) { - if (SortUtils.greater(unsorted[i], unsorted[i + 1])) { - SortUtils.swap(unsorted, i, i + 1); - swapped = true; - } - } - if (swapped) { - bubbleSort(unsorted, len - 1); - } + /** + * BubbleSort algorithm implements using recursion + * + * @param unsorted array contains elements + * @param len length of given array + */ + private static > void bubbleSort(T[] unsorted, int len) { + boolean swapped = false; /* flag to check if array is sorted or not */ + for (int i = 0; i < len - 1; ++i) { + if (SortUtils.greater(unsorted[i], unsorted[i + 1])) { + SortUtils.swap(unsorted, i, i + 1); + swapped = true; + } + } + if (swapped) { + bubbleSort(unsorted, len - 1); } + } } diff --git a/Sorts/BucketSort.java b/Sorts/BucketSort.java index 0ff4a92ec4aa..66795f7f3c89 100644 --- a/Sorts/BucketSort.java +++ b/Sorts/BucketSort.java @@ -5,111 +5,108 @@ import java.util.List; import java.util.Random; -/** - * Wikipedia: https://en.wikipedia.org/wiki/Bucket_sort - */ +/** Wikipedia: https://en.wikipedia.org/wiki/Bucket_sort */ public class BucketSort { - public static void main(String[] args) { - int[] arr = new int[10]; + public static void main(String[] args) { + int[] arr = new int[10]; - /* generate 10 random numbers from -50 to 49 */ - Random random = new Random(); - for (int i = 0; i < arr.length; ++i) { - arr[i] = random.nextInt(100) - 50; - } + /* generate 10 random numbers from -50 to 49 */ + Random random = new Random(); + for (int i = 0; i < arr.length; ++i) { + arr[i] = random.nextInt(100) - 50; + } - bucketSort(arr); + bucketSort(arr); - /* check array is sorted or not */ - for (int i = 0, limit = arr.length - 1; i < limit; ++i) { - assert arr[i] <= arr[i + 1]; - } + /* check array is sorted or not */ + for (int i = 0, limit = arr.length - 1; i < limit; ++i) { + assert arr[i] <= arr[i + 1]; } + } - /** - * BucketSort algorithms implements - * - * @param arr the array contains elements - */ - private static void bucketSort(int[] arr) { - /* get max value of arr */ - int max = max(arr); - - /* get min value of arr */ - int min = min(arr); - - /* number of buckets */ - int numberOfBuckets = max - min + 1; - - List> buckets = new ArrayList<>(numberOfBuckets); - - /* init buckets */ - for (int i = 0; i < numberOfBuckets; ++i) { - buckets.add(new ArrayList<>()); - } - - /* store elements to buckets */ - for (int value : arr) { - int hash = hash(value, min, numberOfBuckets); - buckets.get(hash).add(value); - } - - /* sort individual bucket */ - for (List bucket : buckets) { - Collections.sort(bucket); - } - - /* concatenate buckets to origin array */ - int index = 0; - for (List bucket : buckets) { - for (int value : bucket) { - arr[index++] = value; - } - } - } + /** + * BucketSort algorithms implements + * + * @param arr the array contains elements + */ + private static void bucketSort(int[] arr) { + /* get max value of arr */ + int max = max(arr); + + /* get min value of arr */ + int min = min(arr); + + /* number of buckets */ + int numberOfBuckets = max - min + 1; + List> buckets = new ArrayList<>(numberOfBuckets); - /** - * Get index of bucket which of our elements gets placed into it. - * - * @param elem the element of array to be sorted - * @param min min value of array - * @param numberOfBucket the number of bucket - * @return index of bucket - */ - private static int hash(int elem, int min, int numberOfBucket) { - return (elem - min) / numberOfBucket; + /* init buckets */ + for (int i = 0; i < numberOfBuckets; ++i) { + buckets.add(new ArrayList<>()); } - /** - * Calculate max value of array - * - * @param arr the array contains elements - * @return max value of given array - */ - public static int max(int[] arr) { - int max = arr[0]; - for (int value : arr) { - if (value > max) { - max = value; - } - } - return max; + /* store elements to buckets */ + for (int value : arr) { + int hash = hash(value, min, numberOfBuckets); + buckets.get(hash).add(value); } - /** - * Calculate min value of array - * - * @param arr the array contains elements - * @return min value of given array - */ - public static int min(int[] arr) { - int min = arr[0]; - for (int value : arr) { - if (value < min) { - min = value; - } - } - return min; + /* sort individual bucket */ + for (List bucket : buckets) { + Collections.sort(bucket); + } + + /* concatenate buckets to origin array */ + int index = 0; + for (List bucket : buckets) { + for (int value : bucket) { + arr[index++] = value; + } + } + } + + /** + * Get index of bucket which of our elements gets placed into it. + * + * @param elem the element of array to be sorted + * @param min min value of array + * @param numberOfBucket the number of bucket + * @return index of bucket + */ + private static int hash(int elem, int min, int numberOfBucket) { + return (elem - min) / numberOfBucket; + } + + /** + * Calculate max value of array + * + * @param arr the array contains elements + * @return max value of given array + */ + public static int max(int[] arr) { + int max = arr[0]; + for (int value : arr) { + if (value > max) { + max = value; + } + } + return max; + } + + /** + * Calculate min value of array + * + * @param arr the array contains elements + * @return min value of given array + */ + public static int min(int[] arr) { + int min = arr[0]; + for (int value : arr) { + if (value < min) { + min = value; + } } + return min; + } } diff --git a/Sorts/CocktailShakerSort.java b/Sorts/CocktailShakerSort.java index c3b5df999d23..12f1e4f38e6b 100644 --- a/Sorts/CocktailShakerSort.java +++ b/Sorts/CocktailShakerSort.java @@ -4,60 +4,54 @@ * @author Mateus Bizzo (https://github.com/MattBizzo) * @author Podshivalov Nikita (https://github.com/nikitap492) */ - class CocktailShakerSort implements SortAlgorithm { - /** - * This method implements the Generic Cocktail Shaker Sort - * - * @param array The array to be sorted - * Sorts the array in increasing order - **/ - - @Override - public > T[] sort(T[] array) { - - int length = array.length; - int left = 0; - int right = length - 1; - int swappedLeft, swappedRight; - while (left < right) { - // front - swappedRight = 0; - for (int i = left; i < right; i++) { - if (SortUtils.less(array[i + 1], array[i])) { - SortUtils.swap(array, i, i + 1); - swappedRight = i; - } - } - // back - right = swappedRight; - swappedLeft = length - 1; - for (int j = right; j > left; j--) { - if (SortUtils.less(array[j], array[j - 1])) { - SortUtils.swap(array, j - 1, j); - swappedLeft = j; - } - } - left = swappedLeft; + /** + * This method implements the Generic Cocktail Shaker Sort + * + * @param array The array to be sorted Sorts the array in increasing order + */ + @Override + public > T[] sort(T[] array) { + + int length = array.length; + int left = 0; + int right = length - 1; + int swappedLeft, swappedRight; + while (left < right) { + // front + swappedRight = 0; + for (int i = left; i < right; i++) { + if (SortUtils.less(array[i + 1], array[i])) { + SortUtils.swap(array, i, i + 1); + swappedRight = i; } - return array; - - } - - // Driver Program - public static void main(String[] args) { - // Integer Input - Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12}; - CocktailShakerSort shakerSort = new CocktailShakerSort(); - - // Output => 1 4 6 9 12 23 54 78 231 - SortUtils.print(shakerSort.sort(integers)); - - // String Input - String[] strings = {"c", "a", "e", "b", "d"}; - SortUtils.print(shakerSort.sort(strings)); + } + // back + right = swappedRight; + swappedLeft = length - 1; + for (int j = right; j > left; j--) { + if (SortUtils.less(array[j], array[j - 1])) { + SortUtils.swap(array, j - 1, j); + swappedLeft = j; + } + } + left = swappedLeft; } - - + return array; + } + + // Driver Program + public static void main(String[] args) { + // Integer Input + Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12}; + CocktailShakerSort shakerSort = new CocktailShakerSort(); + + // Output => 1 4 6 9 12 23 54 78 231 + SortUtils.print(shakerSort.sort(integers)); + + // String Input + String[] strings = {"c", "a", "e", "b", "d"}; + SortUtils.print(shakerSort.sort(strings)); + } } diff --git a/Sorts/CombSort.java b/Sorts/CombSort.java index 652fc9f945a6..44afb3c288aa 100644 --- a/Sorts/CombSort.java +++ b/Sorts/CombSort.java @@ -2,15 +2,13 @@ import static Sorts.SortUtils.*; - /** * Comb Sort algorithm implementation - *

- * Best-case performance O(n * log(n)) - * Worst-case performance O(n ^ 2) - * Worst-case space complexity O(1) - *

- * Comb sort improves on bubble sort. + * + *

Best-case performance O(n * log(n)) Worst-case performance O(n ^ 2) Worst-case space + * complexity O(1) + * + *

Comb sort improves on bubble sort. * * @author Sandeep Roy (https://github.com/sandeeproy99) * @author Podshivalov Nikita (https://github.com/nikitap492) @@ -19,55 +17,55 @@ */ class CombSort implements SortAlgorithm { - // To find gap between elements - private int nextGap(int gap) { - // Shrink gap by Shrink factor - gap = (gap * 10) / 13; - return (gap < 1) ? 1 : gap; - } + // To find gap between elements + private int nextGap(int gap) { + // Shrink gap by Shrink factor + gap = (gap * 10) / 13; + return (gap < 1) ? 1 : gap; + } - /** - * Function to sort arr[] using Comb - * - * @param arr - an array should be sorted - * @return sorted array - */ - @Override - public > T[] sort(T[] arr) { - int size = arr.length; + /** + * Function to sort arr[] using Comb + * + * @param arr - an array should be sorted + * @return sorted array + */ + @Override + public > T[] sort(T[] arr) { + int size = arr.length; - // initialize gap - int gap = size; + // initialize gap + int gap = size; - // Initialize swapped as true to make sure that loop runs - boolean swapped = true; + // Initialize swapped as true to make sure that loop runs + boolean swapped = true; - // Keep running while gap is more than 1 and last iteration caused a swap - while (gap != 1 || swapped) { - // Find next gap - gap = nextGap(gap); + // Keep running while gap is more than 1 and last iteration caused a swap + while (gap != 1 || swapped) { + // Find next gap + gap = nextGap(gap); - // Initialize swapped as false so that we can check if swap happened or not - swapped = false; + // Initialize swapped as false so that we can check if swap happened or not + swapped = false; - // Compare all elements with current gap - for (int i = 0; i < size - gap; i++) { - if (less(arr[i + gap], arr[i])) { - // Swap arr[i] and arr[i+gap] - swapped = swap(arr, i, i + gap); - } - } + // Compare all elements with current gap + for (int i = 0; i < size - gap; i++) { + if (less(arr[i + gap], arr[i])) { + // Swap arr[i] and arr[i+gap] + swapped = swap(arr, i, i + gap); } - return arr; + } } + return arr; + } - // Driver method - public static void main(String[] args) { - CombSort ob = new CombSort(); - Integer[] arr = {8, 4, 1, 56, 3, -44, -1, 0, 36, 34, 8, 12, -66, -78, 23, -6, 28, 0}; - ob.sort(arr); + // Driver method + public static void main(String[] args) { + CombSort ob = new CombSort(); + Integer[] arr = {8, 4, 1, 56, 3, -44, -1, 0, 36, 34, 8, 12, -66, -78, 23, -6, 28, 0}; + ob.sort(arr); - System.out.println("sorted array"); - print(arr); - } + System.out.println("sorted array"); + print(arr); + } } diff --git a/Sorts/CountingSort.java b/Sorts/CountingSort.java index 7f10da6cca76..37a6c4e3a7a5 100644 --- a/Sorts/CountingSort.java +++ b/Sorts/CountingSort.java @@ -1,97 +1,96 @@ package Sorts; +import static Sorts.SortUtils.print; +import static java.util.stream.Collectors.toList; +import static java.util.stream.Collectors.toMap; + import java.util.*; import java.util.stream.IntStream; import java.util.stream.Stream; -import static java.util.stream.Collectors.toList; -import static java.util.stream.Collectors.toMap; -import static Sorts.SortUtils.print; - /** * @author Youssef Ali (https://github.com/youssefAli11997) * @author Podshivalov Nikita (https://github.com/nikitap492) */ class CountingSort implements SortAlgorithm { - @Override - public > T[] sort(T[] unsorted) { - return sort(Arrays.asList(unsorted)).toArray(unsorted); - } - - /** - * This method implements the Generic Counting Sort - * - * @param list The list to be sorted - *

- * Sorts the list in increasing order - * The method uses list elements as keys in the frequency map - **/ - @Override - public > List sort(List list) { - - Map frequency = new TreeMap<>(); - // The final output array - List sortedArray = new ArrayList<>(list.size()); - - // Counting the frequency of @param array elements - list.forEach(v -> frequency.put(v, frequency.getOrDefault(v, 0) + 1)); - - // Filling the sortedArray - for (Map.Entry element : frequency.entrySet()) { - for (int j = 0; j < element.getValue(); j++) { - sortedArray.add(element.getKey()); - } - } - - return sortedArray; - } - - - /** - * Stream Counting Sort - * The same as method {@link CountingSort#sort(List)} } but this method uses stream API - * - * @param list The list to be sorted - **/ - private static > List streamSort(List list) { - return list.stream() - .collect(toMap(k -> k, v -> 1, (v1, v2) -> v1 + v2, TreeMap::new)) - .entrySet() - .stream() - .flatMap(entry -> IntStream.rangeClosed(1, entry.getValue()).mapToObj(t -> entry.getKey())) - .collect(toList()); + @Override + public > T[] sort(T[] unsorted) { + return sort(Arrays.asList(unsorted)).toArray(unsorted); + } + + /** + * This method implements the Generic Counting Sort + * + * @param list The list to be sorted + *

Sorts the list in increasing order The method uses list elements as keys in the + * frequency map + */ + @Override + public > List sort(List list) { + + Map frequency = new TreeMap<>(); + // The final output array + List sortedArray = new ArrayList<>(list.size()); + + // Counting the frequency of @param array elements + list.forEach(v -> frequency.put(v, frequency.getOrDefault(v, 0) + 1)); + + // Filling the sortedArray + for (Map.Entry element : frequency.entrySet()) { + for (int j = 0; j < element.getValue(); j++) { + sortedArray.add(element.getKey()); + } } - // Driver Program - public static void main(String[] args) { - // Integer Input - List unsortedInts = Stream.of(4, 23, 6, 78, 1, 54, 23, 1, 9, 231, 9, 12).collect(toList()); - CountingSort countingSort = new CountingSort(); - - System.out.println("Before Sorting:"); - print(unsortedInts); - - // Output => 1 1 4 6 9 9 12 23 23 54 78 231 - System.out.println("After Sorting:"); - print(countingSort.sort(unsortedInts)); - System.out.println("After Sorting By Streams:"); - print(streamSort(unsortedInts)); - - System.out.println("\n------------------------------\n"); - - // String Input - List unsortedStrings = Stream.of("c", "a", "e", "b", "d", "a", "f", "g", "c").collect(toList()); - - System.out.println("Before Sorting:"); - print(unsortedStrings); - - //Output => a a b c c d e f g - System.out.println("After Sorting:"); - print(countingSort.sort(unsortedStrings)); - - System.out.println("After Sorting By Streams:"); - print(streamSort(unsortedStrings)); - - } + return sortedArray; + } + + /** + * Stream Counting Sort The same as method {@link CountingSort#sort(List)} } but this method uses + * stream API + * + * @param list The list to be sorted + */ + private static > List streamSort(List list) { + return list.stream() + .collect(toMap(k -> k, v -> 1, (v1, v2) -> v1 + v2, TreeMap::new)) + .entrySet() + .stream() + .flatMap(entry -> IntStream.rangeClosed(1, entry.getValue()).mapToObj(t -> entry.getKey())) + .collect(toList()); + } + + // Driver Program + public static void main(String[] args) { + // Integer Input + List unsortedInts = + Stream.of(4, 23, 6, 78, 1, 54, 23, 1, 9, 231, 9, 12).collect(toList()); + CountingSort countingSort = new CountingSort(); + + System.out.println("Before Sorting:"); + print(unsortedInts); + + // Output => 1 1 4 6 9 9 12 23 23 54 78 231 + System.out.println("After Sorting:"); + print(countingSort.sort(unsortedInts)); + System.out.println("After Sorting By Streams:"); + print(streamSort(unsortedInts)); + + System.out.println("\n------------------------------\n"); + + // String Input + List unsortedStrings = + Stream.of("c", "a", "e", "b", "d", "a", "f", "g", "c").collect(toList()); + + System.out.println("Before Sorting:"); + print(unsortedStrings); + + // Output => a a b c c d e f g + System.out.println("After Sorting:"); + print(countingSort.sort(unsortedStrings)); + + System.out.println("After Sorting By Streams:"); + print(streamSort(unsortedStrings)); + } } diff --git a/Sorts/CycleSort.java b/Sorts/CycleSort.java index 837c3c320454..20543665ea14 100644 --- a/Sorts/CycleSort.java +++ b/Sorts/CycleSort.java @@ -3,77 +3,69 @@ import static Sorts.SortUtils.less; import static Sorts.SortUtils.print; -/** - * @author Podshivalov Nikita (https://github.com/nikitap492) - */ +/** @author Podshivalov Nikita (https://github.com/nikitap492) */ class CycleSort implements SortAlgorithm { - @Override - public > T[] sort(T[] arr) { - int n = arr.length; + @Override + public > T[] sort(T[] arr) { + int n = arr.length; - // traverse array elements - for (int j = 0; j <= n - 2; j++) { - // initialize item as starting point - T item = arr[j]; + // traverse array elements + for (int j = 0; j <= n - 2; j++) { + // initialize item as starting point + T item = arr[j]; - // Find position where we put the item. - int pos = j; - for (int i = j + 1; i < n; i++) - if (less(arr[i], item)) pos++; + // Find position where we put the item. + int pos = j; + for (int i = j + 1; i < n; i++) if (less(arr[i], item)) pos++; - // If item is already in correct position - if (pos == j) continue; + // If item is already in correct position + if (pos == j) continue; - // ignore all duplicate elements - while (item.compareTo(arr[pos]) == 0) - pos += 1; + // ignore all duplicate elements + while (item.compareTo(arr[pos]) == 0) pos += 1; - // put the item to it's right position - if (pos != j) { - item = replace(arr, pos, item); - } + // put the item to it's right position + if (pos != j) { + item = replace(arr, pos, item); + } - // Rotate rest of the cycle - while (pos != j) { - pos = j; + // Rotate rest of the cycle + while (pos != j) { + pos = j; - // Find position where we put the element - for (int i = j + 1; i < n; i++) - if (less(arr[i], item)) { - pos += 1; - } + // Find position where we put the element + for (int i = j + 1; i < n; i++) + if (less(arr[i], item)) { + pos += 1; + } + // ignore all duplicate elements + while (item.compareTo(arr[pos]) == 0) pos += 1; - // ignore all duplicate elements - while (item.compareTo(arr[pos]) == 0) - pos += 1; - - // put the item to it's right position - if (item != arr[pos]) { - item = replace(arr, pos, item); - } - } + // put the item to it's right position + if (item != arr[pos]) { + item = replace(arr, pos, item); } - - return arr; + } } - private > T replace(T[] arr, int pos, T item) { - T temp = item; - item = arr[pos]; - arr[pos] = temp; - return item; - } + return arr; + } + private > T replace(T[] arr, int pos, T item) { + T temp = item; + item = arr[pos]; + arr[pos] = temp; + return item; + } - public static void main(String[] args) { - Integer arr[] = {4, 23, 6, 78, 1, 26, 11, 23, 0, -6, 3, 54, 231, 9, 12}; - CycleSort cycleSort = new CycleSort(); - cycleSort.sort(arr); - - System.out.println("After sort : "); - print(arr); - } + public static void main(String[] args) { + Integer arr[] = {4, 23, 6, 78, 1, 26, 11, 23, 0, -6, 3, 54, 231, 9, 12}; + CycleSort cycleSort = new CycleSort(); + cycleSort.sort(arr); + System.out.println("After sort : "); + print(arr); + } } diff --git a/Sorts/GnomeSort.java b/Sorts/GnomeSort.java index 8d5f62d438d2..3bf7213b38eb 100644 --- a/Sorts/GnomeSort.java +++ b/Sorts/GnomeSort.java @@ -7,39 +7,36 @@ * * @author Podshivalov Nikita (https://github.com/nikitap492) * @since 2018-04-10 - **/ + */ public class GnomeSort implements SortAlgorithm { - @Override - public > T[] sort(T[] arr) { - int i = 1; - int j = 2; - while (i < arr.length) { - if (less(arr[i - 1], arr[i])) i = j++; - else { - swap(arr, i - 1, i); - if (--i == 0) { - i = j++; - } - } + @Override + public > T[] sort(T[] arr) { + int i = 1; + int j = 2; + while (i < arr.length) { + if (less(arr[i - 1], arr[i])) i = j++; + else { + swap(arr, i - 1, i); + if (--i == 0) { + i = j++; } - - return null; + } } - public static void main(String[] args) { - Integer[] integers = {4, 23, 6, 78, 1, 26, 11, 23, 0, -6, 3, 54, 231, 9, 12}; - String[] strings = {"c", "a", "e", "b", "d", "dd", "da", "zz", "AA", "aa", "aB", "Hb", "Z"}; - GnomeSort gnomeSort = new GnomeSort(); - - gnomeSort.sort(integers); - gnomeSort.sort(strings); + return null; + } - System.out.println("After sort : "); - print(integers); - print(strings); + public static void main(String[] args) { + Integer[] integers = {4, 23, 6, 78, 1, 26, 11, 23, 0, -6, 3, 54, 231, 9, 12}; + String[] strings = {"c", "a", "e", "b", "d", "dd", "da", "zz", "AA", "aa", "aB", "Hb", "Z"}; + GnomeSort gnomeSort = new GnomeSort(); + gnomeSort.sort(integers); + gnomeSort.sort(strings); - } - + System.out.println("After sort : "); + print(integers); + print(strings); + } } diff --git a/Sorts/HeapSort.java b/Sorts/HeapSort.java index 77e63c7085b8..29f14bab658e 100644 --- a/Sorts/HeapSort.java +++ b/Sorts/HeapSort.java @@ -1,129 +1,121 @@ package Sorts; +import static Sorts.SortUtils.*; + import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import static Sorts.SortUtils.*; - /** - * Heap Sort Algorithm - * Implements MinHeap + * Heap Sort Algorithm Implements MinHeap * * @author Podshivalov Nikita (https://github.com/nikitap492) */ public class HeapSort implements SortAlgorithm { + private static class Heap> { + /** Array to store heap */ + private T[] heap; - private static class Heap> { - /** - * Array to store heap - */ - private T[] heap; - - /** - * Constructor - * - * @param heap array of unordered integers - */ - public Heap(T[] heap) { - this.heap = heap; - } + /** + * Constructor + * + * @param heap array of unordered integers + */ + public Heap(T[] heap) { + this.heap = heap; + } - /** - * Heapifies subtree from top as root to last as last child - * - * @param rootIndex index of root - * @param lastChild index of last child - */ - private void heapSubtree(int rootIndex, int lastChild) { - int leftIndex = rootIndex * 2 + 1; - int rightIndex = rootIndex * 2 + 2; - T root = heap[rootIndex]; - if (rightIndex <= lastChild) { // if has right and left children - T left = heap[leftIndex]; - T right = heap[rightIndex]; - if (less(left, right) && less(left, root)) { - swap(heap, leftIndex, rootIndex); - heapSubtree(leftIndex, lastChild); - } else if (less(right, root)) { - swap(heap, rightIndex, rootIndex); - heapSubtree(rightIndex, lastChild); - } - } else if (leftIndex <= lastChild) { // if no right child, but has left child - T left = heap[leftIndex]; - if (less(left, root)) { - swap(heap, leftIndex, rootIndex); - heapSubtree(leftIndex, lastChild); - } - } + /** + * Heapifies subtree from top as root to last as last child + * + * @param rootIndex index of root + * @param lastChild index of last child + */ + private void heapSubtree(int rootIndex, int lastChild) { + int leftIndex = rootIndex * 2 + 1; + int rightIndex = rootIndex * 2 + 2; + T root = heap[rootIndex]; + if (rightIndex <= lastChild) { // if has right and left children + T left = heap[leftIndex]; + T right = heap[rightIndex]; + if (less(left, right) && less(left, root)) { + swap(heap, leftIndex, rootIndex); + heapSubtree(leftIndex, lastChild); + } else if (less(right, root)) { + swap(heap, rightIndex, rootIndex); + heapSubtree(rightIndex, lastChild); } - - - /** - * Makes heap with root as root - * - * @param root index of root of heap - */ - private void makeMinHeap(int root) { - int leftIndex = root * 2 + 1; - int rightIndex = root * 2 + 2; - boolean hasLeftChild = leftIndex < heap.length; - boolean hasRightChild = rightIndex < heap.length; - if (hasRightChild) { //if has left and right - makeMinHeap(leftIndex); - makeMinHeap(rightIndex); - heapSubtree(root, heap.length - 1); - } else if (hasLeftChild) { - heapSubtree(root, heap.length - 1); - } + } else if (leftIndex <= lastChild) { // if no right child, but has left child + T left = heap[leftIndex]; + if (less(left, root)) { + swap(heap, leftIndex, rootIndex); + heapSubtree(leftIndex, lastChild); } - - /** - * Gets the root of heap - * - * @return root of heap - */ - private T getRoot(int size) { - swap(heap, 0, size); - heapSubtree(0, size - 1); - return heap[size]; // return old root - } - - + } } - @Override - public > T[] sort(T[] unsorted) { - return sort(Arrays.asList(unsorted)).toArray(unsorted); + /** + * Makes heap with root as root + * + * @param root index of root of heap + */ + private void makeMinHeap(int root) { + int leftIndex = root * 2 + 1; + int rightIndex = root * 2 + 2; + boolean hasLeftChild = leftIndex < heap.length; + boolean hasRightChild = rightIndex < heap.length; + if (hasRightChild) { // if has left and right + makeMinHeap(leftIndex); + makeMinHeap(rightIndex); + heapSubtree(root, heap.length - 1); + } else if (hasLeftChild) { + heapSubtree(root, heap.length - 1); + } } - @Override - public > List sort(List unsorted) { - int size = unsorted.size(); + /** + * Gets the root of heap + * + * @return root of heap + */ + private T getRoot(int size) { + swap(heap, 0, size); + heapSubtree(0, size - 1); + return heap[size]; // return old root + } + } - @SuppressWarnings("unchecked") - Heap heap = new Heap<>(unsorted.toArray((T[]) new Comparable[unsorted.size()])); + @Override + public > T[] sort(T[] unsorted) { + return sort(Arrays.asList(unsorted)).toArray(unsorted); + } - heap.makeMinHeap(0); // make min heap using index 0 as root. - List sorted = new ArrayList<>(size); - while (size > 0) { - T min = heap.getRoot(--size); - sorted.add(min); - } + @Override + public > List sort(List unsorted) { + int size = unsorted.size(); - return sorted; - } + @SuppressWarnings("unchecked") + Heap heap = new Heap<>(unsorted.toArray((T[]) new Comparable[unsorted.size()])); - /** - * Main method - * - * @param args the command line arguments - */ - public static void main(String[] args) { - Integer[] heap = {4, 23, 6, 78, 1, 54, 231, 9, 12}; - HeapSort heapSort = new HeapSort(); - print(heapSort.sort(heap)); + heap.makeMinHeap(0); // make min heap using index 0 as root. + List sorted = new ArrayList<>(size); + while (size > 0) { + T min = heap.getRoot(--size); + sorted.add(min); } + return sorted; + } + + /** + * Main method + * + * @param args the command line arguments + */ + public static void main(String[] args) { + Integer[] heap = {4, 23, 6, 78, 1, 54, 231, 9, 12}; + HeapSort heapSort = new HeapSort(); + print(heapSort.sort(heap)); + } } diff --git a/Sorts/InsertionSort.java b/Sorts/InsertionSort.java index 9a7169f77dfa..d2dd1c93e409 100644 --- a/Sorts/InsertionSort.java +++ b/Sorts/InsertionSort.java @@ -7,52 +7,49 @@ * @author Varun Upadhyay (https://github.com/varunu28) * @author Podshivalov Nikita (https://github.com/nikitap492) */ - class InsertionSort implements SortAlgorithm { - /** - * This method implements the Generic Insertion Sort - * Sorts the array in increasing order - * - * @param array The array to be sorted - **/ - - @Override - public > T[] sort(T[] array) { - for (int j = 1; j < array.length; j++) { - - // Picking up the key(Card) - T key = array[j]; - int i = j - 1; - - while (i >= 0 && less(key, array[i])) { - array[i + 1] = array[i]; - i--; - } - // Placing the key (Card) at its correct position in the sorted subarray - array[i + 1] = key; - } - return array; + /** + * This method implements the Generic Insertion Sort Sorts the array in increasing order + * + * @param array The array to be sorted + */ + @Override + public > T[] sort(T[] array) { + for (int j = 1; j < array.length; j++) { + + // Picking up the key(Card) + T key = array[j]; + int i = j - 1; + + while (i >= 0 && less(key, array[i])) { + array[i + 1] = array[i]; + i--; + } + // Placing the key (Card) at its correct position in the sorted subarray + array[i + 1] = key; } + return array; + } - // Driver Program - public static void main(String[] args) { - // Integer Input - Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12}; + // Driver Program + public static void main(String[] args) { + // Integer Input + Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12}; - InsertionSort sort = new InsertionSort(); + InsertionSort sort = new InsertionSort(); - sort.sort(integers); + sort.sort(integers); - // Output => 1 4 6 9 12 23 54 78 231 - print(integers); + // Output => 1 4 6 9 12 23 54 78 231 + print(integers); - // String Input - String[] strings = {"c", "a", "e", "b", "d"}; + // String Input + String[] strings = {"c", "a", "e", "b", "d"}; - sort.sort(strings); + sort.sort(strings); - //Output => a b c d e - print(strings); - } + // Output => a b c d e + print(strings); + } } diff --git a/Sorts/MergeSort.java b/Sorts/MergeSort.java index f15e7af4578f..dfd350afb283 100644 --- a/Sorts/MergeSort.java +++ b/Sorts/MergeSort.java @@ -9,90 +9,84 @@ * @author Podshivalov Nikita (https://github.com/nikitap492) * @see SortAlgorithm */ - class MergeSort implements SortAlgorithm { - /** - * This method implements the Generic Merge Sort - * - * @param unsorted the array which should be sorted - * @param Comparable class - * @return sorted array - */ - @Override - - public > T[] sort(T[] unsorted) { - doSort(unsorted, 0, unsorted.length - 1); - return unsorted; + /** + * This method implements the Generic Merge Sort + * + * @param unsorted the array which should be sorted + * @param Comparable class + * @return sorted array + */ + @Override + public > T[] sort(T[] unsorted) { + doSort(unsorted, 0, unsorted.length - 1); + return unsorted; + } + + /** + * @param arr The array to be sorted + * @param left The first index of the array + * @param right The last index of the array Recursively sorts the array in increasing order + */ + private static > void doSort(T[] arr, int left, int right) { + if (left < right) { + int mid = left + (right - left) / 2; + doSort(arr, left, mid); + doSort(arr, mid + 1, right); + merge(arr, left, mid, right); } - - /** - * @param arr The array to be sorted - * @param left The first index of the array - * @param right The last index of the array - * Recursively sorts the array in increasing order - **/ - private static > void doSort(T[] arr, int left, int right) { - if (left < right) { - int mid = left + (right - left) / 2; - doSort(arr, left, mid); - doSort(arr, mid + 1, right); - merge(arr, left, mid, right); - } - + } + + /** + * This method implements the merge step of the merge sort + * + * @param arr The array to be sorted + * @param left The first index of the array + * @param mid The middle index of the array + * @param right The last index of the array merges two parts of an array in increasing order + */ + private static > void merge(T[] arr, int left, int mid, int right) { + int length = right - left + 1; + T[] temp = (T[]) new Comparable[length]; + int i = left; + int j = mid + 1; + int k = 0; + + while (i <= mid && j <= right) { + if (arr[i].compareTo(arr[j]) <= 0) { + temp[k++] = arr[i++]; + } else { + temp[k++] = arr[j++]; + } } - /** - * This method implements the merge step of the merge sort - * - * @param arr The array to be sorted - * @param left The first index of the array - * @param mid The middle index of the array - * @param right The last index of the array - * merges two parts of an array in increasing order - **/ - - private static > void merge(T[] arr, int left, int mid, int right) { - int length = right - left + 1; - T[] temp = (T[]) new Comparable[length]; - int i = left; - int j = mid + 1; - int k = 0; - - while (i <= mid && j <= right) { - if (arr[i].compareTo(arr[j]) <= 0) { - temp[k++] = arr[i++]; - } else { - temp[k++] = arr[j++]; - } - } - - while (i <= mid) { - temp[k++] = arr[i++]; - } - - while (j <= right) { - temp[k++] = arr[j++]; - } + while (i <= mid) { + temp[k++] = arr[i++]; + } - System.arraycopy(temp, 0, arr, left, length); + while (j <= right) { + temp[k++] = arr[j++]; } - // Driver program - public static void main(String[] args) { + System.arraycopy(temp, 0, arr, left, length); + } - // Integer Input - Integer[] arr = {4, 23, 6, 78, 1, 54, 231, 9, 12}; - MergeSort mergeSort = new MergeSort(); - mergeSort.sort(arr); + // Driver program + public static void main(String[] args) { - // Output => 1 4 6 9 12 23 54 78 231 - print(arr); + // Integer Input + Integer[] arr = {4, 23, 6, 78, 1, 54, 231, 9, 12}; + MergeSort mergeSort = new MergeSort(); + mergeSort.sort(arr); - // String Inpu - String[] stringArray = {"c", "a", "e", "b", "d"}; - mergeSort.sort(stringArray); - //Output => a b c d e - print(stringArray); - } + // Output => 1 4 6 9 12 23 54 78 231 + print(arr); + + // String Inpu + String[] stringArray = {"c", "a", "e", "b", "d"}; + mergeSort.sort(stringArray); + // Output => a b c d e + print(stringArray); + } } diff --git a/Sorts/PancakeSort.java b/Sorts/PancakeSort.java index 330e9d0f6a60..f679b37226ad 100644 --- a/Sorts/PancakeSort.java +++ b/Sorts/PancakeSort.java @@ -7,36 +7,35 @@ * * @author Podshivalov Nikita (https://github.com/nikitap492) * @since 2018-04-10 - **/ + */ public class PancakeSort implements SortAlgorithm { - @Override - public > T[] sort(T[] array) { - int size = array.length; - - for (int i = 0; i < size; i++) { - T max = array[0]; - int index = 0; - for (int j = 0; j < size - i; j++) { - if (less(max, array[j])) { - max = array[j]; - index = j; - } - } - flip(array, index, array.length - 1 - i); + @Override + public > T[] sort(T[] array) { + int size = array.length; + + for (int i = 0; i < size; i++) { + T max = array[0]; + int index = 0; + for (int j = 0; j < size - i; j++) { + if (less(max, array[j])) { + max = array[j]; + index = j; } - return array; + } + flip(array, index, array.length - 1 - i); } - - - public static void main(String[] args) { - - Integer[] arr = {10, 9, 8, 7, 6, 15, 14, 7, 4, 3, 8, 6, 3, 1, 2, -2, -5, -8, -3, -1, 13, 12, 11, 5, 4, 3, 2, 1}; - PancakeSort pancakeSort = new PancakeSort(); - System.out.println("After sorting:"); - pancakeSort.sort(arr); - print(arr); - } - - + return array; + } + + public static void main(String[] args) { + + Integer[] arr = { + 10, 9, 8, 7, 6, 15, 14, 7, 4, 3, 8, 6, 3, 1, 2, -2, -5, -8, -3, -1, 13, 12, 11, 5, 4, 3, 2, 1 + }; + PancakeSort pancakeSort = new PancakeSort(); + System.out.println("After sorting:"); + pancakeSort.sort(arr); + print(arr); + } } diff --git a/Sorts/QuickSort.java b/Sorts/QuickSort.java index ef564ac722cb..b88b1dec5ce4 100644 --- a/Sorts/QuickSort.java +++ b/Sorts/QuickSort.java @@ -9,97 +9,89 @@ */ class QuickSort implements SortAlgorithm { - /** - * This method implements the Generic Quick Sort - * - * @param array The array to be sorted - * Sorts the array in increasing order - **/ - - @Override - public > T[] sort(T[] array) { - doSort(array, 0, array.length - 1); - return array; + /** + * This method implements the Generic Quick Sort + * + * @param array The array to be sorted Sorts the array in increasing order + */ + @Override + public > T[] sort(T[] array) { + doSort(array, 0, array.length - 1); + return array; + } + + /** + * The sorting process + * + * @param left The first index of an array + * @param right The last index of an array + * @param array The array to be sorted + */ + private static > void doSort(T[] array, int left, int right) { + if (left < right) { + int pivot = randomPartition(array, left, right); + doSort(array, left, pivot - 1); + doSort(array, pivot, right); } - - - /** - * The sorting process - * - * @param left The first index of an array - * @param right The last index of an array - * @param array The array to be sorted - **/ - - private static > void doSort(T[] array, int left, int right) { - if (left < right) { - int pivot = randomPartition(array, left, right); - doSort(array, left, pivot - 1); - doSort(array, pivot, right); - } + } + + /** + * Ramdomize the array to avoid the basically ordered sequences + * + * @param array The array to be sorted + * @param left The first index of an array + * @param right The last index of an array + * @return the partition index of the array + */ + private static > int randomPartition(T[] array, int left, int right) { + int randomIndex = left + (int) (Math.random() * (right - left + 1)); + swap(array, randomIndex, right); + return partition(array, left, right); + } + + /** + * This method finds the partition index for an array + * + * @param array The array to be sorted + * @param left The first index of an array + * @param right The last index of an array Finds the partition index of an array + */ + private static > int partition(T[] array, int left, int right) { + int mid = (left + right) >>> 1; + T pivot = array[mid]; + + while (left <= right) { + while (less(array[left], pivot)) { + ++left; + } + while (less(pivot, array[right])) { + --right; + } + if (left <= right) { + swap(array, left, right); + ++left; + --right; + } } + return left; + } - /** - * Ramdomize the array to avoid the basically ordered sequences - * - * @param array The array to be sorted - * @param left The first index of an array - * @param right The last index of an array - * @return the partition index of the array - */ + // Driver Program + public static void main(String[] args) { - private static > int randomPartition(T[] array, int left, int right) { - int randomIndex = left + (int)(Math.random()*(right - left + 1)); - swap(array, randomIndex, right); - return partition(array, left, right); - } - - /** - * This method finds the partition index for an array - * - * @param array The array to be sorted - * @param left The first index of an array - * @param right The last index of an array - * Finds the partition index of an array - **/ + // For integer input + Integer[] array = {3, 4, 1, 32, 0, 1, 5, 12, 2, 5, 7, 8, 9, 2, 44, 111, 5}; - private static > int partition(T[] array, int left, int right) { - int mid = (left + right) >>> 1; - T pivot = array[mid]; + QuickSort quickSort = new QuickSort(); + quickSort.sort(array); - while (left <= right) { - while (less(array[left], pivot)) { - ++left; - } - while (less(pivot, array[right])) { - --right; - } - if (left <= right) { - swap(array, left, right); - ++left; - --right; - } - } - return left; - } + // Output => 0 1 1 2 2 3 4 5 5 5 7 8 9 12 32 44 111 + print(array); - // Driver Program - public static void main(String[] args) { + String[] stringArray = {"c", "a", "e", "b", "d"}; + quickSort.sort(stringArray); - // For integer input - Integer[] array = {3, 4, 1, 32, 0, 1, 5, 12, 2, 5, 7, 8, 9, 2, 44, 111, 5}; - - QuickSort quickSort = new QuickSort(); - quickSort.sort(array); - - //Output => 0 1 1 2 2 3 4 5 5 5 7 8 9 12 32 44 111 - print(array); - - String[] stringArray = {"c", "a", "e", "b", "d"}; - quickSort.sort(stringArray); - - //Output => a b c d e - print(stringArray); - } + // Output => a b c d e + print(stringArray); + } } - diff --git a/Sorts/RadixSort.java b/Sorts/RadixSort.java index ca9ed767eaa0..83515fc03bb2 100644 --- a/Sorts/RadixSort.java +++ b/Sorts/RadixSort.java @@ -4,56 +4,46 @@ class RadixSort { - private static int getMax(int[] arr, int n) { - int mx = arr[0]; - for (int i = 1; i < n; i++) - if (arr[i] > mx) - mx = arr[i]; - return mx; - } - - private static void countSort(int[] arr, int n, int exp) { - int[] output = new int[n]; - int i; - int[] count = new int[10]; - Arrays.fill(count, 0); + private static int getMax(int[] arr, int n) { + int mx = arr[0]; + for (int i = 1; i < n; i++) if (arr[i] > mx) mx = arr[i]; + return mx; + } - for (i = 0; i < n; i++) - count[(arr[i] / exp) % 10]++; + private static void countSort(int[] arr, int n, int exp) { + int[] output = new int[n]; + int i; + int[] count = new int[10]; + Arrays.fill(count, 0); - for (i = 1; i < 10; i++) - count[i] += count[i - 1]; + for (i = 0; i < n; i++) count[(arr[i] / exp) % 10]++; - for (i = n - 1; i >= 0; i--) { - output[count[(arr[i] / exp) % 10] - 1] = arr[i]; - count[(arr[i] / exp) % 10]--; - } + for (i = 1; i < 10; i++) count[i] += count[i - 1]; - for (i = 0; i < n; i++) - arr[i] = output[i]; + for (i = n - 1; i >= 0; i--) { + output[count[(arr[i] / exp) % 10] - 1] = arr[i]; + count[(arr[i] / exp) % 10]--; } - private static void radixsort(int[] arr, int n) { + for (i = 0; i < n; i++) arr[i] = output[i]; + } - int m = getMax(arr, n); + private static void radixsort(int[] arr, int n) { + int m = getMax(arr, n); - for (int exp = 1; m / exp > 0; exp *= 10) - countSort(arr, n, exp); - } + for (int exp = 1; m / exp > 0; exp *= 10) countSort(arr, n, exp); + } + static void print(int[] arr, int n) { + for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); + } - static void print(int[] arr, int n) { - for (int i = 0; i < n; i++) - System.out.print(arr[i] + " "); - } - - - public static void main(String[] args) { - int[] arr = {170, 45, 75, 90, 802, 24, 2, 66}; - int n = arr.length; - radixsort(arr, n); - print(arr, n); - } + public static void main(String[] args) { + int[] arr = {170, 45, 75, 90, 802, 24, 2, 66}; + int n = arr.length; + radixsort(arr, n); + print(arr, n); + } } // Written by James Mc Dermott(theycallmemac) diff --git a/Sorts/SelectionSort.java b/Sorts/SelectionSort.java index 31b16c5bb171..5b850dd33723 100644 --- a/Sorts/SelectionSort.java +++ b/Sorts/SelectionSort.java @@ -5,67 +5,64 @@ * @author Podshivalov Nikita (https://github.com/nikitap492) * @see SortAlgorithm */ - public class SelectionSort implements SortAlgorithm { - /** - * This method swaps the two elements in the array - * @param - * @param arr, i, j The array for the swap and - the indexes of the to-swap elements - */ - - public void swap(T[] arr, int i, int j) { - T temp = arr[i]; - arr[i] = arr[j]; - arr[j] = temp; - } - - /** - * This method implements the Generic Selection Sort - * - * @param arr The array to be sorted - * Sorts the array in increasing order - **/ - @Override - public > T[] sort(T[] arr) { - int n = arr.length; - for (int i = 0; i < n - 1; i++) { - // Initial index of min - int min = i; + /** + * This method swaps the two elements in the array + * + * @param + * @param arr, i, j The array for the swap and the indexes of the to-swap elements + */ + public void swap(T[] arr, int i, int j) { + T temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } - for (int j = i + 1; j < n; j++) { - if (arr[min].compareTo(arr[j]) < 0) { - min = j; - } - } + /** + * This method implements the Generic Selection Sort + * + * @param arr The array to be sorted Sorts the array in increasing order + */ + @Override + public > T[] sort(T[] arr) { + int n = arr.length; + for (int i = 0; i < n - 1; i++) { + // Initial index of min + int min = i; - // Swapping if index of min is changed - if (min != i) { - swap(arr, i, min); - } + for (int j = i + 1; j < n; j++) { + if (arr[min].compareTo(arr[j]) < 0) { + min = j; } + } - return arr; + // Swapping if index of min is changed + if (min != i) { + swap(arr, i, min); + } } - // Driver Program - public static void main(String[] args) { + return arr; + } - Integer[] arr = {4, 23, 6, 78, 1, 54, 231, 9, 12}; + // Driver Program + public static void main(String[] args) { - SelectionSort selectionSort = new SelectionSort(); + Integer[] arr = {4, 23, 6, 78, 1, 54, 231, 9, 12}; - Integer[] sorted = selectionSort.sort(arr); + SelectionSort selectionSort = new SelectionSort(); - // Output => 1 4 6 9 12 23 54 78 231 - SortUtils.print(sorted); + Integer[] sorted = selectionSort.sort(arr); - // String Input - String[] strings = {"c", "a", "e", "b", "d"}; - String[] sortedStrings = selectionSort.sort(strings); + // Output => 1 4 6 9 12 23 54 78 231 + SortUtils.print(sorted); - //Output => a b c d e - SortUtils.print(sortedStrings); - } + // String Input + String[] strings = {"c", "a", "e", "b", "d"}; + String[] sortedStrings = selectionSort.sort(strings); + + // Output => a b c d e + SortUtils.print(sortedStrings); + } } diff --git a/Sorts/ShellSort.java b/Sorts/ShellSort.java index b29119a0c3af..79ae6e2df5fa 100644 --- a/Sorts/ShellSort.java +++ b/Sorts/ShellSort.java @@ -4,39 +4,39 @@ public class ShellSort implements SortAlgorithm { - /** - * This method implements Generic Shell Sort. - * - * @param array the array to be sorted - */ - @Override - public > T[] sort(T[] array) { - int length = array.length; - int gap = 1; + /** + * This method implements Generic Shell Sort. + * + * @param array the array to be sorted + */ + @Override + public > T[] sort(T[] array) { + int length = array.length; + int gap = 1; - /* Calculate gap for optimization purpose */ - while (gap < length / 3) { - gap = 3 * gap + 1; - } + /* Calculate gap for optimization purpose */ + while (gap < length / 3) { + gap = 3 * gap + 1; + } - for (; gap > 0; gap /= 3) { - for (int i = gap; i < length; i++) { - int j; - T temp = array[i]; - for (j = i; j >= gap && less(temp, array[j - gap]); j -= gap) { - array[j] = array[j - gap]; - } - array[j] = temp; - } + for (; gap > 0; gap /= 3) { + for (int i = gap; i < length; i++) { + int j; + T temp = array[i]; + for (j = i; j >= gap && less(temp, array[j - gap]); j -= gap) { + array[j] = array[j - gap]; } - return array; + array[j] = temp; + } } + return array; + } - /* Driver Code */ - public static void main(String[] args) { - Integer[] toSort = {4, 23, 6, 78, 1, 54, 231, 9, 12}; + /* Driver Code */ + public static void main(String[] args) { + Integer[] toSort = {4, 23, 6, 78, 1, 54, 231, 9, 12}; - ShellSort sort = new ShellSort(); - print(sort.sort(toSort)); - } + ShellSort sort = new ShellSort(); + print(sort.sort(toSort)); + } } diff --git a/Sorts/SortAlgorithm.java b/Sorts/SortAlgorithm.java index d4d0309da27d..d686cea95911 100644 --- a/Sorts/SortAlgorithm.java +++ b/Sorts/SortAlgorithm.java @@ -7,26 +7,25 @@ * The common interface of most sorting algorithms * * @author Podshivalov Nikita (https://github.com/nikitap492) - **/ + */ public interface SortAlgorithm { - /** - * Main method arrays sorting algorithms - * - * @param unsorted - an array should be sorted - * @return a sorted array - */ - > T[] sort(T[] unsorted); - - /** - * Auxiliary method for algorithms what wanted to work with lists from JCF - * - * @param unsorted - a list should be sorted - * @return a sorted list - */ - @SuppressWarnings("unchecked") - default > List sort(List unsorted) { - return Arrays.asList(sort(unsorted.toArray((T[]) new Comparable[unsorted.size()]))); - } + /** + * Main method arrays sorting algorithms + * + * @param unsorted - an array should be sorted + * @return a sorted array + */ + > T[] sort(T[] unsorted); + /** + * Auxiliary method for algorithms what wanted to work with lists from JCF + * + * @param unsorted - a list should be sorted + * @return a sorted list + */ + @SuppressWarnings("unchecked") + default > List sort(List unsorted) { + return Arrays.asList(sort(unsorted.toArray((T[]) new Comparable[unsorted.size()]))); + } } diff --git a/Sorts/SortUtils.java b/Sorts/SortUtils.java index 334e3c1c1ad5..da8be334ebd2 100644 --- a/Sorts/SortUtils.java +++ b/Sorts/SortUtils.java @@ -7,83 +7,75 @@ * The class contains util methods * * @author Podshivalov Nikita (https://github.com/nikitap492) - **/ + */ final class SortUtils { - /** - * Helper method for swapping places in array - * - * @param array The array which elements we want to swap - * @param idx index of the first element - * @param idy index of the second element - */ - static boolean swap(T[] array, int idx, int idy) { - T swap = array[idx]; - array[idx] = array[idy]; - array[idy] = swap; - return true; - } - - - /** - * This method checks if first element is less than the other element - * - * @param v first element - * @param w second element - * @return true if the first element is less than the second element - */ - static > boolean less(T v, T w) { - return v.compareTo(w) < 0; - } - - - /** - * This method checks if first element is greater than the other element - * - * @param v first element - * @param w second element - * @return true if the first element is greater than the second element - */ - static > boolean greater(T v, T w) { - return v.compareTo(w) > 0; - } + /** + * Helper method for swapping places in array + * + * @param array The array which elements we want to swap + * @param idx index of the first element + * @param idy index of the second element + */ + static boolean swap(T[] array, int idx, int idy) { + T swap = array[idx]; + array[idx] = array[idy]; + array[idy] = swap; + return true; + } + /** + * This method checks if first element is less than the other element + * + * @param v first element + * @param w second element + * @return true if the first element is less than the second element + */ + static > boolean less(T v, T w) { + return v.compareTo(w) < 0; + } - /** - * Prints a list - * - * @param toPrint - a list which should be printed - */ - static void print(List toPrint) { - toPrint.stream() - .map(Object::toString) - .map(str -> str + " ") - .forEach(System.out::print); + /** + * This method checks if first element is greater than the other element + * + * @param v first element + * @param w second element + * @return true if the first element is greater than the second element + */ + static > boolean greater(T v, T w) { + return v.compareTo(w) > 0; + } - System.out.println(); - } + /** + * Prints a list + * + * @param toPrint - a list which should be printed + */ + static void print(List toPrint) { + toPrint.stream().map(Object::toString).map(str -> str + " ").forEach(System.out::print); + System.out.println(); + } - /** - * Prints an array - * - * @param toPrint - an array which should be printed - */ - static void print(Object[] toPrint) { - System.out.println(Arrays.toString(toPrint)); - } - + /** + * Prints an array + * + * @param toPrint - an array which should be printed + */ + static void print(Object[] toPrint) { + System.out.println(Arrays.toString(toPrint)); + } - /** - * Swaps all position from {@param left} to @{@param right} for {@param array} - * - * @param array is an array - * @param left is a left flip border of the array - * @param right is a right flip border of the array - */ - static > void flip(T[] array, int left, int right) { - while (left <= right) { - swap(array, left++, right--); - } + /** + * Swaps all position from {@param left} to @{@param right} for {@param array} + * + * @param array is an array + * @param left is a left flip border of the array + * @param right is a right flip border of the array + */ + static > void flip(T[] array, int left, int right) { + while (left <= right) { + swap(array, left++, right--); } + } } diff --git a/ciphers/AES.java b/ciphers/AES.java index 1bef34f0d4f3..433ae15bf9ff 100644 --- a/ciphers/AES.java +++ b/ciphers/AES.java @@ -4,598 +4,623 @@ import java.util.Scanner; /** - * This class is build to demonstrate the application of the AES-algorithm on a - * single 128-Bit block of data. - * + * This class is build to demonstrate the application of the AES-algorithm on a single 128-Bit block + * of data. */ public class AES { - /** - * Precalculated values for x to the power of 2 in Rijndaels galois field. Used - * as 'RCON' during the key expansion. - */ - private static final int[] RCON = { 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, - 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, - 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, - 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, - 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, - 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, - 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, - 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, - 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, - 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, - 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, - 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, - 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, - 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, - 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d }; - - /** - * Rijndael S-box Substitution table used for encryption in the subBytes step, - * as well as the key expansion. - */ - private static final int[] SBOX = { 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, - 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, - 0xC0, 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, 0x04, - 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, - 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, 0x53, 0xD1, 0x00, 0xED, 0x20, - 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF, 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, - 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8, 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, - 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, - 0x3D, 0x64, 0x5D, 0x19, 0x73, 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, - 0x5E, 0x0B, 0xDB, 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, - 0x79, 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08, 0xBA, - 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A, 0x70, 0x3E, 0xB5, - 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, 0xE1, 0xF8, 0x98, 0x11, 0x69, - 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF, 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, - 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16 }; - - /** - * Inverse Rijndael S-box Substitution table used for decryption in the - * subBytesDec step. - */ - private static final int[] INVERSE_SBOX = { 0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, - 0x81, 0xF3, 0xD7, 0xFB, 0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, - 0xE9, 0xCB, 0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E, - 0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25, 0x72, 0xF8, - 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92, 0x6C, 0x70, 0x48, 0x50, - 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84, 0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, - 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06, 0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, - 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B, 0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, - 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73, 0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8, - 0x1C, 0x75, 0xDF, 0x6E, 0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, - 0xBE, 0x1B, 0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4, - 0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F, 0x60, 0x51, - 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF, 0xA0, 0xE0, 0x3B, 0x4D, - 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, - 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D }; - - /** - * Precalculated lookup table for galois field multiplication by 2 used in the - * MixColums step during encryption. - */ - private static final int[] MULT2 = { 0x00, 0x02, 0x04, 0x06, 0x08, 0x0a, 0x0c, 0x0e, 0x10, 0x12, 0x14, 0x16, 0x18, - 0x1a, 0x1c, 0x1e, 0x20, 0x22, 0x24, 0x26, 0x28, 0x2a, 0x2c, 0x2e, 0x30, 0x32, 0x34, 0x36, 0x38, 0x3a, 0x3c, - 0x3e, 0x40, 0x42, 0x44, 0x46, 0x48, 0x4a, 0x4c, 0x4e, 0x50, 0x52, 0x54, 0x56, 0x58, 0x5a, 0x5c, 0x5e, 0x60, - 0x62, 0x64, 0x66, 0x68, 0x6a, 0x6c, 0x6e, 0x70, 0x72, 0x74, 0x76, 0x78, 0x7a, 0x7c, 0x7e, 0x80, 0x82, 0x84, - 0x86, 0x88, 0x8a, 0x8c, 0x8e, 0x90, 0x92, 0x94, 0x96, 0x98, 0x9a, 0x9c, 0x9e, 0xa0, 0xa2, 0xa4, 0xa6, 0xa8, - 0xaa, 0xac, 0xae, 0xb0, 0xb2, 0xb4, 0xb6, 0xb8, 0xba, 0xbc, 0xbe, 0xc0, 0xc2, 0xc4, 0xc6, 0xc8, 0xca, 0xcc, - 0xce, 0xd0, 0xd2, 0xd4, 0xd6, 0xd8, 0xda, 0xdc, 0xde, 0xe0, 0xe2, 0xe4, 0xe6, 0xe8, 0xea, 0xec, 0xee, 0xf0, - 0xf2, 0xf4, 0xf6, 0xf8, 0xfa, 0xfc, 0xfe, 0x1b, 0x19, 0x1f, 0x1d, 0x13, 0x11, 0x17, 0x15, 0x0b, 0x09, 0x0f, - 0x0d, 0x03, 0x01, 0x07, 0x05, 0x3b, 0x39, 0x3f, 0x3d, 0x33, 0x31, 0x37, 0x35, 0x2b, 0x29, 0x2f, 0x2d, 0x23, - 0x21, 0x27, 0x25, 0x5b, 0x59, 0x5f, 0x5d, 0x53, 0x51, 0x57, 0x55, 0x4b, 0x49, 0x4f, 0x4d, 0x43, 0x41, 0x47, - 0x45, 0x7b, 0x79, 0x7f, 0x7d, 0x73, 0x71, 0x77, 0x75, 0x6b, 0x69, 0x6f, 0x6d, 0x63, 0x61, 0x67, 0x65, 0x9b, - 0x99, 0x9f, 0x9d, 0x93, 0x91, 0x97, 0x95, 0x8b, 0x89, 0x8f, 0x8d, 0x83, 0x81, 0x87, 0x85, 0xbb, 0xb9, 0xbf, - 0xbd, 0xb3, 0xb1, 0xb7, 0xb5, 0xab, 0xa9, 0xaf, 0xad, 0xa3, 0xa1, 0xa7, 0xa5, 0xdb, 0xd9, 0xdf, 0xdd, 0xd3, - 0xd1, 0xd7, 0xd5, 0xcb, 0xc9, 0xcf, 0xcd, 0xc3, 0xc1, 0xc7, 0xc5, 0xfb, 0xf9, 0xff, 0xfd, 0xf3, 0xf1, 0xf7, - 0xf5, 0xeb, 0xe9, 0xef, 0xed, 0xe3, 0xe1, 0xe7, 0xe5 }; - - /** - * Precalculated lookup table for galois field multiplication by 3 used in the - * MixColums step during encryption. - */ - private static final int[] MULT3 = { 0x00, 0x03, 0x06, 0x05, 0x0c, 0x0f, 0x0a, 0x09, 0x18, 0x1b, 0x1e, 0x1d, 0x14, - 0x17, 0x12, 0x11, 0x30, 0x33, 0x36, 0x35, 0x3c, 0x3f, 0x3a, 0x39, 0x28, 0x2b, 0x2e, 0x2d, 0x24, 0x27, 0x22, - 0x21, 0x60, 0x63, 0x66, 0x65, 0x6c, 0x6f, 0x6a, 0x69, 0x78, 0x7b, 0x7e, 0x7d, 0x74, 0x77, 0x72, 0x71, 0x50, - 0x53, 0x56, 0x55, 0x5c, 0x5f, 0x5a, 0x59, 0x48, 0x4b, 0x4e, 0x4d, 0x44, 0x47, 0x42, 0x41, 0xc0, 0xc3, 0xc6, - 0xc5, 0xcc, 0xcf, 0xca, 0xc9, 0xd8, 0xdb, 0xde, 0xdd, 0xd4, 0xd7, 0xd2, 0xd1, 0xf0, 0xf3, 0xf6, 0xf5, 0xfc, - 0xff, 0xfa, 0xf9, 0xe8, 0xeb, 0xee, 0xed, 0xe4, 0xe7, 0xe2, 0xe1, 0xa0, 0xa3, 0xa6, 0xa5, 0xac, 0xaf, 0xaa, - 0xa9, 0xb8, 0xbb, 0xbe, 0xbd, 0xb4, 0xb7, 0xb2, 0xb1, 0x90, 0x93, 0x96, 0x95, 0x9c, 0x9f, 0x9a, 0x99, 0x88, - 0x8b, 0x8e, 0x8d, 0x84, 0x87, 0x82, 0x81, 0x9b, 0x98, 0x9d, 0x9e, 0x97, 0x94, 0x91, 0x92, 0x83, 0x80, 0x85, - 0x86, 0x8f, 0x8c, 0x89, 0x8a, 0xab, 0xa8, 0xad, 0xae, 0xa7, 0xa4, 0xa1, 0xa2, 0xb3, 0xb0, 0xb5, 0xb6, 0xbf, - 0xbc, 0xb9, 0xba, 0xfb, 0xf8, 0xfd, 0xfe, 0xf7, 0xf4, 0xf1, 0xf2, 0xe3, 0xe0, 0xe5, 0xe6, 0xef, 0xec, 0xe9, - 0xea, 0xcb, 0xc8, 0xcd, 0xce, 0xc7, 0xc4, 0xc1, 0xc2, 0xd3, 0xd0, 0xd5, 0xd6, 0xdf, 0xdc, 0xd9, 0xda, 0x5b, - 0x58, 0x5d, 0x5e, 0x57, 0x54, 0x51, 0x52, 0x43, 0x40, 0x45, 0x46, 0x4f, 0x4c, 0x49, 0x4a, 0x6b, 0x68, 0x6d, - 0x6e, 0x67, 0x64, 0x61, 0x62, 0x73, 0x70, 0x75, 0x76, 0x7f, 0x7c, 0x79, 0x7a, 0x3b, 0x38, 0x3d, 0x3e, 0x37, - 0x34, 0x31, 0x32, 0x23, 0x20, 0x25, 0x26, 0x2f, 0x2c, 0x29, 0x2a, 0x0b, 0x08, 0x0d, 0x0e, 0x07, 0x04, 0x01, - 0x02, 0x13, 0x10, 0x15, 0x16, 0x1f, 0x1c, 0x19, 0x1a }; - - /** - * Precalculated lookup table for galois field multiplication by 9 used in the - * MixColums step during decryption. - */ - private static final int[] MULT9 = { 0x00, 0x09, 0x12, 0x1b, 0x24, 0x2d, 0x36, 0x3f, 0x48, 0x41, 0x5a, 0x53, 0x6c, - 0x65, 0x7e, 0x77, 0x90, 0x99, 0x82, 0x8b, 0xb4, 0xbd, 0xa6, 0xaf, 0xd8, 0xd1, 0xca, 0xc3, 0xfc, 0xf5, 0xee, - 0xe7, 0x3b, 0x32, 0x29, 0x20, 0x1f, 0x16, 0x0d, 0x04, 0x73, 0x7a, 0x61, 0x68, 0x57, 0x5e, 0x45, 0x4c, 0xab, - 0xa2, 0xb9, 0xb0, 0x8f, 0x86, 0x9d, 0x94, 0xe3, 0xea, 0xf1, 0xf8, 0xc7, 0xce, 0xd5, 0xdc, 0x76, 0x7f, 0x64, - 0x6d, 0x52, 0x5b, 0x40, 0x49, 0x3e, 0x37, 0x2c, 0x25, 0x1a, 0x13, 0x08, 0x01, 0xe6, 0xef, 0xf4, 0xfd, 0xc2, - 0xcb, 0xd0, 0xd9, 0xae, 0xa7, 0xbc, 0xb5, 0x8a, 0x83, 0x98, 0x91, 0x4d, 0x44, 0x5f, 0x56, 0x69, 0x60, 0x7b, - 0x72, 0x05, 0x0c, 0x17, 0x1e, 0x21, 0x28, 0x33, 0x3a, 0xdd, 0xd4, 0xcf, 0xc6, 0xf9, 0xf0, 0xeb, 0xe2, 0x95, - 0x9c, 0x87, 0x8e, 0xb1, 0xb8, 0xa3, 0xaa, 0xec, 0xe5, 0xfe, 0xf7, 0xc8, 0xc1, 0xda, 0xd3, 0xa4, 0xad, 0xb6, - 0xbf, 0x80, 0x89, 0x92, 0x9b, 0x7c, 0x75, 0x6e, 0x67, 0x58, 0x51, 0x4a, 0x43, 0x34, 0x3d, 0x26, 0x2f, 0x10, - 0x19, 0x02, 0x0b, 0xd7, 0xde, 0xc5, 0xcc, 0xf3, 0xfa, 0xe1, 0xe8, 0x9f, 0x96, 0x8d, 0x84, 0xbb, 0xb2, 0xa9, - 0xa0, 0x47, 0x4e, 0x55, 0x5c, 0x63, 0x6a, 0x71, 0x78, 0x0f, 0x06, 0x1d, 0x14, 0x2b, 0x22, 0x39, 0x30, 0x9a, - 0x93, 0x88, 0x81, 0xbe, 0xb7, 0xac, 0xa5, 0xd2, 0xdb, 0xc0, 0xc9, 0xf6, 0xff, 0xe4, 0xed, 0x0a, 0x03, 0x18, - 0x11, 0x2e, 0x27, 0x3c, 0x35, 0x42, 0x4b, 0x50, 0x59, 0x66, 0x6f, 0x74, 0x7d, 0xa1, 0xa8, 0xb3, 0xba, 0x85, - 0x8c, 0x97, 0x9e, 0xe9, 0xe0, 0xfb, 0xf2, 0xcd, 0xc4, 0xdf, 0xd6, 0x31, 0x38, 0x23, 0x2a, 0x15, 0x1c, 0x07, - 0x0e, 0x79, 0x70, 0x6b, 0x62, 0x5d, 0x54, 0x4f, 0x46 }; - - /** - * Precalculated lookup table for galois field multiplication by 11 used in the - * MixColums step during decryption. - */ - private static final int[] MULT11 = { 0x00, 0x0b, 0x16, 0x1d, 0x2c, 0x27, 0x3a, 0x31, 0x58, 0x53, 0x4e, 0x45, 0x74, - 0x7f, 0x62, 0x69, 0xb0, 0xbb, 0xa6, 0xad, 0x9c, 0x97, 0x8a, 0x81, 0xe8, 0xe3, 0xfe, 0xf5, 0xc4, 0xcf, 0xd2, - 0xd9, 0x7b, 0x70, 0x6d, 0x66, 0x57, 0x5c, 0x41, 0x4a, 0x23, 0x28, 0x35, 0x3e, 0x0f, 0x04, 0x19, 0x12, 0xcb, - 0xc0, 0xdd, 0xd6, 0xe7, 0xec, 0xf1, 0xfa, 0x93, 0x98, 0x85, 0x8e, 0xbf, 0xb4, 0xa9, 0xa2, 0xf6, 0xfd, 0xe0, - 0xeb, 0xda, 0xd1, 0xcc, 0xc7, 0xae, 0xa5, 0xb8, 0xb3, 0x82, 0x89, 0x94, 0x9f, 0x46, 0x4d, 0x50, 0x5b, 0x6a, - 0x61, 0x7c, 0x77, 0x1e, 0x15, 0x08, 0x03, 0x32, 0x39, 0x24, 0x2f, 0x8d, 0x86, 0x9b, 0x90, 0xa1, 0xaa, 0xb7, - 0xbc, 0xd5, 0xde, 0xc3, 0xc8, 0xf9, 0xf2, 0xef, 0xe4, 0x3d, 0x36, 0x2b, 0x20, 0x11, 0x1a, 0x07, 0x0c, 0x65, - 0x6e, 0x73, 0x78, 0x49, 0x42, 0x5f, 0x54, 0xf7, 0xfc, 0xe1, 0xea, 0xdb, 0xd0, 0xcd, 0xc6, 0xaf, 0xa4, 0xb9, - 0xb2, 0x83, 0x88, 0x95, 0x9e, 0x47, 0x4c, 0x51, 0x5a, 0x6b, 0x60, 0x7d, 0x76, 0x1f, 0x14, 0x09, 0x02, 0x33, - 0x38, 0x25, 0x2e, 0x8c, 0x87, 0x9a, 0x91, 0xa0, 0xab, 0xb6, 0xbd, 0xd4, 0xdf, 0xc2, 0xc9, 0xf8, 0xf3, 0xee, - 0xe5, 0x3c, 0x37, 0x2a, 0x21, 0x10, 0x1b, 0x06, 0x0d, 0x64, 0x6f, 0x72, 0x79, 0x48, 0x43, 0x5e, 0x55, 0x01, - 0x0a, 0x17, 0x1c, 0x2d, 0x26, 0x3b, 0x30, 0x59, 0x52, 0x4f, 0x44, 0x75, 0x7e, 0x63, 0x68, 0xb1, 0xba, 0xa7, - 0xac, 0x9d, 0x96, 0x8b, 0x80, 0xe9, 0xe2, 0xff, 0xf4, 0xc5, 0xce, 0xd3, 0xd8, 0x7a, 0x71, 0x6c, 0x67, 0x56, - 0x5d, 0x40, 0x4b, 0x22, 0x29, 0x34, 0x3f, 0x0e, 0x05, 0x18, 0x13, 0xca, 0xc1, 0xdc, 0xd7, 0xe6, 0xed, 0xf0, - 0xfb, 0x92, 0x99, 0x84, 0x8f, 0xbe, 0xb5, 0xa8, 0xa3 }; - - /** - * Precalculated lookup table for galois field multiplication by 13 used in the - * MixColums step during decryption. - */ - private static final int[] MULT13 = { 0x00, 0x0d, 0x1a, 0x17, 0x34, 0x39, 0x2e, 0x23, 0x68, 0x65, 0x72, 0x7f, 0x5c, - 0x51, 0x46, 0x4b, 0xd0, 0xdd, 0xca, 0xc7, 0xe4, 0xe9, 0xfe, 0xf3, 0xb8, 0xb5, 0xa2, 0xaf, 0x8c, 0x81, 0x96, - 0x9b, 0xbb, 0xb6, 0xa1, 0xac, 0x8f, 0x82, 0x95, 0x98, 0xd3, 0xde, 0xc9, 0xc4, 0xe7, 0xea, 0xfd, 0xf0, 0x6b, - 0x66, 0x71, 0x7c, 0x5f, 0x52, 0x45, 0x48, 0x03, 0x0e, 0x19, 0x14, 0x37, 0x3a, 0x2d, 0x20, 0x6d, 0x60, 0x77, - 0x7a, 0x59, 0x54, 0x43, 0x4e, 0x05, 0x08, 0x1f, 0x12, 0x31, 0x3c, 0x2b, 0x26, 0xbd, 0xb0, 0xa7, 0xaa, 0x89, - 0x84, 0x93, 0x9e, 0xd5, 0xd8, 0xcf, 0xc2, 0xe1, 0xec, 0xfb, 0xf6, 0xd6, 0xdb, 0xcc, 0xc1, 0xe2, 0xef, 0xf8, - 0xf5, 0xbe, 0xb3, 0xa4, 0xa9, 0x8a, 0x87, 0x90, 0x9d, 0x06, 0x0b, 0x1c, 0x11, 0x32, 0x3f, 0x28, 0x25, 0x6e, - 0x63, 0x74, 0x79, 0x5a, 0x57, 0x40, 0x4d, 0xda, 0xd7, 0xc0, 0xcd, 0xee, 0xe3, 0xf4, 0xf9, 0xb2, 0xbf, 0xa8, - 0xa5, 0x86, 0x8b, 0x9c, 0x91, 0x0a, 0x07, 0x10, 0x1d, 0x3e, 0x33, 0x24, 0x29, 0x62, 0x6f, 0x78, 0x75, 0x56, - 0x5b, 0x4c, 0x41, 0x61, 0x6c, 0x7b, 0x76, 0x55, 0x58, 0x4f, 0x42, 0x09, 0x04, 0x13, 0x1e, 0x3d, 0x30, 0x27, - 0x2a, 0xb1, 0xbc, 0xab, 0xa6, 0x85, 0x88, 0x9f, 0x92, 0xd9, 0xd4, 0xc3, 0xce, 0xed, 0xe0, 0xf7, 0xfa, 0xb7, - 0xba, 0xad, 0xa0, 0x83, 0x8e, 0x99, 0x94, 0xdf, 0xd2, 0xc5, 0xc8, 0xeb, 0xe6, 0xf1, 0xfc, 0x67, 0x6a, 0x7d, - 0x70, 0x53, 0x5e, 0x49, 0x44, 0x0f, 0x02, 0x15, 0x18, 0x3b, 0x36, 0x21, 0x2c, 0x0c, 0x01, 0x16, 0x1b, 0x38, - 0x35, 0x22, 0x2f, 0x64, 0x69, 0x7e, 0x73, 0x50, 0x5d, 0x4a, 0x47, 0xdc, 0xd1, 0xc6, 0xcb, 0xe8, 0xe5, 0xf2, - 0xff, 0xb4, 0xb9, 0xae, 0xa3, 0x80, 0x8d, 0x9a, 0x97 }; - - /** - * Precalculated lookup table for galois field multiplication by 14 used in the - * MixColums step during decryption. - */ - private static final int[] MULT14 = { 0x00, 0x0e, 0x1c, 0x12, 0x38, 0x36, 0x24, 0x2a, 0x70, 0x7e, 0x6c, 0x62, 0x48, - 0x46, 0x54, 0x5a, 0xe0, 0xee, 0xfc, 0xf2, 0xd8, 0xd6, 0xc4, 0xca, 0x90, 0x9e, 0x8c, 0x82, 0xa8, 0xa6, 0xb4, - 0xba, 0xdb, 0xd5, 0xc7, 0xc9, 0xe3, 0xed, 0xff, 0xf1, 0xab, 0xa5, 0xb7, 0xb9, 0x93, 0x9d, 0x8f, 0x81, 0x3b, - 0x35, 0x27, 0x29, 0x03, 0x0d, 0x1f, 0x11, 0x4b, 0x45, 0x57, 0x59, 0x73, 0x7d, 0x6f, 0x61, 0xad, 0xa3, 0xb1, - 0xbf, 0x95, 0x9b, 0x89, 0x87, 0xdd, 0xd3, 0xc1, 0xcf, 0xe5, 0xeb, 0xf9, 0xf7, 0x4d, 0x43, 0x51, 0x5f, 0x75, - 0x7b, 0x69, 0x67, 0x3d, 0x33, 0x21, 0x2f, 0x05, 0x0b, 0x19, 0x17, 0x76, 0x78, 0x6a, 0x64, 0x4e, 0x40, 0x52, - 0x5c, 0x06, 0x08, 0x1a, 0x14, 0x3e, 0x30, 0x22, 0x2c, 0x96, 0x98, 0x8a, 0x84, 0xae, 0xa0, 0xb2, 0xbc, 0xe6, - 0xe8, 0xfa, 0xf4, 0xde, 0xd0, 0xc2, 0xcc, 0x41, 0x4f, 0x5d, 0x53, 0x79, 0x77, 0x65, 0x6b, 0x31, 0x3f, 0x2d, - 0x23, 0x09, 0x07, 0x15, 0x1b, 0xa1, 0xaf, 0xbd, 0xb3, 0x99, 0x97, 0x85, 0x8b, 0xd1, 0xdf, 0xcd, 0xc3, 0xe9, - 0xe7, 0xf5, 0xfb, 0x9a, 0x94, 0x86, 0x88, 0xa2, 0xac, 0xbe, 0xb0, 0xea, 0xe4, 0xf6, 0xf8, 0xd2, 0xdc, 0xce, - 0xc0, 0x7a, 0x74, 0x66, 0x68, 0x42, 0x4c, 0x5e, 0x50, 0x0a, 0x04, 0x16, 0x18, 0x32, 0x3c, 0x2e, 0x20, 0xec, - 0xe2, 0xf0, 0xfe, 0xd4, 0xda, 0xc8, 0xc6, 0x9c, 0x92, 0x80, 0x8e, 0xa4, 0xaa, 0xb8, 0xb6, 0x0c, 0x02, 0x10, - 0x1e, 0x34, 0x3a, 0x28, 0x26, 0x7c, 0x72, 0x60, 0x6e, 0x44, 0x4a, 0x58, 0x56, 0x37, 0x39, 0x2b, 0x25, 0x0f, - 0x01, 0x13, 0x1d, 0x47, 0x49, 0x5b, 0x55, 0x7f, 0x71, 0x63, 0x6d, 0xd7, 0xd9, 0xcb, 0xc5, 0xef, 0xe1, 0xf3, - 0xfd, 0xa7, 0xa9, 0xbb, 0xb5, 0x9f, 0x91, 0x83, 0x8d }; - - /** - * Subroutine of the Rijndael key expansion. - * - * @param t - * @param rconCounter - * @return - */ - public static BigInteger scheduleCore(BigInteger t, int rconCounter) { - String rBytes = t.toString(16); - - // Add zero padding - while (rBytes.length() < 8) { - rBytes = "0" + rBytes; - } - - // rotate the first 16 bits to the back - String rotatingBytes = rBytes.substring(0, 2); - String fixedBytes = rBytes.substring(2); - - rBytes = fixedBytes + rotatingBytes; - - // apply S-Box to all 8-Bit Substrings - for (int i = 0; i < 4; i++) { - String currentByteBits = rBytes.substring(i * 2, (i + 1) * 2); - - int currentByte = Integer.parseInt(currentByteBits, 16); - currentByte = SBOX[currentByte]; - - // add the current RCON value to the first byte - if (i == 0) { - currentByte = currentByte ^ RCON[rconCounter]; - } - - currentByteBits = Integer.toHexString(currentByte); - - // Add zero padding - - while (currentByteBits.length() < 2) { - currentByteBits = '0' + currentByteBits; - } - - // replace bytes in original string - rBytes = rBytes.substring(0, i * 2) + currentByteBits + rBytes.substring((i + 1) * 2); - } - - // t = new BigInteger(rBytes, 16); - // return t; - return new BigInteger(rBytes, 16); - } - - /** - * - * Returns an array of 10 + 1 round keys that are calculated by using Rijndael - * key schedule - * - * @param initialKey - * @return array of 10 + 1 round keys - */ - public static BigInteger[] keyExpansion(BigInteger initialKey) { - BigInteger[] roundKeys = { initialKey, new BigInteger("0"), new BigInteger("0"), new BigInteger("0"), - new BigInteger("0"), new BigInteger("0"), new BigInteger("0"), new BigInteger("0"), new BigInteger("0"), - new BigInteger("0"), new BigInteger("0"), }; - - // initialize rcon iteration - int rconCounter = 1; - - for (int i = 1; i < 11; i++) { - - // get the previous 32 bits the key - BigInteger t = roundKeys[i - 1].remainder(new BigInteger("100000000", 16)); - - // split previous key into 8-bit segments - BigInteger[] prevKey = { roundKeys[i - 1].remainder(new BigInteger("100000000", 16)), - roundKeys[i - 1].remainder(new BigInteger("10000000000000000", 16)) - .divide(new BigInteger("100000000", 16)), - roundKeys[i - 1].remainder(new BigInteger("1000000000000000000000000", 16)) - .divide(new BigInteger("10000000000000000", 16)), - roundKeys[i - 1].divide(new BigInteger("1000000000000000000000000", 16)), }; - - // run schedule core - t = scheduleCore(t, rconCounter); - rconCounter += 1; - - // Calculate partial round key - BigInteger t0 = t.xor(prevKey[3]); - BigInteger t1 = t0.xor(prevKey[2]); - BigInteger t2 = t1.xor(prevKey[1]); - BigInteger t3 = t2.xor(prevKey[0]); - - // Join round key segments - t2 = t2.multiply(new BigInteger("100000000", 16)); - t1 = t1.multiply(new BigInteger("10000000000000000", 16)); - t0 = t0.multiply(new BigInteger("1000000000000000000000000", 16)); - roundKeys[i] = t0.add(t1).add(t2).add(t3); - - } - return roundKeys; - } - - /** - * representation of the input 128-bit block as an array of 8-bit integers. - * - * @param block - * of 128-bit integers - * @return array of 8-bit integers - */ - public static int[] splitBlockIntoCells(BigInteger block) { - - int[] cells = new int[16]; - String blockBits = block.toString(2); - - // Append leading 0 for full "128-bit" string - while (blockBits.length() < 128) { - blockBits = '0' + blockBits; - } - - // split 128 to 8 bit cells - for (int i = 0; i < cells.length; i++) { - String cellBits = blockBits.substring(8 * i, 8 * (i + 1)); - cells[i] = Integer.parseInt(cellBits, 2); - } - - return cells; - } - - /** - * Returns the 128-bit BigInteger representation of the input of an array of - * 8-bit integers. - * - * @param cells - * that we need to merge - * @return block of merged cells - */ - public static BigInteger mergeCellsIntoBlock(int[] cells) { - - String blockBits = ""; - for (int i = 0; i < 16; i++) { - String cellBits = Integer.toBinaryString(cells[i]); - - // Append leading 0 for full "8-bit" strings - while (cellBits.length() < 8) { - cellBits = '0' + cellBits; - } - - blockBits += cellBits; - } - - return new BigInteger(blockBits, 2); - } - - /** - * - * @param ciphertext - * @param key - * @return ciphertext XOR key - */ - public static BigInteger addRoundKey(BigInteger ciphertext, BigInteger key) { - return ciphertext.xor(key); - } - - /** - * substitutes 8-Bit long substrings of the input using the S-Box and returns - * the result. - * - * @param ciphertext - * @return subtraction Output - */ - public static BigInteger subBytes(BigInteger ciphertext) { - - int[] cells = splitBlockIntoCells(ciphertext); - - for (int i = 0; i < 16; i++) { - cells[i] = SBOX[cells[i]]; - } - - return mergeCellsIntoBlock(cells); - } - - /** - * substitutes 8-Bit long substrings of the input using the inverse S-Box for - * decryption and returns the result. - * - * @param ciphertext - * @return subtraction Output - */ - public static BigInteger subBytesDec(BigInteger ciphertext) { - - int[] cells = splitBlockIntoCells(ciphertext); - - for (int i = 0; i < 16; i++) { - cells[i] = INVERSE_SBOX[cells[i]]; - } - - return mergeCellsIntoBlock(cells); - } - - /** - * Cell permutation step. Shifts cells within the rows of the input and returns - * the result. - * - * @param ciphertext - */ - public static BigInteger shiftRows(BigInteger ciphertext) { - int[] cells = splitBlockIntoCells(ciphertext); - int[] output = new int[16]; - - // do nothing in the first row - output[0] = cells[0]; - output[4] = cells[4]; - output[8] = cells[8]; - output[12] = cells[12]; - - // shift the second row backwards by one cell - output[1] = cells[5]; - output[5] = cells[9]; - output[9] = cells[13]; - output[13] = cells[1]; - - // shift the third row backwards by two cell - output[2] = cells[10]; - output[6] = cells[14]; - output[10] = cells[2]; - output[14] = cells[6]; - - // shift the forth row backwards by tree cell - output[3] = cells[15]; - output[7] = cells[3]; - output[11] = cells[7]; - output[15] = cells[11]; - - return mergeCellsIntoBlock(output); - } - - /** - * Cell permutation step for decryption . Shifts cells within the rows of the - * input and returns the result. - * - * @param ciphertext - */ - public static BigInteger shiftRowsDec(BigInteger ciphertext) { - int[] cells = splitBlockIntoCells(ciphertext); - int[] output = new int[16]; - - // do nothing in the first row - output[0] = cells[0]; - output[4] = cells[4]; - output[8] = cells[8]; - output[12] = cells[12]; - - // shift the second row forwards by one cell - output[1] = cells[13]; - output[5] = cells[1]; - output[9] = cells[5]; - output[13] = cells[9]; - - // shift the third row forwards by two cell - output[2] = cells[10]; - output[6] = cells[14]; - output[10] = cells[2]; - output[14] = cells[6]; - - // shift the forth row forwards by tree cell - output[3] = cells[7]; - output[7] = cells[11]; - output[11] = cells[15]; - output[15] = cells[3]; - - return mergeCellsIntoBlock(output); - } - - /** - * Applies the Rijndael MixColumns to the input and returns the result. - * - * @param ciphertext - */ - public static BigInteger mixColumns(BigInteger ciphertext) { - - int[] cells = splitBlockIntoCells(ciphertext); - int[] outputCells = new int[16]; - - for (int i = 0; i < 4; i++) { - int[] row = { cells[i * 4], cells[i * 4 + 1], cells[i * 4 + 2], cells[i * 4 + 3] }; - - outputCells[i * 4] = MULT2[row[0]] ^ MULT3[row[1]] ^ row[2] ^ row[3]; - outputCells[i * 4 + 1] = row[0] ^ MULT2[row[1]] ^ MULT3[row[2]] ^ row[3]; - outputCells[i * 4 + 2] = row[0] ^ row[1] ^ MULT2[row[2]] ^ MULT3[row[3]]; - outputCells[i * 4 + 3] = MULT3[row[0]] ^ row[1] ^ row[2] ^ MULT2[row[3]]; - } - return mergeCellsIntoBlock(outputCells); - } - - /** - * Applies the inverse Rijndael MixColumns for decryption to the input and - * returns the result. - * - * @param ciphertext - */ - public static BigInteger mixColumnsDec(BigInteger ciphertext) { - - int[] cells = splitBlockIntoCells(ciphertext); - int[] outputCells = new int[16]; - - for (int i = 0; i < 4; i++) { - int[] row = { cells[i * 4], cells[i * 4 + 1], cells[i * 4 + 2], cells[i * 4 + 3] }; - - outputCells[i * 4] = MULT14[row[0]] ^ MULT11[row[1]] ^ MULT13[row[2]] ^ MULT9[row[3]]; - outputCells[i * 4 + 1] = MULT9[row[0]] ^ MULT14[row[1]] ^ MULT11[row[2]] ^ MULT13[row[3]]; - outputCells[i * 4 + 2] = MULT13[row[0]] ^ MULT9[row[1]] ^ MULT14[row[2]] ^ MULT11[row[3]]; - outputCells[i * 4 + 3] = MULT11[row[0]] ^ MULT13[row[1]] ^ MULT9[row[2]] ^ MULT14[row[3]]; - } - return mergeCellsIntoBlock(outputCells); - } - - /** - * Encrypts the plaintext with the key and returns the result - * - * @param plainText - * which we want to encrypt - * @param key - * the key for encrypt - * @return EncryptedText - */ - public static BigInteger encrypt(BigInteger plainText, BigInteger key) { - BigInteger[] roundKeys = keyExpansion(key); - - // Initial round - plainText = addRoundKey(plainText, roundKeys[0]); - - // Main rounds - for (int i = 1; i < 10; i++) { - plainText = subBytes(plainText); - plainText = shiftRows(plainText); - plainText = mixColumns(plainText); - plainText = addRoundKey(plainText, roundKeys[i]); - } - - // Final round - plainText = subBytes(plainText); - plainText = shiftRows(plainText); - plainText = addRoundKey(plainText, roundKeys[10]); - - return plainText; - } - - /** - * Decrypts the ciphertext with the key and returns the result - * - * @param cipherText - * The Encrypted text which we want to decrypt - * @param key - * @return decryptedText - */ - public static BigInteger decrypt(BigInteger cipherText, BigInteger key) { - - BigInteger[] roundKeys = keyExpansion(key); - - // Invert final round - cipherText = addRoundKey(cipherText, roundKeys[10]); - cipherText = shiftRowsDec(cipherText); - cipherText = subBytesDec(cipherText); - - // Invert main rounds - for (int i = 9; i > 0; i--) { - cipherText = addRoundKey(cipherText, roundKeys[i]); - cipherText = mixColumnsDec(cipherText); - cipherText = shiftRowsDec(cipherText); - cipherText = subBytesDec(cipherText); - } - - // Invert initial round - cipherText = addRoundKey(cipherText, roundKeys[0]); - - return cipherText; - } - - public static void main(String[] args) { - - try (Scanner input = new Scanner(System.in)) { - System.out.println("Enter (e) letter for encrpyt or (d) letter for decrypt :"); - char choice = input.nextLine().charAt(0); - String in; - switch (choice) { - case 'E': - case 'e': - System.out.println("Choose a plaintext block (128-Bit Integer in base 16):"); - in = input.nextLine(); - BigInteger plaintext = new BigInteger(in, 16); - System.out.println("Choose a Key (128-Bit Integer in base 16):"); - in = input.nextLine(); - BigInteger encryptionKey = new BigInteger(in, 16); - System.out.println("The encrypted message is: \n" + encrypt(plaintext, encryptionKey).toString(16)); - break; - case 'D': - case 'd': - System.out.println("Enter your ciphertext block (128-Bit Integer in base 16):"); - in = input.nextLine(); - BigInteger ciphertext = new BigInteger(in, 16); - System.out.println("Choose a Key (128-Bit Integer in base 16):"); - in = input.nextLine(); - BigInteger decryptionKey = new BigInteger(in, 16); - System.out.println("The deciphered message is:\n" + decrypt(ciphertext, decryptionKey).toString(16)); - break; - default: - System.out.println("** End **"); - } - } - - } + /** + * Precalculated values for x to the power of 2 in Rijndaels galois field. Used as 'RCON' during + * the key expansion. + */ + private static final int[] RCON = { + 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, + 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, + 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, + 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, + 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, + 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, + 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, + 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, + 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, + 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, + 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, + 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, + 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, + 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, + 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, + 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d + }; + + /** + * Rijndael S-box Substitution table used for encryption in the subBytes step, as well as the key + * expansion. + */ + private static final int[] SBOX = { + 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, + 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, + 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, + 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75, + 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, + 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF, + 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8, + 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, + 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73, + 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB, + 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, + 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08, + 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A, + 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, + 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF, + 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16 + }; + + /** Inverse Rijndael S-box Substitution table used for decryption in the subBytesDec step. */ + private static final int[] INVERSE_SBOX = { + 0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB, + 0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB, + 0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E, + 0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25, + 0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92, + 0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84, + 0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06, + 0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B, + 0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73, + 0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E, + 0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B, + 0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4, + 0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F, + 0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF, + 0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61, + 0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D + }; + + /** + * Precalculated lookup table for galois field multiplication by 2 used in the MixColums step + * during encryption. + */ + private static final int[] MULT2 = { + 0x00, 0x02, 0x04, 0x06, 0x08, 0x0a, 0x0c, 0x0e, 0x10, 0x12, 0x14, 0x16, 0x18, 0x1a, 0x1c, 0x1e, + 0x20, 0x22, 0x24, 0x26, 0x28, 0x2a, 0x2c, 0x2e, 0x30, 0x32, 0x34, 0x36, 0x38, 0x3a, 0x3c, 0x3e, + 0x40, 0x42, 0x44, 0x46, 0x48, 0x4a, 0x4c, 0x4e, 0x50, 0x52, 0x54, 0x56, 0x58, 0x5a, 0x5c, 0x5e, + 0x60, 0x62, 0x64, 0x66, 0x68, 0x6a, 0x6c, 0x6e, 0x70, 0x72, 0x74, 0x76, 0x78, 0x7a, 0x7c, 0x7e, + 0x80, 0x82, 0x84, 0x86, 0x88, 0x8a, 0x8c, 0x8e, 0x90, 0x92, 0x94, 0x96, 0x98, 0x9a, 0x9c, 0x9e, + 0xa0, 0xa2, 0xa4, 0xa6, 0xa8, 0xaa, 0xac, 0xae, 0xb0, 0xb2, 0xb4, 0xb6, 0xb8, 0xba, 0xbc, 0xbe, + 0xc0, 0xc2, 0xc4, 0xc6, 0xc8, 0xca, 0xcc, 0xce, 0xd0, 0xd2, 0xd4, 0xd6, 0xd8, 0xda, 0xdc, 0xde, + 0xe0, 0xe2, 0xe4, 0xe6, 0xe8, 0xea, 0xec, 0xee, 0xf0, 0xf2, 0xf4, 0xf6, 0xf8, 0xfa, 0xfc, 0xfe, + 0x1b, 0x19, 0x1f, 0x1d, 0x13, 0x11, 0x17, 0x15, 0x0b, 0x09, 0x0f, 0x0d, 0x03, 0x01, 0x07, 0x05, + 0x3b, 0x39, 0x3f, 0x3d, 0x33, 0x31, 0x37, 0x35, 0x2b, 0x29, 0x2f, 0x2d, 0x23, 0x21, 0x27, 0x25, + 0x5b, 0x59, 0x5f, 0x5d, 0x53, 0x51, 0x57, 0x55, 0x4b, 0x49, 0x4f, 0x4d, 0x43, 0x41, 0x47, 0x45, + 0x7b, 0x79, 0x7f, 0x7d, 0x73, 0x71, 0x77, 0x75, 0x6b, 0x69, 0x6f, 0x6d, 0x63, 0x61, 0x67, 0x65, + 0x9b, 0x99, 0x9f, 0x9d, 0x93, 0x91, 0x97, 0x95, 0x8b, 0x89, 0x8f, 0x8d, 0x83, 0x81, 0x87, 0x85, + 0xbb, 0xb9, 0xbf, 0xbd, 0xb3, 0xb1, 0xb7, 0xb5, 0xab, 0xa9, 0xaf, 0xad, 0xa3, 0xa1, 0xa7, 0xa5, + 0xdb, 0xd9, 0xdf, 0xdd, 0xd3, 0xd1, 0xd7, 0xd5, 0xcb, 0xc9, 0xcf, 0xcd, 0xc3, 0xc1, 0xc7, 0xc5, + 0xfb, 0xf9, 0xff, 0xfd, 0xf3, 0xf1, 0xf7, 0xf5, 0xeb, 0xe9, 0xef, 0xed, 0xe3, 0xe1, 0xe7, 0xe5 + }; + + /** + * Precalculated lookup table for galois field multiplication by 3 used in the MixColums step + * during encryption. + */ + private static final int[] MULT3 = { + 0x00, 0x03, 0x06, 0x05, 0x0c, 0x0f, 0x0a, 0x09, 0x18, 0x1b, 0x1e, 0x1d, 0x14, 0x17, 0x12, 0x11, + 0x30, 0x33, 0x36, 0x35, 0x3c, 0x3f, 0x3a, 0x39, 0x28, 0x2b, 0x2e, 0x2d, 0x24, 0x27, 0x22, 0x21, + 0x60, 0x63, 0x66, 0x65, 0x6c, 0x6f, 0x6a, 0x69, 0x78, 0x7b, 0x7e, 0x7d, 0x74, 0x77, 0x72, 0x71, + 0x50, 0x53, 0x56, 0x55, 0x5c, 0x5f, 0x5a, 0x59, 0x48, 0x4b, 0x4e, 0x4d, 0x44, 0x47, 0x42, 0x41, + 0xc0, 0xc3, 0xc6, 0xc5, 0xcc, 0xcf, 0xca, 0xc9, 0xd8, 0xdb, 0xde, 0xdd, 0xd4, 0xd7, 0xd2, 0xd1, + 0xf0, 0xf3, 0xf6, 0xf5, 0xfc, 0xff, 0xfa, 0xf9, 0xe8, 0xeb, 0xee, 0xed, 0xe4, 0xe7, 0xe2, 0xe1, + 0xa0, 0xa3, 0xa6, 0xa5, 0xac, 0xaf, 0xaa, 0xa9, 0xb8, 0xbb, 0xbe, 0xbd, 0xb4, 0xb7, 0xb2, 0xb1, + 0x90, 0x93, 0x96, 0x95, 0x9c, 0x9f, 0x9a, 0x99, 0x88, 0x8b, 0x8e, 0x8d, 0x84, 0x87, 0x82, 0x81, + 0x9b, 0x98, 0x9d, 0x9e, 0x97, 0x94, 0x91, 0x92, 0x83, 0x80, 0x85, 0x86, 0x8f, 0x8c, 0x89, 0x8a, + 0xab, 0xa8, 0xad, 0xae, 0xa7, 0xa4, 0xa1, 0xa2, 0xb3, 0xb0, 0xb5, 0xb6, 0xbf, 0xbc, 0xb9, 0xba, + 0xfb, 0xf8, 0xfd, 0xfe, 0xf7, 0xf4, 0xf1, 0xf2, 0xe3, 0xe0, 0xe5, 0xe6, 0xef, 0xec, 0xe9, 0xea, + 0xcb, 0xc8, 0xcd, 0xce, 0xc7, 0xc4, 0xc1, 0xc2, 0xd3, 0xd0, 0xd5, 0xd6, 0xdf, 0xdc, 0xd9, 0xda, + 0x5b, 0x58, 0x5d, 0x5e, 0x57, 0x54, 0x51, 0x52, 0x43, 0x40, 0x45, 0x46, 0x4f, 0x4c, 0x49, 0x4a, + 0x6b, 0x68, 0x6d, 0x6e, 0x67, 0x64, 0x61, 0x62, 0x73, 0x70, 0x75, 0x76, 0x7f, 0x7c, 0x79, 0x7a, + 0x3b, 0x38, 0x3d, 0x3e, 0x37, 0x34, 0x31, 0x32, 0x23, 0x20, 0x25, 0x26, 0x2f, 0x2c, 0x29, 0x2a, + 0x0b, 0x08, 0x0d, 0x0e, 0x07, 0x04, 0x01, 0x02, 0x13, 0x10, 0x15, 0x16, 0x1f, 0x1c, 0x19, 0x1a + }; + + /** + * Precalculated lookup table for galois field multiplication by 9 used in the MixColums step + * during decryption. + */ + private static final int[] MULT9 = { + 0x00, 0x09, 0x12, 0x1b, 0x24, 0x2d, 0x36, 0x3f, 0x48, 0x41, 0x5a, 0x53, 0x6c, 0x65, 0x7e, 0x77, + 0x90, 0x99, 0x82, 0x8b, 0xb4, 0xbd, 0xa6, 0xaf, 0xd8, 0xd1, 0xca, 0xc3, 0xfc, 0xf5, 0xee, 0xe7, + 0x3b, 0x32, 0x29, 0x20, 0x1f, 0x16, 0x0d, 0x04, 0x73, 0x7a, 0x61, 0x68, 0x57, 0x5e, 0x45, 0x4c, + 0xab, 0xa2, 0xb9, 0xb0, 0x8f, 0x86, 0x9d, 0x94, 0xe3, 0xea, 0xf1, 0xf8, 0xc7, 0xce, 0xd5, 0xdc, + 0x76, 0x7f, 0x64, 0x6d, 0x52, 0x5b, 0x40, 0x49, 0x3e, 0x37, 0x2c, 0x25, 0x1a, 0x13, 0x08, 0x01, + 0xe6, 0xef, 0xf4, 0xfd, 0xc2, 0xcb, 0xd0, 0xd9, 0xae, 0xa7, 0xbc, 0xb5, 0x8a, 0x83, 0x98, 0x91, + 0x4d, 0x44, 0x5f, 0x56, 0x69, 0x60, 0x7b, 0x72, 0x05, 0x0c, 0x17, 0x1e, 0x21, 0x28, 0x33, 0x3a, + 0xdd, 0xd4, 0xcf, 0xc6, 0xf9, 0xf0, 0xeb, 0xe2, 0x95, 0x9c, 0x87, 0x8e, 0xb1, 0xb8, 0xa3, 0xaa, + 0xec, 0xe5, 0xfe, 0xf7, 0xc8, 0xc1, 0xda, 0xd3, 0xa4, 0xad, 0xb6, 0xbf, 0x80, 0x89, 0x92, 0x9b, + 0x7c, 0x75, 0x6e, 0x67, 0x58, 0x51, 0x4a, 0x43, 0x34, 0x3d, 0x26, 0x2f, 0x10, 0x19, 0x02, 0x0b, + 0xd7, 0xde, 0xc5, 0xcc, 0xf3, 0xfa, 0xe1, 0xe8, 0x9f, 0x96, 0x8d, 0x84, 0xbb, 0xb2, 0xa9, 0xa0, + 0x47, 0x4e, 0x55, 0x5c, 0x63, 0x6a, 0x71, 0x78, 0x0f, 0x06, 0x1d, 0x14, 0x2b, 0x22, 0x39, 0x30, + 0x9a, 0x93, 0x88, 0x81, 0xbe, 0xb7, 0xac, 0xa5, 0xd2, 0xdb, 0xc0, 0xc9, 0xf6, 0xff, 0xe4, 0xed, + 0x0a, 0x03, 0x18, 0x11, 0x2e, 0x27, 0x3c, 0x35, 0x42, 0x4b, 0x50, 0x59, 0x66, 0x6f, 0x74, 0x7d, + 0xa1, 0xa8, 0xb3, 0xba, 0x85, 0x8c, 0x97, 0x9e, 0xe9, 0xe0, 0xfb, 0xf2, 0xcd, 0xc4, 0xdf, 0xd6, + 0x31, 0x38, 0x23, 0x2a, 0x15, 0x1c, 0x07, 0x0e, 0x79, 0x70, 0x6b, 0x62, 0x5d, 0x54, 0x4f, 0x46 + }; + + /** + * Precalculated lookup table for galois field multiplication by 11 used in the MixColums step + * during decryption. + */ + private static final int[] MULT11 = { + 0x00, 0x0b, 0x16, 0x1d, 0x2c, 0x27, 0x3a, 0x31, 0x58, 0x53, 0x4e, 0x45, 0x74, 0x7f, 0x62, 0x69, + 0xb0, 0xbb, 0xa6, 0xad, 0x9c, 0x97, 0x8a, 0x81, 0xe8, 0xe3, 0xfe, 0xf5, 0xc4, 0xcf, 0xd2, 0xd9, + 0x7b, 0x70, 0x6d, 0x66, 0x57, 0x5c, 0x41, 0x4a, 0x23, 0x28, 0x35, 0x3e, 0x0f, 0x04, 0x19, 0x12, + 0xcb, 0xc0, 0xdd, 0xd6, 0xe7, 0xec, 0xf1, 0xfa, 0x93, 0x98, 0x85, 0x8e, 0xbf, 0xb4, 0xa9, 0xa2, + 0xf6, 0xfd, 0xe0, 0xeb, 0xda, 0xd1, 0xcc, 0xc7, 0xae, 0xa5, 0xb8, 0xb3, 0x82, 0x89, 0x94, 0x9f, + 0x46, 0x4d, 0x50, 0x5b, 0x6a, 0x61, 0x7c, 0x77, 0x1e, 0x15, 0x08, 0x03, 0x32, 0x39, 0x24, 0x2f, + 0x8d, 0x86, 0x9b, 0x90, 0xa1, 0xaa, 0xb7, 0xbc, 0xd5, 0xde, 0xc3, 0xc8, 0xf9, 0xf2, 0xef, 0xe4, + 0x3d, 0x36, 0x2b, 0x20, 0x11, 0x1a, 0x07, 0x0c, 0x65, 0x6e, 0x73, 0x78, 0x49, 0x42, 0x5f, 0x54, + 0xf7, 0xfc, 0xe1, 0xea, 0xdb, 0xd0, 0xcd, 0xc6, 0xaf, 0xa4, 0xb9, 0xb2, 0x83, 0x88, 0x95, 0x9e, + 0x47, 0x4c, 0x51, 0x5a, 0x6b, 0x60, 0x7d, 0x76, 0x1f, 0x14, 0x09, 0x02, 0x33, 0x38, 0x25, 0x2e, + 0x8c, 0x87, 0x9a, 0x91, 0xa0, 0xab, 0xb6, 0xbd, 0xd4, 0xdf, 0xc2, 0xc9, 0xf8, 0xf3, 0xee, 0xe5, + 0x3c, 0x37, 0x2a, 0x21, 0x10, 0x1b, 0x06, 0x0d, 0x64, 0x6f, 0x72, 0x79, 0x48, 0x43, 0x5e, 0x55, + 0x01, 0x0a, 0x17, 0x1c, 0x2d, 0x26, 0x3b, 0x30, 0x59, 0x52, 0x4f, 0x44, 0x75, 0x7e, 0x63, 0x68, + 0xb1, 0xba, 0xa7, 0xac, 0x9d, 0x96, 0x8b, 0x80, 0xe9, 0xe2, 0xff, 0xf4, 0xc5, 0xce, 0xd3, 0xd8, + 0x7a, 0x71, 0x6c, 0x67, 0x56, 0x5d, 0x40, 0x4b, 0x22, 0x29, 0x34, 0x3f, 0x0e, 0x05, 0x18, 0x13, + 0xca, 0xc1, 0xdc, 0xd7, 0xe6, 0xed, 0xf0, 0xfb, 0x92, 0x99, 0x84, 0x8f, 0xbe, 0xb5, 0xa8, 0xa3 + }; + + /** + * Precalculated lookup table for galois field multiplication by 13 used in the MixColums step + * during decryption. + */ + private static final int[] MULT13 = { + 0x00, 0x0d, 0x1a, 0x17, 0x34, 0x39, 0x2e, 0x23, 0x68, 0x65, 0x72, 0x7f, 0x5c, 0x51, 0x46, 0x4b, + 0xd0, 0xdd, 0xca, 0xc7, 0xe4, 0xe9, 0xfe, 0xf3, 0xb8, 0xb5, 0xa2, 0xaf, 0x8c, 0x81, 0x96, 0x9b, + 0xbb, 0xb6, 0xa1, 0xac, 0x8f, 0x82, 0x95, 0x98, 0xd3, 0xde, 0xc9, 0xc4, 0xe7, 0xea, 0xfd, 0xf0, + 0x6b, 0x66, 0x71, 0x7c, 0x5f, 0x52, 0x45, 0x48, 0x03, 0x0e, 0x19, 0x14, 0x37, 0x3a, 0x2d, 0x20, + 0x6d, 0x60, 0x77, 0x7a, 0x59, 0x54, 0x43, 0x4e, 0x05, 0x08, 0x1f, 0x12, 0x31, 0x3c, 0x2b, 0x26, + 0xbd, 0xb0, 0xa7, 0xaa, 0x89, 0x84, 0x93, 0x9e, 0xd5, 0xd8, 0xcf, 0xc2, 0xe1, 0xec, 0xfb, 0xf6, + 0xd6, 0xdb, 0xcc, 0xc1, 0xe2, 0xef, 0xf8, 0xf5, 0xbe, 0xb3, 0xa4, 0xa9, 0x8a, 0x87, 0x90, 0x9d, + 0x06, 0x0b, 0x1c, 0x11, 0x32, 0x3f, 0x28, 0x25, 0x6e, 0x63, 0x74, 0x79, 0x5a, 0x57, 0x40, 0x4d, + 0xda, 0xd7, 0xc0, 0xcd, 0xee, 0xe3, 0xf4, 0xf9, 0xb2, 0xbf, 0xa8, 0xa5, 0x86, 0x8b, 0x9c, 0x91, + 0x0a, 0x07, 0x10, 0x1d, 0x3e, 0x33, 0x24, 0x29, 0x62, 0x6f, 0x78, 0x75, 0x56, 0x5b, 0x4c, 0x41, + 0x61, 0x6c, 0x7b, 0x76, 0x55, 0x58, 0x4f, 0x42, 0x09, 0x04, 0x13, 0x1e, 0x3d, 0x30, 0x27, 0x2a, + 0xb1, 0xbc, 0xab, 0xa6, 0x85, 0x88, 0x9f, 0x92, 0xd9, 0xd4, 0xc3, 0xce, 0xed, 0xe0, 0xf7, 0xfa, + 0xb7, 0xba, 0xad, 0xa0, 0x83, 0x8e, 0x99, 0x94, 0xdf, 0xd2, 0xc5, 0xc8, 0xeb, 0xe6, 0xf1, 0xfc, + 0x67, 0x6a, 0x7d, 0x70, 0x53, 0x5e, 0x49, 0x44, 0x0f, 0x02, 0x15, 0x18, 0x3b, 0x36, 0x21, 0x2c, + 0x0c, 0x01, 0x16, 0x1b, 0x38, 0x35, 0x22, 0x2f, 0x64, 0x69, 0x7e, 0x73, 0x50, 0x5d, 0x4a, 0x47, + 0xdc, 0xd1, 0xc6, 0xcb, 0xe8, 0xe5, 0xf2, 0xff, 0xb4, 0xb9, 0xae, 0xa3, 0x80, 0x8d, 0x9a, 0x97 + }; + + /** + * Precalculated lookup table for galois field multiplication by 14 used in the MixColums step + * during decryption. + */ + private static final int[] MULT14 = { + 0x00, 0x0e, 0x1c, 0x12, 0x38, 0x36, 0x24, 0x2a, 0x70, 0x7e, 0x6c, 0x62, 0x48, 0x46, 0x54, 0x5a, + 0xe0, 0xee, 0xfc, 0xf2, 0xd8, 0xd6, 0xc4, 0xca, 0x90, 0x9e, 0x8c, 0x82, 0xa8, 0xa6, 0xb4, 0xba, + 0xdb, 0xd5, 0xc7, 0xc9, 0xe3, 0xed, 0xff, 0xf1, 0xab, 0xa5, 0xb7, 0xb9, 0x93, 0x9d, 0x8f, 0x81, + 0x3b, 0x35, 0x27, 0x29, 0x03, 0x0d, 0x1f, 0x11, 0x4b, 0x45, 0x57, 0x59, 0x73, 0x7d, 0x6f, 0x61, + 0xad, 0xa3, 0xb1, 0xbf, 0x95, 0x9b, 0x89, 0x87, 0xdd, 0xd3, 0xc1, 0xcf, 0xe5, 0xeb, 0xf9, 0xf7, + 0x4d, 0x43, 0x51, 0x5f, 0x75, 0x7b, 0x69, 0x67, 0x3d, 0x33, 0x21, 0x2f, 0x05, 0x0b, 0x19, 0x17, + 0x76, 0x78, 0x6a, 0x64, 0x4e, 0x40, 0x52, 0x5c, 0x06, 0x08, 0x1a, 0x14, 0x3e, 0x30, 0x22, 0x2c, + 0x96, 0x98, 0x8a, 0x84, 0xae, 0xa0, 0xb2, 0xbc, 0xe6, 0xe8, 0xfa, 0xf4, 0xde, 0xd0, 0xc2, 0xcc, + 0x41, 0x4f, 0x5d, 0x53, 0x79, 0x77, 0x65, 0x6b, 0x31, 0x3f, 0x2d, 0x23, 0x09, 0x07, 0x15, 0x1b, + 0xa1, 0xaf, 0xbd, 0xb3, 0x99, 0x97, 0x85, 0x8b, 0xd1, 0xdf, 0xcd, 0xc3, 0xe9, 0xe7, 0xf5, 0xfb, + 0x9a, 0x94, 0x86, 0x88, 0xa2, 0xac, 0xbe, 0xb0, 0xea, 0xe4, 0xf6, 0xf8, 0xd2, 0xdc, 0xce, 0xc0, + 0x7a, 0x74, 0x66, 0x68, 0x42, 0x4c, 0x5e, 0x50, 0x0a, 0x04, 0x16, 0x18, 0x32, 0x3c, 0x2e, 0x20, + 0xec, 0xe2, 0xf0, 0xfe, 0xd4, 0xda, 0xc8, 0xc6, 0x9c, 0x92, 0x80, 0x8e, 0xa4, 0xaa, 0xb8, 0xb6, + 0x0c, 0x02, 0x10, 0x1e, 0x34, 0x3a, 0x28, 0x26, 0x7c, 0x72, 0x60, 0x6e, 0x44, 0x4a, 0x58, 0x56, + 0x37, 0x39, 0x2b, 0x25, 0x0f, 0x01, 0x13, 0x1d, 0x47, 0x49, 0x5b, 0x55, 0x7f, 0x71, 0x63, 0x6d, + 0xd7, 0xd9, 0xcb, 0xc5, 0xef, 0xe1, 0xf3, 0xfd, 0xa7, 0xa9, 0xbb, 0xb5, 0x9f, 0x91, 0x83, 0x8d + }; + + /** + * Subroutine of the Rijndael key expansion. + * + * @param t + * @param rconCounter + * @return + */ + public static BigInteger scheduleCore(BigInteger t, int rconCounter) { + String rBytes = t.toString(16); + + // Add zero padding + while (rBytes.length() < 8) { + rBytes = "0" + rBytes; + } + + // rotate the first 16 bits to the back + String rotatingBytes = rBytes.substring(0, 2); + String fixedBytes = rBytes.substring(2); + + rBytes = fixedBytes + rotatingBytes; + + // apply S-Box to all 8-Bit Substrings + for (int i = 0; i < 4; i++) { + String currentByteBits = rBytes.substring(i * 2, (i + 1) * 2); + + int currentByte = Integer.parseInt(currentByteBits, 16); + currentByte = SBOX[currentByte]; + + // add the current RCON value to the first byte + if (i == 0) { + currentByte = currentByte ^ RCON[rconCounter]; + } + + currentByteBits = Integer.toHexString(currentByte); + + // Add zero padding + + while (currentByteBits.length() < 2) { + currentByteBits = '0' + currentByteBits; + } + + // replace bytes in original string + rBytes = rBytes.substring(0, i * 2) + currentByteBits + rBytes.substring((i + 1) * 2); + } + + // t = new BigInteger(rBytes, 16); + // return t; + return new BigInteger(rBytes, 16); + } + + /** + * Returns an array of 10 + 1 round keys that are calculated by using Rijndael key schedule + * + * @param initialKey + * @return array of 10 + 1 round keys + */ + public static BigInteger[] keyExpansion(BigInteger initialKey) { + BigInteger[] roundKeys = { + initialKey, + new BigInteger("0"), + new BigInteger("0"), + new BigInteger("0"), + new BigInteger("0"), + new BigInteger("0"), + new BigInteger("0"), + new BigInteger("0"), + new BigInteger("0"), + new BigInteger("0"), + new BigInteger("0"), + }; + + // initialize rcon iteration + int rconCounter = 1; + + for (int i = 1; i < 11; i++) { + + // get the previous 32 bits the key + BigInteger t = roundKeys[i - 1].remainder(new BigInteger("100000000", 16)); + + // split previous key into 8-bit segments + BigInteger[] prevKey = { + roundKeys[i - 1].remainder(new BigInteger("100000000", 16)), + roundKeys[i - 1] + .remainder(new BigInteger("10000000000000000", 16)) + .divide(new BigInteger("100000000", 16)), + roundKeys[i - 1] + .remainder(new BigInteger("1000000000000000000000000", 16)) + .divide(new BigInteger("10000000000000000", 16)), + roundKeys[i - 1].divide(new BigInteger("1000000000000000000000000", 16)), + }; + + // run schedule core + t = scheduleCore(t, rconCounter); + rconCounter += 1; + + // Calculate partial round key + BigInteger t0 = t.xor(prevKey[3]); + BigInteger t1 = t0.xor(prevKey[2]); + BigInteger t2 = t1.xor(prevKey[1]); + BigInteger t3 = t2.xor(prevKey[0]); + + // Join round key segments + t2 = t2.multiply(new BigInteger("100000000", 16)); + t1 = t1.multiply(new BigInteger("10000000000000000", 16)); + t0 = t0.multiply(new BigInteger("1000000000000000000000000", 16)); + roundKeys[i] = t0.add(t1).add(t2).add(t3); + } + return roundKeys; + } + + /** + * representation of the input 128-bit block as an array of 8-bit integers. + * + * @param block of 128-bit integers + * @return array of 8-bit integers + */ + public static int[] splitBlockIntoCells(BigInteger block) { + + int[] cells = new int[16]; + String blockBits = block.toString(2); + + // Append leading 0 for full "128-bit" string + while (blockBits.length() < 128) { + blockBits = '0' + blockBits; + } + + // split 128 to 8 bit cells + for (int i = 0; i < cells.length; i++) { + String cellBits = blockBits.substring(8 * i, 8 * (i + 1)); + cells[i] = Integer.parseInt(cellBits, 2); + } + + return cells; + } + + /** + * Returns the 128-bit BigInteger representation of the input of an array of 8-bit integers. + * + * @param cells that we need to merge + * @return block of merged cells + */ + public static BigInteger mergeCellsIntoBlock(int[] cells) { + + String blockBits = ""; + for (int i = 0; i < 16; i++) { + String cellBits = Integer.toBinaryString(cells[i]); + + // Append leading 0 for full "8-bit" strings + while (cellBits.length() < 8) { + cellBits = '0' + cellBits; + } + + blockBits += cellBits; + } + + return new BigInteger(blockBits, 2); + } + + /** + * @param ciphertext + * @param key + * @return ciphertext XOR key + */ + public static BigInteger addRoundKey(BigInteger ciphertext, BigInteger key) { + return ciphertext.xor(key); + } + + /** + * substitutes 8-Bit long substrings of the input using the S-Box and returns the result. + * + * @param ciphertext + * @return subtraction Output + */ + public static BigInteger subBytes(BigInteger ciphertext) { + + int[] cells = splitBlockIntoCells(ciphertext); + + for (int i = 0; i < 16; i++) { + cells[i] = SBOX[cells[i]]; + } + + return mergeCellsIntoBlock(cells); + } + + /** + * substitutes 8-Bit long substrings of the input using the inverse S-Box for decryption and + * returns the result. + * + * @param ciphertext + * @return subtraction Output + */ + public static BigInteger subBytesDec(BigInteger ciphertext) { + + int[] cells = splitBlockIntoCells(ciphertext); + + for (int i = 0; i < 16; i++) { + cells[i] = INVERSE_SBOX[cells[i]]; + } + + return mergeCellsIntoBlock(cells); + } + + /** + * Cell permutation step. Shifts cells within the rows of the input and returns the result. + * + * @param ciphertext + */ + public static BigInteger shiftRows(BigInteger ciphertext) { + int[] cells = splitBlockIntoCells(ciphertext); + int[] output = new int[16]; + + // do nothing in the first row + output[0] = cells[0]; + output[4] = cells[4]; + output[8] = cells[8]; + output[12] = cells[12]; + + // shift the second row backwards by one cell + output[1] = cells[5]; + output[5] = cells[9]; + output[9] = cells[13]; + output[13] = cells[1]; + + // shift the third row backwards by two cell + output[2] = cells[10]; + output[6] = cells[14]; + output[10] = cells[2]; + output[14] = cells[6]; + + // shift the forth row backwards by tree cell + output[3] = cells[15]; + output[7] = cells[3]; + output[11] = cells[7]; + output[15] = cells[11]; + + return mergeCellsIntoBlock(output); + } + + /** + * Cell permutation step for decryption . Shifts cells within the rows of the input and returns + * the result. + * + * @param ciphertext + */ + public static BigInteger shiftRowsDec(BigInteger ciphertext) { + int[] cells = splitBlockIntoCells(ciphertext); + int[] output = new int[16]; + + // do nothing in the first row + output[0] = cells[0]; + output[4] = cells[4]; + output[8] = cells[8]; + output[12] = cells[12]; + + // shift the second row forwards by one cell + output[1] = cells[13]; + output[5] = cells[1]; + output[9] = cells[5]; + output[13] = cells[9]; + + // shift the third row forwards by two cell + output[2] = cells[10]; + output[6] = cells[14]; + output[10] = cells[2]; + output[14] = cells[6]; + + // shift the forth row forwards by tree cell + output[3] = cells[7]; + output[7] = cells[11]; + output[11] = cells[15]; + output[15] = cells[3]; + + return mergeCellsIntoBlock(output); + } + + /** + * Applies the Rijndael MixColumns to the input and returns the result. + * + * @param ciphertext + */ + public static BigInteger mixColumns(BigInteger ciphertext) { + + int[] cells = splitBlockIntoCells(ciphertext); + int[] outputCells = new int[16]; + + for (int i = 0; i < 4; i++) { + int[] row = {cells[i * 4], cells[i * 4 + 1], cells[i * 4 + 2], cells[i * 4 + 3]}; + + outputCells[i * 4] = MULT2[row[0]] ^ MULT3[row[1]] ^ row[2] ^ row[3]; + outputCells[i * 4 + 1] = row[0] ^ MULT2[row[1]] ^ MULT3[row[2]] ^ row[3]; + outputCells[i * 4 + 2] = row[0] ^ row[1] ^ MULT2[row[2]] ^ MULT3[row[3]]; + outputCells[i * 4 + 3] = MULT3[row[0]] ^ row[1] ^ row[2] ^ MULT2[row[3]]; + } + return mergeCellsIntoBlock(outputCells); + } + + /** + * Applies the inverse Rijndael MixColumns for decryption to the input and returns the result. + * + * @param ciphertext + */ + public static BigInteger mixColumnsDec(BigInteger ciphertext) { + + int[] cells = splitBlockIntoCells(ciphertext); + int[] outputCells = new int[16]; + + for (int i = 0; i < 4; i++) { + int[] row = {cells[i * 4], cells[i * 4 + 1], cells[i * 4 + 2], cells[i * 4 + 3]}; + + outputCells[i * 4] = MULT14[row[0]] ^ MULT11[row[1]] ^ MULT13[row[2]] ^ MULT9[row[3]]; + outputCells[i * 4 + 1] = MULT9[row[0]] ^ MULT14[row[1]] ^ MULT11[row[2]] ^ MULT13[row[3]]; + outputCells[i * 4 + 2] = MULT13[row[0]] ^ MULT9[row[1]] ^ MULT14[row[2]] ^ MULT11[row[3]]; + outputCells[i * 4 + 3] = MULT11[row[0]] ^ MULT13[row[1]] ^ MULT9[row[2]] ^ MULT14[row[3]]; + } + return mergeCellsIntoBlock(outputCells); + } + + /** + * Encrypts the plaintext with the key and returns the result + * + * @param plainText which we want to encrypt + * @param key the key for encrypt + * @return EncryptedText + */ + public static BigInteger encrypt(BigInteger plainText, BigInteger key) { + BigInteger[] roundKeys = keyExpansion(key); + + // Initial round + plainText = addRoundKey(plainText, roundKeys[0]); + + // Main rounds + for (int i = 1; i < 10; i++) { + plainText = subBytes(plainText); + plainText = shiftRows(plainText); + plainText = mixColumns(plainText); + plainText = addRoundKey(plainText, roundKeys[i]); + } + + // Final round + plainText = subBytes(plainText); + plainText = shiftRows(plainText); + plainText = addRoundKey(plainText, roundKeys[10]); + + return plainText; + } + + /** + * Decrypts the ciphertext with the key and returns the result + * + * @param cipherText The Encrypted text which we want to decrypt + * @param key + * @return decryptedText + */ + public static BigInteger decrypt(BigInteger cipherText, BigInteger key) { + + BigInteger[] roundKeys = keyExpansion(key); + + // Invert final round + cipherText = addRoundKey(cipherText, roundKeys[10]); + cipherText = shiftRowsDec(cipherText); + cipherText = subBytesDec(cipherText); + + // Invert main rounds + for (int i = 9; i > 0; i--) { + cipherText = addRoundKey(cipherText, roundKeys[i]); + cipherText = mixColumnsDec(cipherText); + cipherText = shiftRowsDec(cipherText); + cipherText = subBytesDec(cipherText); + } + + // Invert initial round + cipherText = addRoundKey(cipherText, roundKeys[0]); + + return cipherText; + } + + public static void main(String[] args) { + + try (Scanner input = new Scanner(System.in)) { + System.out.println("Enter (e) letter for encrpyt or (d) letter for decrypt :"); + char choice = input.nextLine().charAt(0); + String in; + switch (choice) { + case 'E': + case 'e': + System.out.println("Choose a plaintext block (128-Bit Integer in base 16):"); + in = input.nextLine(); + BigInteger plaintext = new BigInteger(in, 16); + System.out.println("Choose a Key (128-Bit Integer in base 16):"); + in = input.nextLine(); + BigInteger encryptionKey = new BigInteger(in, 16); + System.out.println( + "The encrypted message is: \n" + encrypt(plaintext, encryptionKey).toString(16)); + break; + case 'D': + case 'd': + System.out.println("Enter your ciphertext block (128-Bit Integer in base 16):"); + in = input.nextLine(); + BigInteger ciphertext = new BigInteger(in, 16); + System.out.println("Choose a Key (128-Bit Integer in base 16):"); + in = input.nextLine(); + BigInteger decryptionKey = new BigInteger(in, 16); + System.out.println( + "The deciphered message is:\n" + decrypt(ciphertext, decryptionKey).toString(16)); + break; + default: + System.out.println("** End **"); + } + } + } } diff --git a/ciphers/AESEncryption.java b/ciphers/AESEncryption.java index 884109f9bdb7..12e5824de7d1 100644 --- a/ciphers/AESEncryption.java +++ b/ciphers/AESEncryption.java @@ -10,116 +10,101 @@ import javax.crypto.SecretKey; /** - * This example program shows how AES encryption and decryption can be done in - * Java. Please note that secret key and encrypted text is unreadable binary and - * hence in the following program we display it in hexadecimal format of the - * underlying bytes. - * + * This example program shows how AES encryption and decryption can be done in Java. Please note + * that secret key and encrypted text is unreadable binary and hence in the following program we + * display it in hexadecimal format of the underlying bytes. */ public class AESEncryption { + private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray(); + /** + * 1. Generate a plain text for encryption 2. Get a secret key (printed in hexadecimal form). In + * actual use this must by encrypted and kept safe. The same key is required for decryption. + */ + public static void main(String[] args) throws Exception { + String plainText = "Hello World"; + SecretKey secKey = getSecretEncryptionKey(); + byte[] cipherText = encryptText(plainText, secKey); + String decryptedText = decryptText(cipherText, secKey); - private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray(); - /** - * 1. Generate a plain text for encryption 2. Get a secret key (printed in - * hexadecimal form). In actual use this must by encrypted and kept safe. The - * same key is required for decryption. - * - */ - public static void main(String[] args) throws Exception { - String plainText = "Hello World"; - SecretKey secKey = getSecretEncryptionKey(); - byte[] cipherText = encryptText(plainText, secKey); - String decryptedText = decryptText(cipherText, secKey); + System.out.println("Original Text:" + plainText); + System.out.println("AES Key (Hex Form):" + bytesToHex(secKey.getEncoded())); + System.out.println("Encrypted Text (Hex Form):" + bytesToHex(cipherText)); + System.out.println("Descrypted Text:" + decryptedText); + } - System.out.println("Original Text:" + plainText); - System.out.println("AES Key (Hex Form):" + bytesToHex(secKey.getEncoded())); - System.out.println("Encrypted Text (Hex Form):" + bytesToHex(cipherText)); - System.out.println("Descrypted Text:" + decryptedText); + /** + * gets the AES encryption key. In your actual programs, this should be safely stored. + * + * @return secKey (Secret key that we encrypt using it) + * @throws NoSuchAlgorithmException (from KeyGenrator) + */ + public static SecretKey getSecretEncryptionKey() throws NoSuchAlgorithmException { + KeyGenerator aesKeyGenerator = KeyGenerator.getInstance("AES"); + aesKeyGenerator.init(128); // The AES key size in number of bits + SecretKey secKey = aesKeyGenerator.generateKey(); + return secKey; + } - } + /** + * Encrypts plainText in AES using the secret key + * + * @param plainText + * @param secKey + * @return byteCipherText (The encrypted text) + * @throws NoSuchPaddingException (from Cipher) + * @throws NoSuchAlgorithmException (from Cipher) + * @throws InvalidKeyException (from Cipher) + * @throws BadPaddingException (from Cipher) + * @throws IllegalBlockSizeException (from Cipher) + */ + public static byte[] encryptText(String plainText, SecretKey secKey) + throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, + IllegalBlockSizeException, BadPaddingException { + // AES defaults to AES/ECB/PKCS5Padding in Java 7 + Cipher aesCipher = Cipher.getInstance("AES"); + aesCipher.init(Cipher.ENCRYPT_MODE, secKey); + byte[] byteCipherText = aesCipher.doFinal(plainText.getBytes()); + return byteCipherText; + } - /** - * gets the AES encryption key. In your actual programs, this should be safely - * stored. - * - * @return secKey (Secret key that we encrypt using it) - * @throws NoSuchAlgorithmException - * (from KeyGenrator) - * - */ - public static SecretKey getSecretEncryptionKey() throws NoSuchAlgorithmException { - KeyGenerator aesKeyGenerator = KeyGenerator.getInstance("AES"); - aesKeyGenerator.init(128); // The AES key size in number of bits - SecretKey secKey = aesKeyGenerator.generateKey(); - return secKey; - } + /** + * Decrypts encrypted byte array using the key used for encryption. + * + * @param byteCipherText + * @param secKey + * @return plainText + * @throws NoSuchPaddingException + * @throws NoSuchAlgorithmException + * @throws InvalidKeyException + * @throws BadPaddingException + * @throws IllegalBlockSizeException + */ + public static String decryptText(byte[] byteCipherText, SecretKey secKey) + throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, + IllegalBlockSizeException, BadPaddingException { + // AES defaults to AES/ECB/PKCS5Padding in Java 7 + Cipher aesCipher = Cipher.getInstance("AES"); + aesCipher.init(Cipher.DECRYPT_MODE, secKey); + byte[] bytePlainText = aesCipher.doFinal(byteCipherText); + return new String(bytePlainText); + } - /** - * Encrypts plainText in AES using the secret key - * - * @param plainText - * @param secKey - * @return byteCipherText (The encrypted text) - * @throws NoSuchPaddingException - * (from Cipher) - * @throws NoSuchAlgorithmException - * (from Cipher) - * @throws InvalidKeyException - * (from Cipher) - * @throws BadPaddingException - * (from Cipher) - * @throws IllegalBlockSizeException - * (from Cipher) - */ - public static byte[] encryptText(String plainText, SecretKey secKey) throws NoSuchAlgorithmException, - NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { - // AES defaults to AES/ECB/PKCS5Padding in Java 7 - Cipher aesCipher = Cipher.getInstance("AES"); - aesCipher.init(Cipher.ENCRYPT_MODE, secKey); - byte[] byteCipherText = aesCipher.doFinal(plainText.getBytes()); - return byteCipherText; - } - - /** - * Decrypts encrypted byte array using the key used for encryption. - * - * @param byteCipherText - * @param secKey - * @return plainText - * @throws NoSuchPaddingException - * @throws NoSuchAlgorithmException - * @throws InvalidKeyException - * @throws BadPaddingException - * @throws IllegalBlockSizeException - */ - public static String decryptText(byte[] byteCipherText, SecretKey secKey) throws NoSuchAlgorithmException, - NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { - // AES defaults to AES/ECB/PKCS5Padding in Java 7 - Cipher aesCipher = Cipher.getInstance("AES"); - aesCipher.init(Cipher.DECRYPT_MODE, secKey); - byte[] bytePlainText = aesCipher.doFinal(byteCipherText); - return new String(bytePlainText); - } - - /** - * Convert a binary byte array into readable hex form - * Old library is deprecated on OpenJdk 11 and - * this is faster regarding other solution is using StringBuilder - * Credit - * {@link - * https://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to-a-hex-string-in-java/9855338#9855338} - * @param hash - * (in binary) - * @return hexHash - */ - public static String bytesToHex(byte[] bytes) { - char[] hexChars = new char[bytes.length * 2]; - for (int j = 0; j < bytes.length; j++) { - int v = bytes[j] & 0xFF; - hexChars[j * 2] = HEX_ARRAY[v >>> 4]; - hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F]; - } - return new String(hexChars); - } + /** + * Convert a binary byte array into readable hex form Old library is deprecated on OpenJdk 11 and + * this is faster regarding other solution is using StringBuilder Credit {@link + * https://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to-a-hex-string-in-java/9855338#9855338} + * + * @param hash (in binary) + * @return hexHash + */ + public static String bytesToHex(byte[] bytes) { + char[] hexChars = new char[bytes.length * 2]; + for (int j = 0; j < bytes.length; j++) { + int v = bytes[j] & 0xFF; + hexChars[j * 2] = HEX_ARRAY[v >>> 4]; + hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F]; + } + return new String(hexChars); + } } diff --git a/ciphers/Caesar.java b/ciphers/Caesar.java index d9028613bce8..ff7f4482be1e 100644 --- a/ciphers/Caesar.java +++ b/ciphers/Caesar.java @@ -3,128 +3,119 @@ import java.util.Scanner; /** - * - * A Java implementation of Caesar Cipher. /It is a type of substitution cipher - * in which each letter in the plaintext is replaced by a letter some fixed - * number of positions down the alphabet. / + * A Java implementation of Caesar Cipher. /It is a type of substitution cipher in which each letter + * in the plaintext is replaced by a letter some fixed number of positions down the alphabet. / * * @author FAHRI YARDIMCI * @author khalil2535 */ public class Caesar { - /** - * Encrypt text by shifting every Latin char by add number shift for ASCII - * Example : A + 1 -> B - * - * @param message - * @param shift - * @return Encrypted message - */ - public static String encode(String message, int shift) { - String encoded = ""; + /** + * Encrypt text by shifting every Latin char by add number shift for ASCII Example : A + 1 -> B + * + * @param message + * @param shift + * @return Encrypted message + */ + public static String encode(String message, int shift) { + String encoded = ""; - - shift %= 26; - + shift %= 26; - final int length = message.length(); - for (int i = 0; i < length; i++) { + final int length = message.length(); + for (int i = 0; i < length; i++) { -// int current = message.charAt(i); //using char to shift characters because ascii is in-order latin alphabet - char current = message.charAt(i); // Java law : char + int = char + // int current = message.charAt(i); //using char to shift characters because ascii + // is in-order latin alphabet + char current = message.charAt(i); // Java law : char + int = char - if (IsCapitalLatinLetter(current)) { + if (IsCapitalLatinLetter(current)) { - current += shift; - encoded += (char) (current > 'Z' ? current - 26 : current); // 26 = number of latin letters + current += shift; + encoded += (char) (current > 'Z' ? current - 26 : current); // 26 = number of latin letters - } else if (IsSmallLatinLetter(current)) { + } else if (IsSmallLatinLetter(current)) { - current += shift; - encoded += (char) (current > 'z' ? current - 26 : current); // 26 = number of latin letters + current += shift; + encoded += (char) (current > 'z' ? current - 26 : current); // 26 = number of latin letters - } else { - encoded += current; - } - } - return encoded; + } else { + encoded += current; + } } + return encoded; + } - /** - * Decrypt message by shifting back every Latin char to previous the ASCII - * Example : B - 1 -> A - * - * @param encryptedMessage - * @param shift - * @return message - */ - public static String decode(String encryptedMessage, int shift) { - String decoded = ""; - - - shift %= 26; - - - final int length = encryptedMessage.length(); - for (int i = 0; i < length; i++) { - char current = encryptedMessage.charAt(i); - if (IsCapitalLatinLetter(current)) { - - current -= shift; - decoded += (char) (current < 'A' ? current + 26 : current);// 26 = number of latin letters - - } else if (IsSmallLatinLetter(current)) { - - current -= shift; - decoded += (char) (current < 'a' ? current + 26 : current);// 26 = number of latin letters - - } else { - decoded += current; - } - } - return decoded; - } + /** + * Decrypt message by shifting back every Latin char to previous the ASCII Example : B - 1 -> A + * + * @param encryptedMessage + * @param shift + * @return message + */ + public static String decode(String encryptedMessage, int shift) { + String decoded = ""; - /** - * - * @param c - * @return true if character is capital Latin letter or false for others - */ - private static boolean IsCapitalLatinLetter(char c) { - return c >= 'A' && c <= 'Z'; - } + shift %= 26; - /** - * - * @param c - * @return true if character is small Latin letter or false for others - */ - private static boolean IsSmallLatinLetter(char c) { - return c >= 'a' && c <= 'z'; - } + final int length = encryptedMessage.length(); + for (int i = 0; i < length; i++) { + char current = encryptedMessage.charAt(i); + if (IsCapitalLatinLetter(current)) { - public static void main(String[] args) { - Scanner input = new Scanner(System.in); - System.out.println("Please enter the message (Latin Alphabet)"); - String message = input.nextLine(); - System.out.println(message); - System.out.println("Please enter the shift number"); - int shift = input.nextInt() % 26; - System.out.println("(E)ncode or (D)ecode ?"); - char choice = input.next().charAt(0); - switch (choice) { - case 'E': - case 'e': - System.out.println("ENCODED MESSAGE IS \n" + encode(message, shift)); //send our function to handle - break; - case 'D': - case 'd': - System.out.println("DECODED MESSAGE IS \n" + decode(message, shift)); - default: - System.out.println("default case"); - } - input.close(); - } + current -= shift; + decoded += (char) (current < 'A' ? current + 26 : current); // 26 = number of latin letters + } else if (IsSmallLatinLetter(current)) { + + current -= shift; + decoded += (char) (current < 'a' ? current + 26 : current); // 26 = number of latin letters + + } else { + decoded += current; + } + } + return decoded; + } + + /** + * @param c + * @return true if character is capital Latin letter or false for others + */ + private static boolean IsCapitalLatinLetter(char c) { + return c >= 'A' && c <= 'Z'; + } + + /** + * @param c + * @return true if character is small Latin letter or false for others + */ + private static boolean IsSmallLatinLetter(char c) { + return c >= 'a' && c <= 'z'; + } + + public static void main(String[] args) { + Scanner input = new Scanner(System.in); + System.out.println("Please enter the message (Latin Alphabet)"); + String message = input.nextLine(); + System.out.println(message); + System.out.println("Please enter the shift number"); + int shift = input.nextInt() % 26; + System.out.println("(E)ncode or (D)ecode ?"); + char choice = input.next().charAt(0); + switch (choice) { + case 'E': + case 'e': + System.out.println( + "ENCODED MESSAGE IS \n" + encode(message, shift)); // send our function to handle + break; + case 'D': + case 'd': + System.out.println("DECODED MESSAGE IS \n" + decode(message, shift)); + default: + System.out.println("default case"); + } + input.close(); + } } diff --git a/ciphers/ColumnarTranspositionCipher.java b/ciphers/ColumnarTranspositionCipher.java index 60af4ff5429c..9947d781c257 100644 --- a/ciphers/ColumnarTranspositionCipher.java +++ b/ciphers/ColumnarTranspositionCipher.java @@ -7,218 +7,204 @@ */ public class ColumnarTranspositionCipher { - private static String keyword; - private static Object[][] table; - private static String abecedarium; - public static final String ABECEDARIUM = "abcdefghijklmnopqrstuvwxyzABCDEFG" - + "HIJKLMNOPQRSTUVWXYZ0123456789,.;:-@"; - private static final String ENCRYPTION_FIELD = "≈"; - private static final char ENCRYPTION_FIELD_CHAR = '≈'; + private static String keyword; + private static Object[][] table; + private static String abecedarium; + public static final String ABECEDARIUM = + "abcdefghijklmnopqrstuvwxyzABCDEFG" + "HIJKLMNOPQRSTUVWXYZ0123456789,.;:-@"; + 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; i < sortedTable[i].length; i++) { - for (int j = 1; j < sortedTable.length; j++) { - wordEncrypted += sortedTable[j][i]; - } - } - return wordEncrypted; + /** + * 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; i < sortedTable[i].length; i++) { + for (int j = 1; j < sortedTable.length; j++) { + wordEncrypted += sortedTable[j][i]; + } } + return wordEncrypted; + } - /** - * Encrypts a certain String with the Columnar Transposition Cipher Rule - * - * @param word Word being encrypted - * @param keyword String with keyword being used - * @param abecedarium String with the abecedarium being used. null for - * default one - * @return a String with the word encrypted by the Columnar Transposition - * Cipher Rule - */ - public static String encrpyter(String word, String keyword, - String abecedarium) { - ColumnarTranspositionCipher.keyword = keyword; - if (abecedarium != null) { - ColumnarTranspositionCipher.abecedarium = abecedarium; - } else { - ColumnarTranspositionCipher.abecedarium = ABECEDARIUM; - } - table = tableBuilder(word); - Object[][] sortedTable = sortTable(table); - String wordEncrypted = ""; - for (int i = 0; i < sortedTable[0].length; i++) { - for (int j = 1; j < sortedTable.length; j++) { - wordEncrypted += sortedTable[j][i]; - } - } - return wordEncrypted; + /** + * Encrypts a certain String with the Columnar Transposition Cipher Rule + * + * @param word Word being encrypted + * @param keyword String with keyword being used + * @param abecedarium String with the abecedarium being used. null for default one + * @return a String with the word encrypted by the Columnar Transposition Cipher Rule + */ + public static String encrpyter(String word, String keyword, String abecedarium) { + ColumnarTranspositionCipher.keyword = keyword; + if (abecedarium != null) { + ColumnarTranspositionCipher.abecedarium = abecedarium; + } else { + ColumnarTranspositionCipher.abecedarium = ABECEDARIUM; } - - /** - * Decrypts a certain encrypted String with the Columnar Transposition - * Cipher Rule - * - * @return a String decrypted with the word encrypted by the Columnar - * Transposition Cipher Rule - */ - public static String decrypter() { - String wordDecrypted = ""; - for (int i = 1; i < table.length; i++) { - for (Object item : table[i]) { - wordDecrypted += item; - } - } - return wordDecrypted.replaceAll(ENCRYPTION_FIELD, ""); + table = tableBuilder(word); + Object[][] sortedTable = sortTable(table); + String wordEncrypted = ""; + for (int i = 0; i < sortedTable[0].length; i++) { + for (int j = 1; j < sortedTable.length; j++) { + wordEncrypted += sortedTable[j][i]; + } } + return wordEncrypted; + } - /** - * Builds a table with the word to be encrypted in rows by the Columnar - * Transposition Cipher Rule - * - * @return An Object[][] with the word to be encrypted filled in rows and - * columns - */ - private static Object[][] tableBuilder(String word) { - Object[][] table = new Object[numberOfRows(word) + 1][keyword.length()]; - char[] wordInChards = word.toCharArray(); - //Fils in the respective numbers - table[0] = findElements(); - int charElement = 0; - for (int i = 1; i < table.length; i++) { - for (int j = 0; j < table[i].length; j++) { - if (charElement < wordInChards.length) { - table[i][j] = wordInChards[charElement]; - charElement++; - } else { - table[i][j] = ENCRYPTION_FIELD_CHAR; - } - } - } - return table; + /** + * Decrypts a certain encrypted String with the Columnar Transposition Cipher Rule + * + * @return a String decrypted with the word encrypted by the Columnar Transposition Cipher Rule + */ + public static String decrypter() { + String wordDecrypted = ""; + for (int i = 1; i < table.length; i++) { + for (Object item : table[i]) { + wordDecrypted += item; + } } + return wordDecrypted.replaceAll(ENCRYPTION_FIELD, ""); + } - /** - * Determines the number of rows the table should have regarding the - * Columnar Transposition Cipher Rule - * - * @return an int with the number of rows that the table should have in - * order to respect the Columnar Transposition Cipher Rule. - */ - private static int numberOfRows(String word) { - if (word.length() / keyword.length() > word.length() / keyword.length()) { - return (word.length() / keyword.length()) + 1; + /** + * Builds a table with the word to be encrypted in rows by the Columnar Transposition Cipher Rule + * + * @return An Object[][] with the word to be encrypted filled in rows and columns + */ + private static Object[][] tableBuilder(String word) { + Object[][] table = new Object[numberOfRows(word) + 1][keyword.length()]; + char[] wordInChards = word.toCharArray(); + // Fils in the respective numbers + table[0] = findElements(); + int charElement = 0; + for (int i = 1; i < table.length; i++) { + for (int j = 0; j < table[i].length; j++) { + if (charElement < wordInChards.length) { + table[i][j] = wordInChards[charElement]; + charElement++; } else { - return word.length() / keyword.length(); + table[i][j] = ENCRYPTION_FIELD_CHAR; } + } } + return table; + } - /** - * - * @return charValues - */ - private static Object[] findElements() { - Object[] charValues = new Object[keyword.length()]; - for (int i = 0; i < charValues.length; i++) { - int charValueIndex = abecedarium.indexOf(keyword.charAt(i)); - charValues[i] = charValueIndex > -1 ? charValueIndex : null; - } - return charValues; + /** + * Determines the number of rows the table should have regarding the Columnar Transposition Cipher + * Rule + * + * @return an int with the number of rows that the table should have in order to respect the + * Columnar Transposition Cipher Rule. + */ + private static int numberOfRows(String word) { + if (word.length() / keyword.length() > word.length() / keyword.length()) { + return (word.length() / keyword.length()) + 1; + } else { + return word.length() / keyword.length(); } + } - /** - * - * @param table - * @return tableSorted - */ - private static Object[][] sortTable(Object[][] table) { - Object[][] tableSorted = new Object[table.length][table[0].length]; - for (int i = 0; i < tableSorted.length; i++) { - System.arraycopy(table[i], 0, tableSorted[i], 0, tableSorted[i].length); - } - for (int i = 0; i < tableSorted[0].length; i++) { - for (int j = i + 1; j < tableSorted[0].length; j++) { - if ((int) tableSorted[0][i] > (int) table[0][j]) { - Object[] column = getColumn(tableSorted, tableSorted.length, i); - switchColumns(tableSorted, j, i, column); - } - } - } - return tableSorted; + /** @return charValues */ + private static Object[] findElements() { + Object[] charValues = new Object[keyword.length()]; + for (int i = 0; i < charValues.length; i++) { + int charValueIndex = abecedarium.indexOf(keyword.charAt(i)); + charValues[i] = charValueIndex > -1 ? charValueIndex : null; } + return charValues; + } - /** - * - * @param table - * @param rows - * @param column - * @return columnArray - */ - private static Object[] getColumn(Object[][] table, int rows, int column) { - Object[] columnArray = new Object[rows]; - for (int i = 0; i < rows; i++) { - columnArray[i] = table[i][column]; + /** + * @param table + * @return tableSorted + */ + private static Object[][] sortTable(Object[][] table) { + Object[][] tableSorted = new Object[table.length][table[0].length]; + for (int i = 0; i < tableSorted.length; i++) { + System.arraycopy(table[i], 0, tableSorted[i], 0, tableSorted[i].length); + } + for (int i = 0; i < tableSorted[0].length; i++) { + for (int j = i + 1; j < tableSorted[0].length; j++) { + if ((int) tableSorted[0][i] > (int) table[0][j]) { + Object[] column = getColumn(tableSorted, tableSorted.length, i); + switchColumns(tableSorted, j, i, column); } - return columnArray; + } } + return tableSorted; + } - /** - * - * @param table - * @param firstColumnIndex - * @param secondColumnIndex - * @param columnToSwitch - */ - private static void switchColumns(Object[][] table, int firstColumnIndex, - int secondColumnIndex, Object[] columnToSwitch) { - for (int i = 0; i < table.length; i++) { - table[i][secondColumnIndex] = table[i][firstColumnIndex]; - table[i][firstColumnIndex] = columnToSwitch[i]; - } + /** + * @param table + * @param rows + * @param column + * @return columnArray + */ + private static Object[] getColumn(Object[][] table, int rows, int column) { + Object[] columnArray = new Object[rows]; + for (int i = 0; i < rows; i++) { + columnArray[i] = table[i][column]; } + return columnArray; + } - /** - * Creates an abecedarium with a specified ascii inded - * - * @param value Number of characters being used based on the ASCII Table - */ - private static void abecedariumBuilder(int value) { - abecedarium = ""; - for (int i = 0; i < value; i++) { - abecedarium += (char) i; - } + /** + * @param table + * @param firstColumnIndex + * @param secondColumnIndex + * @param columnToSwitch + */ + private static void switchColumns( + Object[][] table, int firstColumnIndex, int secondColumnIndex, Object[] columnToSwitch) { + for (int i = 0; i < table.length; i++) { + table[i][secondColumnIndex] = table[i][firstColumnIndex]; + table[i][firstColumnIndex] = columnToSwitch[i]; } + } - private static void showTable() { - for (Object[] table1 : table) { - for (Object item : table1) { - System.out.print(item + " "); - } - System.out.println(); - } + /** + * Creates an abecedarium with a specified ascii inded + * + * @param value Number of characters being used based on the ASCII Table + */ + private static void abecedariumBuilder(int value) { + abecedarium = ""; + for (int i = 0; i < value; i++) { + abecedarium += (char) i; } + } - public static void main(String[] args) { - String keywordForExample = "asd215"; - String wordBeingEncrypted = "This is a test of the Columnar Transposition Cipher"; - System.out.println("### Example of Columnar Transposition Cipher ###\n"); - System.out.println("Word being encryped ->>> " + wordBeingEncrypted); - System.out.println("Word encrypted ->>> " + ColumnarTranspositionCipher - .encrpyter(wordBeingEncrypted, keywordForExample)); - System.out.println("Word decryped ->>> " + ColumnarTranspositionCipher - .decrypter()); - System.out.println("\n### Encrypted Table ###"); - showTable(); + private static void showTable() { + for (Object[] table1 : table) { + for (Object item : table1) { + System.out.print(item + " "); + } + System.out.println(); } + } + + public static void main(String[] args) { + String keywordForExample = "asd215"; + String wordBeingEncrypted = "This is a test of the Columnar Transposition Cipher"; + System.out.println("### Example of Columnar Transposition Cipher ###\n"); + System.out.println("Word being encryped ->>> " + wordBeingEncrypted); + System.out.println( + "Word encrypted ->>> " + + ColumnarTranspositionCipher.encrpyter(wordBeingEncrypted, keywordForExample)); + System.out.println("Word decryped ->>> " + ColumnarTranspositionCipher.decrypter()); + System.out.println("\n### Encrypted Table ###"); + showTable(); + } } diff --git a/ciphers/RSA.java b/ciphers/RSA.java index 751475168a4f..0778f48ccf4b 100644 --- a/ciphers/RSA.java +++ b/ciphers/RSA.java @@ -4,88 +4,78 @@ import java.security.SecureRandom; import javax.swing.JOptionPane; -/** - * @author Nguyen Duy Tiep on 23-Oct-17. - */ +/** @author Nguyen Duy Tiep on 23-Oct-17. */ public final class RSA { - public static void main(String[] args) { - - RSA rsa = new RSA(1024); - String text1 = JOptionPane.showInputDialog("Enter a message to encrypt :"); - - String ciphertext = rsa.encrypt(text1); - JOptionPane.showMessageDialog(null, "Your encrypted message : " + ciphertext); - - JOptionPane.showMessageDialog(null, "Your message after decrypt : " + rsa.decrypt(ciphertext)); - } - - private BigInteger modulus, privateKey, publicKey; - - /** - * - * @param bits - */ - public RSA(int bits) { - generateKeys(bits); - } - - /** - * - * @param message - * @return encrypted message - */ - public synchronized String encrypt(String message) { - return (new BigInteger(message.getBytes())).modPow(publicKey, modulus).toString(); - } - - /** - * - * @param message - * @return encrypted message as big integer - */ - public synchronized BigInteger encrypt(BigInteger message) { - return message.modPow(publicKey, modulus); - } - - /** - * - * @param encryptedMessage - * @return plain message - */ - public synchronized String decrypt(String encryptedMessage) { - return new String((new BigInteger(encryptedMessage)).modPow(privateKey, modulus).toByteArray()); - } - - /** - * - * @param encryptedMessage - * @return plain message as big integer - */ - public synchronized BigInteger decrypt(BigInteger encryptedMessage) { - return encryptedMessage.modPow(privateKey, modulus); - } - - /** - * Generate a new public and private key set. - * - * @param bits - */ - 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); + public static void main(String[] args) { + + RSA rsa = new RSA(1024); + String text1 = JOptionPane.showInputDialog("Enter a message to encrypt :"); + + String ciphertext = rsa.encrypt(text1); + JOptionPane.showMessageDialog(null, "Your encrypted message : " + ciphertext); + + JOptionPane.showMessageDialog(null, "Your message after decrypt : " + rsa.decrypt(ciphertext)); + } + + private BigInteger modulus, privateKey, publicKey; + + /** @param bits */ + public RSA(int bits) { + generateKeys(bits); + } + + /** + * @param message + * @return encrypted message + */ + public synchronized String encrypt(String message) { + return (new BigInteger(message.getBytes())).modPow(publicKey, modulus).toString(); + } + + /** + * @param message + * @return encrypted message as big integer + */ + public synchronized BigInteger encrypt(BigInteger message) { + return message.modPow(publicKey, modulus); + } + + /** + * @param encryptedMessage + * @return plain message + */ + public synchronized String decrypt(String encryptedMessage) { + return new String((new BigInteger(encryptedMessage)).modPow(privateKey, modulus).toByteArray()); + } + + /** + * @param encryptedMessage + * @return plain message as big integer + */ + public synchronized BigInteger decrypt(BigInteger encryptedMessage) { + return encryptedMessage.modPow(privateKey, modulus); + } + + /** + * Generate a new public and private key set. + * + * @param bits + */ + 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); + } } diff --git a/ciphers/SimpleSubstitutionCipher.java b/ciphers/SimpleSubstitutionCipher.java index d9bae4f072c8..1279c4949456 100644 --- a/ciphers/SimpleSubstitutionCipher.java +++ b/ciphers/SimpleSubstitutionCipher.java @@ -3,95 +3,85 @@ import java.util.*; /** + * The simple substitution cipher is a cipher that has been in use for many hundreds of years (an + * excellent history is given in Simon Singhs 'the Code Book'). It basically consists of + * substituting every plaintext character for a different ciphertext character. It differs from the + * Caesar cipher in that the cipher alphabet is not simply the alphabet shifted, it is completely + * jumbled. * - * The simple substitution cipher is a cipher that has been in use for many hundreds of years - * (an excellent history is given in Simon Singhs 'the Code Book'). - * It basically consists of substituting every plaintext character for a different ciphertext character. - * It differs from the Caesar cipher in that the cipher alphabet is not simply the alphabet shifted, - * it is completely jumbled. - * * @author Hassan Elseoudy */ - public class SimpleSubstitutionCipher { - /** - * Encrypt text by replacing each element with its opposite character. - * - * @param message - * @param cipherSmall - * @return Encrypted message - */ - public static String encode(String message, String cipherSmall) { - String encoded = ""; - - // This map is used to encode - Map cipherMap = new HashMap(); - - char beginSmallLetter = 'a'; - char beginCapitalLetter = 'A'; - - cipherSmall = cipherSmall.toLowerCase(); - String cipherCapital = cipherSmall.toUpperCase(); - - // To handle Small and Capital letters - for(int i = 0; i < cipherSmall.length(); i++){ - cipherMap.put(beginSmallLetter++,cipherSmall.charAt(i)); - cipherMap.put(beginCapitalLetter++,cipherCapital.charAt(i)); - } - - for(int i = 0; i < message.length(); i++){ - if(Character.isAlphabetic(message.charAt(i))) - encoded += cipherMap.get(message.charAt(i)); - else - encoded += message.charAt(i); - } - - return encoded; + /** + * Encrypt text by replacing each element with its opposite character. + * + * @param message + * @param cipherSmall + * @return Encrypted message + */ + public static String encode(String message, String cipherSmall) { + String encoded = ""; + + // This map is used to encode + Map cipherMap = new HashMap(); + + char beginSmallLetter = 'a'; + char beginCapitalLetter = 'A'; + + cipherSmall = cipherSmall.toLowerCase(); + String cipherCapital = cipherSmall.toUpperCase(); + + // To handle Small and Capital letters + for (int i = 0; i < cipherSmall.length(); i++) { + cipherMap.put(beginSmallLetter++, cipherSmall.charAt(i)); + cipherMap.put(beginCapitalLetter++, cipherCapital.charAt(i)); } - /** - * Decrypt message by replacing each element with its opposite character in cipher. - * - * @param encryptedMessage - * @param cipherSmall - * @return message - */ - public static String decode(String encryptedMessage, String cipherSmall) { - String decoded = ""; - + for (int i = 0; i < message.length(); i++) { + if (Character.isAlphabetic(message.charAt(i))) encoded += cipherMap.get(message.charAt(i)); + else encoded += message.charAt(i); + } - Map cipherMap = new HashMap(); + return encoded; + } - char beginSmallLetter = 'a'; - char beginCapitalLetter = 'A'; + /** + * Decrypt message by replacing each element with its opposite character in cipher. + * + * @param encryptedMessage + * @param cipherSmall + * @return message + */ + public static String decode(String encryptedMessage, String cipherSmall) { + String decoded = ""; - cipherSmall = cipherSmall.toLowerCase(); - String cipherCapital = cipherSmall.toUpperCase(); + Map cipherMap = new HashMap(); - for(int i = 0; i < cipherSmall.length(); i++){ - cipherMap.put(cipherSmall.charAt(i),beginSmallLetter++); - cipherMap.put(cipherCapital.charAt(i),beginCapitalLetter++); - } + char beginSmallLetter = 'a'; + char beginCapitalLetter = 'A'; - for(int i = 0; i < encryptedMessage.length(); i++){ - if(Character.isAlphabetic(encryptedMessage.charAt(i))) - decoded += cipherMap.get(encryptedMessage.charAt(i)); - else - decoded += encryptedMessage.charAt(i); - } + cipherSmall = cipherSmall.toLowerCase(); + String cipherCapital = cipherSmall.toUpperCase(); - return decoded; + for (int i = 0; i < cipherSmall.length(); i++) { + cipherMap.put(cipherSmall.charAt(i), beginSmallLetter++); + cipherMap.put(cipherCapital.charAt(i), beginCapitalLetter++); } - /** - * - * TODO remove main and make JUnit Testing - */ - public static void main(String[] args) { - String a = encode("defend the east wall of the castle","phqgiumeaylnofdxjkrcvstzwb"); - String b = decode(a,"phqgiumeaylnofdxjkrcvstzwb"); - System.out.println(b); + for (int i = 0; i < encryptedMessage.length(); i++) { + if (Character.isAlphabetic(encryptedMessage.charAt(i))) + decoded += cipherMap.get(encryptedMessage.charAt(i)); + else decoded += encryptedMessage.charAt(i); } + return decoded; + } + + /** TODO remove main and make JUnit Testing */ + public static void main(String[] args) { + String a = encode("defend the east wall of the castle", "phqgiumeaylnofdxjkrcvstzwb"); + String b = decode(a, "phqgiumeaylnofdxjkrcvstzwb"); + System.out.println(b); + } } diff --git a/ciphers/Vigenere.java b/ciphers/Vigenere.java index 48c54288dcf8..05d2952c313d 100644 --- a/ciphers/Vigenere.java +++ b/ciphers/Vigenere.java @@ -2,66 +2,60 @@ /** * A Java implementation of Vigenere Cipher. - * @author straiffix + * + * @author straiffix */ +public class Vigenere { + public static String encrypt(final String message, final String key) { -public class Vigenere { + String result = ""; - public static String encrypt(final String message, final String key) - { + for (int i = 0, j = 0; i < message.length(); i++) { + char c = message.charAt(i); + if (Character.isLetter(c)) { + if (Character.isUpperCase(c)) { + result += (char) ((c + key.toUpperCase().charAt(j) - 2 * 'A') % 26 + 'A'); - String result = ""; - - for (int i = 0, j = 0; i < message.length(); i++) { - char c = message.charAt(i); - if (Character.isLetter(c)){ - if(Character.isUpperCase(c)) { - result += (char) ((c + key.toUpperCase().charAt(j) - 2 * 'A') % 26 + 'A'); - - } else { - result += (char) ((c + key.toLowerCase().charAt(j) - 2 * 'a') % 26 + 'a'); - - } - } else { - result+=c; - } - j = ++j % key.length(); + } else { + result += (char) ((c + key.toLowerCase().charAt(j) - 2 * 'a') % 26 + 'a'); } - return result; + } else { + result += c; + } + j = ++j % key.length(); } + return result; + } - public static String decrypt( final String message, final String key) - { - String result =""; - - for(int i = 0, j = 0; i < message.length(); i++){ - - char c = message.charAt(i); - if (Character.isLetter(c)){ - if(Character.isUpperCase(c)) { - result += ((char)('Z'-(25-(c-key.toUpperCase().charAt(j)))%26)); - - } else { - result += ((char)('z'-(25-(c-key.toLowerCase().charAt(j)))%26)); + public static String decrypt(final String message, final String key) { + String result = ""; - } - } else { - result+=c; - } + for (int i = 0, j = 0; i < message.length(); i++) { - j = ++j % key.length(); + char c = message.charAt(i); + if (Character.isLetter(c)) { + if (Character.isUpperCase(c)) { + result += ((char) ('Z' - (25 - (c - key.toUpperCase().charAt(j))) % 26)); + } else { + result += ((char) ('z' - (25 - (c - key.toLowerCase().charAt(j))) % 26)); } - return result; - } - public static void main (String [] args){ - String text="Hello World!"; - String key="itsakey"; - System.out.println(text); - String ciphertext=encrypt(text, key); - System.out.println(ciphertext); - System.out.println(decrypt(ciphertext, key)); + } else { + result += c; + } + j = ++j % key.length(); } + return result; + } + + public static void main(String[] args) { + String text = "Hello World!"; + String key = "itsakey"; + System.out.println(text); + String ciphertext = encrypt(text, key); + System.out.println(ciphertext); + System.out.println(decrypt(ciphertext, key)); + } } diff --git a/divideconquer/ClosestPair.java b/divideconquer/ClosestPair.java index 3d717417a80c..1eeced4ee8db 100644 --- a/divideconquer/ClosestPair.java +++ b/divideconquer/ClosestPair.java @@ -1,378 +1,338 @@ package divideconquer; /** - * For a set of points in a coordinates system (10000 maximum), - * ClosestPair class calculates the two closest points. + * For a set of points in a coordinates system (10000 maximum), ClosestPair class calculates the two + * closest points. * * @author: anonymous * @author: Marisa Afuera */ - public final class ClosestPair { + /** Number of points */ + int numberPoints = 0; + /** Input data, maximum 10000. */ + private Location[] array; + /** Minimum point coordinate. */ + Location point1 = null; + /** Minimum point coordinate. */ + Location point2 = null; + /** Minimum point length. */ + private static double minNum = Double.MAX_VALUE; - /** - * Number of points - */ - int numberPoints = 0; - /** - * Input data, maximum 10000. - */ - private Location[] array; - /** - * Minimum point coordinate. - */ - Location point1 = null; - /** - * Minimum point coordinate. - */ - Location point2 = null; - /** - * Minimum point length. - */ - private static double minNum = Double.MAX_VALUE; - - public static void setMinNum(double minNum) { - ClosestPair.minNum = minNum; - } - - public static void setSecondCount(int secondCount) { - ClosestPair.secondCount = secondCount; - } - - /** - * secondCount - */ - private static int secondCount = 0; - - /** - * Constructor. - */ - ClosestPair(int points) { - numberPoints = points; - array = new Location[numberPoints]; - } - - /** - * Location class is an auxiliary type to keep points coordinates. - */ - - public static class Location { + public static void setMinNum(double minNum) { + ClosestPair.minNum = minNum; + } - double x = 0; - double y = 0; + public static void setSecondCount(int secondCount) { + ClosestPair.secondCount = secondCount; + } - /** - * @param xpar (IN Parameter) x coordinate
- * @param ypar (IN Parameter) y coordinate
- */ + /** secondCount */ + private static int secondCount = 0; - Location(final double xpar, final double ypar) { //Save x, y coordinates - this.x = xpar; - this.y = ypar; - } + /** Constructor. */ + ClosestPair(int points) { + numberPoints = points; + array = new Location[numberPoints]; + } - } - - public Location[] createLocation(int numberValues) { - return new Location[numberValues]; - - } - - public Location buildLocation(double x, double y) { - return new Location(x, y); - } + /** Location class is an auxiliary type to keep points coordinates. */ + public static class Location { + double x = 0; + double y = 0; /** - * xPartition function: arrange x-axis. - * - * @param a (IN Parameter) array of points
- * @param first (IN Parameter) first point
- * @param last (IN Parameter) last point
- * @return pivot index + * @param xpar (IN Parameter) x coordinate
+ * @param ypar (IN Parameter) y coordinate
*/ - - public int xPartition( - final Location[] a, final int first, final int last) { - - Location pivot = a[last]; // pivot - int i = first - 1; - Location temp; // Temporarily store value for position transformation - for (int j = first; j <= last - 1; j++) { - if (a[j].x <= pivot.x) { // Less than or less than pivot - i++; - temp = a[i]; // array[i] <-> array[j] - a[i] = a[j]; - a[j] = temp; - } - } + Location(final double xpar, final double ypar) { // Save x, y coordinates + this.x = xpar; + this.y = ypar; + } + } + + public Location[] createLocation(int numberValues) { + return new Location[numberValues]; + } + + public Location buildLocation(double x, double y) { + return new Location(x, y); + } + + /** + * xPartition function: arrange x-axis. + * + * @param a (IN Parameter) array of points
+ * @param first (IN Parameter) first point
+ * @param last (IN Parameter) last point
+ * @return pivot index + */ + public int xPartition(final Location[] a, final int first, final int last) { + + Location pivot = a[last]; // pivot + int i = first - 1; + Location temp; // Temporarily store value for position transformation + for (int j = first; j <= last - 1; j++) { + if (a[j].x <= pivot.x) { // Less than or less than pivot i++; - temp = a[i]; // array[pivot] <-> array[i] - a[i] = a[last]; - a[last] = temp; - return i; // pivot index + temp = a[i]; // array[i] <-> array[j] + a[i] = a[j]; + a[j] = temp; + } } - - /** - * yPartition function: arrange y-axis. - * - * @param a (IN Parameter) array of points
- * @param first (IN Parameter) first point
- * @param last (IN Parameter) last point
- * @return pivot index - */ - - public int yPartition( - final Location[] a, final int first, final int last) { - - Location pivot = a[last]; // pivot - int i = first - 1; - Location temp; // Temporarily store value for position transformation - for (int j = first; j <= last - 1; j++) { - if (a[j].y <= pivot.y) { // Less than or less than pivot - i++; - temp = a[i]; // array[i] <-> array[j] - a[i] = a[j]; - a[j] = temp; - } - } + i++; + temp = a[i]; // array[pivot] <-> array[i] + a[i] = a[last]; + a[last] = temp; + return i; // pivot index + } + + /** + * yPartition function: arrange y-axis. + * + * @param a (IN Parameter) array of points
+ * @param first (IN Parameter) first point
+ * @param last (IN Parameter) last point
+ * @return pivot index + */ + public int yPartition(final Location[] a, final int first, final int last) { + + Location pivot = a[last]; // pivot + int i = first - 1; + Location temp; // Temporarily store value for position transformation + for (int j = first; j <= last - 1; j++) { + if (a[j].y <= pivot.y) { // Less than or less than pivot i++; - temp = a[i]; // array[pivot] <-> array[i] - a[i] = a[last]; - a[last] = temp; - return i; // pivot index + temp = a[i]; // array[i] <-> array[j] + a[i] = a[j]; + a[j] = temp; + } } - - /** - * xQuickSort function: //x-axis Quick Sorting. - * - * @param a (IN Parameter) array of points
- * @param first (IN Parameter) first point
- * @param last (IN Parameter) last point
- */ - - public void xQuickSort( - final Location[] a, final int first, final int last) { - - if (first < last) { - int q = xPartition(a, first, last); // pivot - xQuickSort(a, first, q - 1); // Left - xQuickSort(a, q + 1, last); // Right - } + i++; + temp = a[i]; // array[pivot] <-> array[i] + a[i] = a[last]; + a[last] = temp; + return i; // pivot index + } + + /** + * xQuickSort function: //x-axis Quick Sorting. + * + * @param a (IN Parameter) array of points
+ * @param first (IN Parameter) first point
+ * @param last (IN Parameter) last point
+ */ + public void xQuickSort(final Location[] a, final int first, final int last) { + + if (first < last) { + int q = xPartition(a, first, last); // pivot + xQuickSort(a, first, q - 1); // Left + xQuickSort(a, q + 1, last); // Right } - - /** - * yQuickSort function: //y-axis Quick Sorting. - * - * @param a (IN Parameter) array of points
- * @param first (IN Parameter) first point
- * @param last (IN Parameter) last point
- */ - - public void yQuickSort( - final Location[] a, final int first, final int last) { - - if (first < last) { - int q = yPartition(a, first, last); // pivot - yQuickSort(a, first, q - 1); // Left - yQuickSort(a, q + 1, last); // Right - } + } + + /** + * yQuickSort function: //y-axis Quick Sorting. + * + * @param a (IN Parameter) array of points
+ * @param first (IN Parameter) first point
+ * @param last (IN Parameter) last point
+ */ + public void yQuickSort(final Location[] a, final int first, final int last) { + + if (first < last) { + int q = yPartition(a, first, last); // pivot + yQuickSort(a, first, q - 1); // Left + yQuickSort(a, q + 1, last); // Right } - - /** - * closestPair function: find closest pair. - * - * @param a (IN Parameter) array stored before divide
- * @param indexNum (IN Parameter) number coordinates divideArray
- * @return minimum distance
- */ - - public double closestPair(final Location[] a, final int indexNum) { - - Location[] divideArray = new Location[indexNum]; - System.arraycopy(a, 0, divideArray, 0, indexNum); // Copy previous array - int divideX = indexNum / 2; // Intermediate value for divide - Location[] leftArray = new Location[divideX]; //divide - left array - //divide-right array - Location[] rightArray = new Location[indexNum - divideX]; - if (indexNum <= 3) { // If the number of coordinates is 3 or less - return bruteForce(divideArray); - } - //divide-left array - System.arraycopy(divideArray, 0, leftArray, 0, divideX); - //divide-right array - System.arraycopy( - divideArray, divideX, rightArray, 0, indexNum - divideX); - - double minLeftArea = 0; //Minimum length of left array - double minRightArea = 0; //Minimum length of right array - double minValue = 0; //Minimum lengt - - minLeftArea = closestPair(leftArray, divideX); // recursive closestPair - minRightArea = closestPair(rightArray, indexNum - divideX); - // window size (= minimum length) - minValue = Math.min(minLeftArea, minRightArea); - - // Create window. Set the size for creating a window - // and creating a new array for the coordinates in the window - for (int i = 0; i < indexNum; i++) { - double xGap = Math.abs(divideArray[divideX].x - divideArray[i].x); - if (xGap < minValue) { - ClosestPair.setSecondCount(secondCount + 1); // size of the array - } else { - if (divideArray[i].x > divideArray[divideX].x) { - break; - } - } - } - // new array for coordinates in window - Location[] firstWindow = new Location[secondCount]; - int k = 0; - for (int i = 0; i < indexNum; i++) { - double xGap = Math.abs(divideArray[divideX].x - divideArray[i].x); - if (xGap < minValue) { // if it's inside a window - firstWindow[k] = divideArray[i]; // put in an array - k++; - } else { - if (divideArray[i].x > divideArray[divideX].x) { - break; - } - } + } + + /** + * closestPair function: find closest pair. + * + * @param a (IN Parameter) array stored before divide
+ * @param indexNum (IN Parameter) number coordinates divideArray
+ * @return minimum distance
+ */ + public double closestPair(final Location[] a, final int indexNum) { + + Location[] divideArray = new Location[indexNum]; + System.arraycopy(a, 0, divideArray, 0, indexNum); // Copy previous array + int divideX = indexNum / 2; // Intermediate value for divide + Location[] leftArray = new Location[divideX]; // divide - left array + // divide-right array + Location[] rightArray = new Location[indexNum - divideX]; + if (indexNum <= 3) { // If the number of coordinates is 3 or less + return bruteForce(divideArray); + } + // divide-left array + System.arraycopy(divideArray, 0, leftArray, 0, divideX); + // divide-right array + System.arraycopy(divideArray, divideX, rightArray, 0, indexNum - divideX); + + double minLeftArea = 0; // Minimum length of left array + double minRightArea = 0; // Minimum length of right array + double minValue = 0; // Minimum lengt + + minLeftArea = closestPair(leftArray, divideX); // recursive closestPair + minRightArea = closestPair(rightArray, indexNum - divideX); + // window size (= minimum length) + minValue = Math.min(minLeftArea, minRightArea); + + // Create window. Set the size for creating a window + // and creating a new array for the coordinates in the window + for (int i = 0; i < indexNum; i++) { + double xGap = Math.abs(divideArray[divideX].x - divideArray[i].x); + if (xGap < minValue) { + ClosestPair.setSecondCount(secondCount + 1); // size of the array + } else { + if (divideArray[i].x > divideArray[divideX].x) { + break; } - yQuickSort(firstWindow, 0, secondCount - 1); // Sort by y coordinates - /* Coordinates in Window */ - double length = 0; - // size comparison within window - for (int i = 0; i < secondCount - 1; i++) { - for (int j = (i + 1); j < secondCount; j++) { - double xGap = Math.abs(firstWindow[i].x - firstWindow[j].x); - double yGap = Math.abs(firstWindow[i].y - firstWindow[j].y); - if (yGap < minValue) { - length = Math.sqrt(Math.pow(xGap, 2) + Math.pow(yGap, 2)); - // If measured distance is less than current min distance - if (length < minValue) { - // Change minimum distance to current distance - minValue = length; - // Conditional for registering final coordinate - if (length < minNum) { - ClosestPair.setMinNum(length); - point1 = firstWindow[i]; - point2 = firstWindow[j]; - } - } - } else { - break; - } - } + } + } + // new array for coordinates in window + Location[] firstWindow = new Location[secondCount]; + int k = 0; + for (int i = 0; i < indexNum; i++) { + double xGap = Math.abs(divideArray[divideX].x - divideArray[i].x); + if (xGap < minValue) { // if it's inside a window + firstWindow[k] = divideArray[i]; // put in an array + k++; + } else { + if (divideArray[i].x > divideArray[divideX].x) { + break; } - ClosestPair.setSecondCount(0); - return minValue; + } } - - /** - * bruteForce function: When the number of coordinates is less than 3. - * - * @param arrayParam (IN Parameter) array stored before divide
- * @return
- */ - - public double bruteForce(final Location[] arrayParam) { - - double minValue = Double.MAX_VALUE; // minimum distance - double length = 0; - double xGap = 0; // Difference between x coordinates - double yGap = 0; // Difference between y coordinates - double result = 0; - - if (arrayParam.length == 2) { - // Difference between x coordinates - xGap = (arrayParam[0].x - arrayParam[1].x); - // Difference between y coordinates - yGap = (arrayParam[0].y - arrayParam[1].y); - // distance between coordinates - length = Math.sqrt(Math.pow(xGap, 2) + Math.pow(yGap, 2)); - // Conditional statement for registering final coordinate + yQuickSort(firstWindow, 0, secondCount - 1); // Sort by y coordinates + /* Coordinates in Window */ + double length = 0; + // size comparison within window + for (int i = 0; i < secondCount - 1; i++) { + for (int j = (i + 1); j < secondCount; j++) { + double xGap = Math.abs(firstWindow[i].x - firstWindow[j].x); + double yGap = Math.abs(firstWindow[i].y - firstWindow[j].y); + if (yGap < minValue) { + length = Math.sqrt(Math.pow(xGap, 2) + Math.pow(yGap, 2)); + // If measured distance is less than current min distance + if (length < minValue) { + // Change minimum distance to current distance + minValue = length; + // Conditional for registering final coordinate if (length < minNum) { - ClosestPair.setMinNum(length); - + ClosestPair.setMinNum(length); + point1 = firstWindow[i]; + point2 = firstWindow[j]; } - point1 = arrayParam[0]; - point2 = arrayParam[1]; - result = length; + } + } else { + break; } - if (arrayParam.length == 3) { - for (int i = 0; i < arrayParam.length - 1; i++) { - for (int j = (i + 1); j < arrayParam.length; j++) { - // Difference between x coordinates - xGap = (arrayParam[i].x - arrayParam[j].x); - // Difference between y coordinates - yGap = (arrayParam[i].y - arrayParam[j].y); - // distance between coordinates - length = - Math.sqrt(Math.pow(xGap, 2) + Math.pow(yGap, 2)); - // If measured distance is less than current min distance - if (length < minValue) { - // Change minimum distance to current distance - minValue = length; - if (length < minNum) { - // Registering final coordinate - ClosestPair.setMinNum(length); - point1 = arrayParam[i]; - point2 = arrayParam[j]; - } - } - } + } + } + ClosestPair.setSecondCount(0); + return minValue; + } + + /** + * bruteForce function: When the number of coordinates is less than 3. + * + * @param arrayParam (IN Parameter) array stored before divide
+ * @return
+ */ + public double bruteForce(final Location[] arrayParam) { + + double minValue = Double.MAX_VALUE; // minimum distance + double length = 0; + double xGap = 0; // Difference between x coordinates + double yGap = 0; // Difference between y coordinates + double result = 0; + + if (arrayParam.length == 2) { + // Difference between x coordinates + xGap = (arrayParam[0].x - arrayParam[1].x); + // Difference between y coordinates + yGap = (arrayParam[0].y - arrayParam[1].y); + // distance between coordinates + length = Math.sqrt(Math.pow(xGap, 2) + Math.pow(yGap, 2)); + // Conditional statement for registering final coordinate + if (length < minNum) { + ClosestPair.setMinNum(length); + } + point1 = arrayParam[0]; + point2 = arrayParam[1]; + result = length; + } + if (arrayParam.length == 3) { + for (int i = 0; i < arrayParam.length - 1; i++) { + for (int j = (i + 1); j < arrayParam.length; j++) { + // Difference between x coordinates + xGap = (arrayParam[i].x - arrayParam[j].x); + // Difference between y coordinates + yGap = (arrayParam[i].y - arrayParam[j].y); + // distance between coordinates + length = Math.sqrt(Math.pow(xGap, 2) + Math.pow(yGap, 2)); + // If measured distance is less than current min distance + if (length < minValue) { + // Change minimum distance to current distance + minValue = length; + if (length < minNum) { + // Registering final coordinate + ClosestPair.setMinNum(length); + point1 = arrayParam[i]; + point2 = arrayParam[j]; } - result = minValue; - + } } - return result; // If only one point returns 0. + } + result = minValue; + } + return result; // If only one point returns 0. + } + + /** + * main function: execute class. + * + * @param args (IN Parameter)
+ * @throws IOException If an input or output exception occurred + */ + public static void main(final String[] args) { + + // Input data consists of one x-coordinate and one y-coordinate + + ClosestPair cp = new ClosestPair(12); + cp.array[0] = cp.buildLocation(2, 3); + cp.array[1] = cp.buildLocation(2, 16); + cp.array[2] = cp.buildLocation(3, 9); + cp.array[3] = cp.buildLocation(6, 3); + cp.array[4] = cp.buildLocation(7, 7); + cp.array[5] = cp.buildLocation(19, 4); + cp.array[6] = cp.buildLocation(10, 11); + cp.array[7] = cp.buildLocation(15, 2); + cp.array[8] = cp.buildLocation(15, 19); + cp.array[9] = cp.buildLocation(16, 11); + cp.array[10] = cp.buildLocation(17, 13); + cp.array[11] = cp.buildLocation(9, 12); + + System.out.println("Input data"); + System.out.println("Number of points: " + cp.array.length); + for (int i = 0; i < cp.array.length; i++) { + System.out.println("x: " + cp.array[i].x + ", y: " + cp.array[i].y); } - /** - * main function: execute class. - * - * @param args (IN Parameter)
- * @throws IOException If an input or output - * exception occurred - */ - - public static void main(final String[] args) { - - //Input data consists of one x-coordinate and one y-coordinate - - ClosestPair cp = new ClosestPair(12); - cp.array[0] = cp.buildLocation(2, 3); - cp.array[1] = cp.buildLocation(2, 16); - cp.array[2] = cp.buildLocation(3, 9); - cp.array[3] = cp.buildLocation(6, 3); - cp.array[4] = cp.buildLocation(7, 7); - cp.array[5] = cp.buildLocation(19, 4); - cp.array[6] = cp.buildLocation(10, 11); - cp.array[7] = cp.buildLocation(15, 2); - cp.array[8] = cp.buildLocation(15, 19); - cp.array[9] = cp.buildLocation(16, 11); - cp.array[10] = cp.buildLocation(17, 13); - cp.array[11] = cp.buildLocation(9, 12); - - System.out.println("Input data"); - System.out.println("Number of points: " + cp.array.length); - for (int i = 0; i < cp.array.length; i++) { - System.out.println("x: " + cp.array[i].x + ", y: " + cp.array[i].y); - } - - cp.xQuickSort(cp.array, 0, cp.array.length - 1); // Sorting by x value - - double result; // minimum distance + cp.xQuickSort(cp.array, 0, cp.array.length - 1); // Sorting by x value - result = cp.closestPair(cp.array, cp.array.length); - // ClosestPair start - // minimum distance coordinates and distance output - System.out.println("Output Data"); - System.out.println("(" + cp.point1.x + ", " + cp.point1.y + ")"); - System.out.println("(" + cp.point2.x + ", " + cp.point2.y + ")"); - System.out.println("Minimum Distance : " + result); + double result; // minimum distance - } + result = cp.closestPair(cp.array, cp.array.length); + // ClosestPair start + // minimum distance coordinates and distance output + System.out.println("Output Data"); + System.out.println("(" + cp.point1.x + ", " + cp.point1.y + ")"); + System.out.println("(" + cp.point2.x + ", " + cp.point2.y + ")"); + System.out.println("Minimum Distance : " + result); + } } diff --git a/divideconquer/SkylineAlgorithm.java b/divideconquer/SkylineAlgorithm.java index 081cc7800bc3..e5f280f07953 100644 --- a/divideconquer/SkylineAlgorithm.java +++ b/divideconquer/SkylineAlgorithm.java @@ -5,182 +5,165 @@ /** * @author dimgrichr - *

- * Space complexity: O(n) - * Time complexity: O(nlogn), because it is a divide and conquer algorithm + *

Space complexity: O(n) Time complexity: O(nlogn), because it is a divide and conquer + * algorithm */ public class SkylineAlgorithm { - private ArrayList points; - - /** - * Main constructor of the application. - * ArrayList points gets created, which represents the sum of all edges. - */ - public SkylineAlgorithm() { - points = new ArrayList<>(); + private ArrayList points; + + /** + * Main constructor of the application. ArrayList points gets created, which represents the sum of + * all edges. + */ + public SkylineAlgorithm() { + points = new ArrayList<>(); + } + + /** @return points, the ArrayList that includes all points. */ + public ArrayList getPoints() { + return points; + } + + /** + * The main divide and conquer, and also recursive algorithm. It gets an ArrayList full of points + * as an argument. If the size of that ArrayList is 1 or 2, the ArrayList is returned as it is, or + * with one less point (if the initial size is 2 and one of it's points, is dominated by the other + * one). On the other hand, if the ArrayList's size is bigger than 2, the function is called + * again, twice, with arguments the corresponding half of the initial ArrayList each time. Once + * the flashback has ended, the function produceFinalSkyLine gets called, in order to produce the + * final skyline, and return it. + * + * @param list, the initial list of points + * @return leftSkyLine, the combination of first half's and second half's skyline + * @see Point + */ + public ArrayList produceSubSkyLines(ArrayList list) { + + // part where function exits flashback + int size = list.size(); + if (size == 1) { + return list; + } else if (size == 2) { + if (list.get(0).dominates(list.get(1))) { + list.remove(1); + } else { + if (list.get(1).dominates(list.get(0))) { + list.remove(0); + } + } + return list; } - - /** - * @return points, the ArrayList that includes all points. - */ - public ArrayList getPoints() { - return points; + // recursive part of the function + ArrayList leftHalf = new ArrayList<>(); + ArrayList rightHalf = new ArrayList<>(); + for (int i = 0; i < list.size(); i++) { + if (i < list.size() / 2) { + leftHalf.add(list.get(i)); + } else { + rightHalf.add(list.get(i)); + } + } + ArrayList leftSubSkyLine = produceSubSkyLines(leftHalf); + ArrayList rightSubSkyLine = produceSubSkyLines(rightHalf); + + // skyline is produced + return produceFinalSkyLine(leftSubSkyLine, rightSubSkyLine); + } + + /** + * The first half's skyline gets cleared from some points that are not part of the final skyline + * (Points with same x-value and different y=values. The point with the smallest y-value is kept). + * Then, the minimum y-value of the points of first half's skyline is found. That helps us to + * clear the second half's skyline, because, the points of second half's skyline that have greater + * y-value of the minimum y-value that we found before, are dominated, so they are not part of the + * final skyline. Finally, the "cleaned" first half's and second half's skylines, are combined, + * producing the final skyline, which is returned. + * + * @param left the skyline of the left part of points + * @param right the skyline of the right part of points + * @return left the final skyline + */ + public ArrayList produceFinalSkyLine(ArrayList left, ArrayList right) { + + // dominated points of ArrayList left are removed + for (int i = 0; i < left.size() - 1; i++) { + if (left.get(i).x == left.get(i + 1).x && left.get(i).y > left.get(i + 1).y) { + left.remove(i); + i--; + } } - - /** - * The main divide and conquer, and also recursive algorithm. - * It gets an ArrayList full of points as an argument. - * If the size of that ArrayList is 1 or 2, - * the ArrayList is returned as it is, or with one less point - * (if the initial size is 2 and one of it's points, is dominated by the other one). - * On the other hand, if the ArrayList's size is bigger than 2, - * the function is called again, twice, - * with arguments the corresponding half of the initial ArrayList each time. - * Once the flashback has ended, the function produceFinalSkyLine gets called, - * in order to produce the final skyline, and return it. - * - * @param list, the initial list of points - * @return leftSkyLine, the combination of first half's and second half's skyline - * @see Point - */ - public ArrayList produceSubSkyLines(ArrayList list) { - - // part where function exits flashback - int size = list.size(); - if (size == 1) { - return list; - } else if (size == 2) { - if (list.get(0).dominates(list.get(1))) { - list.remove(1); - } else { - if (list.get(1).dominates(list.get(0))) { - list.remove(0); - } - } - return list; - } - - // recursive part of the function - ArrayList leftHalf = new ArrayList<>(); - ArrayList rightHalf = new ArrayList<>(); - for (int i = 0; i < list.size(); i++) { - if (i < list.size() / 2) { - leftHalf.add(list.get(i)); - } else { - rightHalf.add(list.get(i)); - } + // minimum y-value is found + int min = left.get(0).y; + for (int i = 1; i < left.size(); i++) { + if (min > left.get(i).y) { + min = left.get(i).y; + if (min == 1) { + i = left.size(); } - ArrayList leftSubSkyLine = produceSubSkyLines(leftHalf); - ArrayList rightSubSkyLine = produceSubSkyLines(rightHalf); + } + } - // skyline is produced - return produceFinalSkyLine(leftSubSkyLine, rightSubSkyLine); + // dominated points of ArrayList right are removed + for (int i = 0; i < right.size(); i++) { + if (right.get(i).y >= min) { + right.remove(i); + i--; + } } + // final skyline found and returned + left.addAll(right); + return left; + } + + public static class Point { + private int x; + private int y; /** - * The first half's skyline gets cleared - * from some points that are not part of the final skyline - * (Points with same x-value and different y=values. The point with the smallest y-value is kept). - * Then, the minimum y-value of the points of first half's skyline is found. - * That helps us to clear the second half's skyline, because, the points - * of second half's skyline that have greater y-value of the minimum y-value that we found before, - * are dominated, so they are not part of the final skyline. - * Finally, the "cleaned" first half's and second half's skylines, are combined, - * producing the final skyline, which is returned. + * The main constructor of Point Class, used to represent the 2 Dimension points. * - * @param left the skyline of the left part of points - * @param right the skyline of the right part of points - * @return left the final skyline + * @param x the point's x-value. + * @param y the point's y-value. */ - public ArrayList produceFinalSkyLine(ArrayList left, ArrayList right) { - - // dominated points of ArrayList left are removed - for (int i = 0; i < left.size() - 1; i++) { - if (left.get(i).x == left.get(i + 1).x && left.get(i).y > left.get(i + 1).y) { - left.remove(i); - i--; - } - } - - // minimum y-value is found - int min = left.get(0).y; - for (int i = 1; i < left.size(); i++) { - if (min > left.get(i).y) { - min = left.get(i).y; - if (min == 1) { - i = left.size(); - } - } - } - - // dominated points of ArrayList right are removed - for (int i = 0; i < right.size(); i++) { - if (right.get(i).y >= min) { - right.remove(i); - i--; - } - } - - // final skyline found and returned - left.addAll(right); - return left; + public Point(int x, int y) { + this.x = x; + this.y = y; } + /** @return x, the x-value */ + public int getX() { + return x; + } - public static class Point { - private int x; - private int y; - - /** - * The main constructor of Point Class, used to represent the 2 Dimension points. - * - * @param x the point's x-value. - * @param y the point's y-value. - */ - public Point(int x, int y) { - this.x = x; - this.y = y; - } - - /** - * @return x, the x-value - */ - public int getX() { - return x; - } - - /** - * @return y, the y-value - */ - public int getY() { - return y; - } - - /** - * Based on the skyline theory, - * it checks if the point that calls the function dominates the argument point. - * - * @param p1 the point that is compared - * @return true if the point wich calls the function dominates p1 - * false otherwise. - */ - public boolean dominates(Point p1) { - // checks if p1 is dominated - return (this.x < p1.x && this.y <= p1.y) || (this.x <= p1.x && this.y < p1.y); - } + /** @return y, the y-value */ + public int getY() { + return y; } /** - * It is used to compare the 2 Dimension points, - * based on their x-values, in order get sorted later. + * Based on the skyline theory, it checks if the point that calls the function dominates the + * argument point. + * + * @param p1 the point that is compared + * @return true if the point wich calls the function dominates p1 false otherwise. */ - class XComparator implements Comparator { - @Override - public int compare(Point a, Point b) { - return Integer.compare(a.x, b.x); - } + public boolean dominates(Point p1) { + // checks if p1 is dominated + return (this.x < p1.x && this.y <= p1.y) || (this.x <= p1.x && this.y < p1.y); + } + } + + /** + * It is used to compare the 2 Dimension points, based on their x-values, in order get sorted + * later. + */ + class XComparator implements Comparator { + @Override + public int compare(Point a, Point b) { + return Integer.compare(a.x, b.x); } + } } diff --git a/strings/Alphabetical.java b/strings/Alphabetical.java index babf542bf01f..67620eae5367 100644 --- a/strings/Alphabetical.java +++ b/strings/Alphabetical.java @@ -1,35 +1,33 @@ package strings; /** - *

- * Alphabetical order is a system whereby character strings are placed in order - * based on the position of the characters in the conventional ordering of an alphabet. - *

- * Wikipedia: https://en.wikipedia.org/wiki/Alphabetical_order + * Alphabetical order is a system whereby character strings are placed in order based on the + * position of the characters in the conventional ordering of an alphabet. Wikipedia: + * https://en.wikipedia.org/wiki/Alphabetical_order */ class Alphabetical { - public static void main(String[] args) { - assert !isAlphabetical("123abc"); - assert isAlphabetical("aBC"); - assert isAlphabetical("abc"); - assert !isAlphabetical("xyzabc"); - assert isAlphabetical("abcxyz"); - } + public static void main(String[] args) { + assert !isAlphabetical("123abc"); + assert isAlphabetical("aBC"); + assert isAlphabetical("abc"); + assert !isAlphabetical("xyzabc"); + assert isAlphabetical("abcxyz"); + } - /** - * Check if a string is alphabetical order or not - * - * @param s a string - * @return {@code true} if given string is alphabetical order, otherwise {@code false} - */ - public static boolean isAlphabetical(String s) { - s = s.toLowerCase(); - for (int i = 0; i < s.length() - 1; ++i) { - if (!Character.isLetter(s.charAt(i)) || !(s.charAt(i) <= s.charAt(i + 1))) { - return false; - } - } - return true; + /** + * Check if a string is alphabetical order or not + * + * @param s a string + * @return {@code true} if given string is alphabetical order, otherwise {@code false} + */ + public static boolean isAlphabetical(String s) { + s = s.toLowerCase(); + for (int i = 0; i < s.length() - 1; ++i) { + if (!Character.isLetter(s.charAt(i)) || !(s.charAt(i) <= s.charAt(i + 1))) { + return false; + } } -} \ No newline at end of file + return true; + } +} diff --git a/strings/CharactersSame.java b/strings/CharactersSame.java index d88c03209d88..26ccbd4f0c24 100644 --- a/strings/CharactersSame.java +++ b/strings/CharactersSame.java @@ -2,28 +2,26 @@ public class CharactersSame { - /** - * Driver Code - */ - public static void main(String[] args) { - assert isAllCharactersSame(""); - assert !isAllCharactersSame("aab"); - assert isAllCharactersSame("aaa"); - assert isAllCharactersSame("11111"); - } + /** Driver Code */ + public static void main(String[] args) { + assert isAllCharactersSame(""); + assert !isAllCharactersSame("aab"); + assert isAllCharactersSame("aaa"); + assert isAllCharactersSame("11111"); + } - /** - * check if all the characters of a string are same - * - * @param s the string to check - * @return {@code true} if all characters of a string are same, otherwise {@code false} - */ - public static boolean isAllCharactersSame(String s) { - for (int i = 1, length = s.length(); i < length; ++i) { - if (s.charAt(i) != s.charAt(0)) { - return false; - } - } - return true; + /** + * check if all the characters of a string are same + * + * @param s the string to check + * @return {@code true} if all characters of a string are same, otherwise {@code false} + */ + public static boolean isAllCharactersSame(String s) { + for (int i = 1, length = s.length(); i < length; ++i) { + if (s.charAt(i) != s.charAt(0)) { + return false; + } } + return true; + } } diff --git a/strings/CheckAnagrams.java b/strings/CheckAnagrams.java index 46642e01e4b7..20ab715acede 100644 --- a/strings/CheckAnagrams.java +++ b/strings/CheckAnagrams.java @@ -3,30 +3,30 @@ import java.util.Arrays; /** - * Two strings are anagrams if they are made of the same letters - * arranged differently (ignoring the case). + * Two strings are anagrams if they are made of the same letters arranged differently (ignoring the + * case). */ public class CheckAnagrams { - public static void main(String[] args) { - assert isAnagrams("Silent", "Listen"); - assert isAnagrams("This is a string", "Is this a string"); - assert !isAnagrams("There", "Their"); - } + public static void main(String[] args) { + assert isAnagrams("Silent", "Listen"); + assert isAnagrams("This is a string", "Is this a string"); + assert !isAnagrams("There", "Their"); + } - /** - * Check if two strings are anagrams or not - * - * @param s1 the first string - * @param s2 the second string - * @return {@code true} if two string are anagrams, otherwise {@code false} - */ - public static boolean isAnagrams(String s1, String s2) { - s1 = s1.toLowerCase(); - s2 = s2.toLowerCase(); - char[] values1 = s1.toCharArray(); - char[] values2 = s2.toCharArray(); - Arrays.sort(values1); - Arrays.sort(values2); - return new String(values1).equals(new String(values2)); - } + /** + * Check if two strings are anagrams or not + * + * @param s1 the first string + * @param s2 the second string + * @return {@code true} if two string are anagrams, otherwise {@code false} + */ + public static boolean isAnagrams(String s1, String s2) { + s1 = s1.toLowerCase(); + s2 = s2.toLowerCase(); + char[] values1 = s1.toCharArray(); + char[] values2 = s2.toCharArray(); + Arrays.sort(values1); + Arrays.sort(values2); + return new String(values1).equals(new String(values2)); + } } diff --git a/strings/Lower.java b/strings/Lower.java index 15cc027eb785..4746e787cd2e 100644 --- a/strings/Lower.java +++ b/strings/Lower.java @@ -2,29 +2,27 @@ public class Lower { - /** - * Driver Code - */ - public static void main(String[] args) { - String[] strings = {"ABC", "ABC123", "abcABC", "abc123ABC"}; - for (String s : strings) { - assert toLowerCase(s).equals(s.toLowerCase()); - } + /** Driver Code */ + public static void main(String[] args) { + String[] strings = {"ABC", "ABC123", "abcABC", "abc123ABC"}; + for (String s : strings) { + assert toLowerCase(s).equals(s.toLowerCase()); } + } - /** - * Converts all of the characters in this {@code String} to lower case - * - * @param s the string to convert - * @return the {@code String}, converted to lowercase. - */ - public static String toLowerCase(String s) { - char[] values = s.toCharArray(); - for (int i = 0; i < values.length; ++i) { - if (Character.isLetter(values[i]) && Character.isUpperCase(values[i])) { - values[i] = Character.toLowerCase(values[i]); - } - } - return new String(values); + /** + * Converts all of the characters in this {@code String} to lower case + * + * @param s the string to convert + * @return the {@code String}, converted to lowercase. + */ + public static String toLowerCase(String s) { + char[] values = s.toCharArray(); + for (int i = 0; i < values.length; ++i) { + if (Character.isLetter(values[i]) && Character.isUpperCase(values[i])) { + values[i] = Character.toLowerCase(values[i]); + } } + return new String(values); + } } diff --git a/strings/Palindrome.java b/strings/Palindrome.java index 8f95a83a0787..9f77b4c38d04 100644 --- a/strings/Palindrome.java +++ b/strings/Palindrome.java @@ -1,68 +1,64 @@ package strings; -/** - * Wikipedia: https://en.wikipedia.org/wiki/Palindrome - */ +/** Wikipedia: https://en.wikipedia.org/wiki/Palindrome */ class Palindrome { - /** - * Driver Code - */ - public static void main(String[] args) { - String[] palindromes = {null, "", "aba", "123321"}; - for (String s : palindromes) { - assert isPalindrome(s) && isPalindromeRecursion(s) && isPalindrome1(s); - } - - String[] notPalindromes = {"abb", "abc", "abc123"}; - for (String s : notPalindromes) { - assert !isPalindrome(s) && !isPalindromeRecursion(s) && !isPalindrome1(s); - } + /** Driver Code */ + public static void main(String[] args) { + String[] palindromes = {null, "", "aba", "123321"}; + for (String s : palindromes) { + assert isPalindrome(s) && isPalindromeRecursion(s) && isPalindrome1(s); } - /** - * Check if a string is palindrome string or not - * - * @param s a string to check - * @return {@code true} if given string is palindrome, otherwise {@code false} - */ - public static boolean isPalindrome(String s) { - return (s == null || s.length() <= 1) || s.equals(new StringBuilder(s).reverse().toString()); + String[] notPalindromes = {"abb", "abc", "abc123"}; + for (String s : notPalindromes) { + assert !isPalindrome(s) && !isPalindromeRecursion(s) && !isPalindrome1(s); } + } - /** - * Check if a string is palindrome string or not using recursion - * - * @param s a string to check - * @return {@code true} if given string is palindrome, otherwise {@code false} - */ - public static boolean isPalindromeRecursion(String s) { - if (s == null || s.length() <= 1) { - return true; - } + /** + * Check if a string is palindrome string or not + * + * @param s a string to check + * @return {@code true} if given string is palindrome, otherwise {@code false} + */ + public static boolean isPalindrome(String s) { + return (s == null || s.length() <= 1) || s.equals(new StringBuilder(s).reverse().toString()); + } - if (s.charAt(0) != s.charAt(s.length() - 1)) { - return false; - } + /** + * Check if a string is palindrome string or not using recursion + * + * @param s a string to check + * @return {@code true} if given string is palindrome, otherwise {@code false} + */ + public static boolean isPalindromeRecursion(String s) { + if (s == null || s.length() <= 1) { + return true; + } - return isPalindrome(s.substring(1, s.length() - 1)); + if (s.charAt(0) != s.charAt(s.length() - 1)) { + return false; } - /** - * Check if a string is palindrome string or not another way - * - * @param s a string to check - * @return {@code true} if given string is palindrome, otherwise {@code false} - */ - public static boolean isPalindrome1(String s) { - if (s == null || s.length() <= 1) { - return true; - } - for (int i = 0, j = s.length() - 1; i < j; ++i, --j) { - if (s.charAt(i) != s.charAt(j)) { - return false; - } - } - return true; + return isPalindrome(s.substring(1, s.length() - 1)); + } + + /** + * Check if a string is palindrome string or not another way + * + * @param s a string to check + * @return {@code true} if given string is palindrome, otherwise {@code false} + */ + public static boolean isPalindrome1(String s) { + if (s == null || s.length() <= 1) { + return true; + } + for (int i = 0, j = s.length() - 1; i < j; ++i, --j) { + if (s.charAt(i) != s.charAt(j)) { + return false; + } } + return true; + } } diff --git a/strings/Pangram.java b/strings/Pangram.java index a18cb12c783e..27fce85a10cf 100644 --- a/strings/Pangram.java +++ b/strings/Pangram.java @@ -1,39 +1,35 @@ package strings; -/** - * Wikipedia: https://en.wikipedia.org/wiki/Pangram - */ +/** Wikipedia: https://en.wikipedia.org/wiki/Pangram */ public class Pangram { - /** - * Driver Code - */ - public static void main(String[] args) { - assert isPangram("The quick brown fox jumps over the lazy dog"); - assert !isPangram("The quick brown fox jumps over the azy dog"); /* not exists l character */ - } + /** Driver Code */ + public static void main(String[] args) { + assert isPangram("The quick brown fox jumps over the lazy dog"); + assert !isPangram("The quick brown fox jumps over the azy dog"); /* not exists l character */ + } - /** - * Check if a string is a pangram string or not - * - * @param s string to check - * @return {@code true} if given string is pangram, otherwise {@code false} - */ - public static boolean isPangram(String s) { - boolean[] marked = new boolean[26]; /* by default all letters don't exists */ - char[] values = s.toCharArray(); - for (char value : values) { - if (Character.isLetter(value)) { - int index = Character.isUpperCase(value) ? value - 'A' : value - 'a'; - marked[index] = true; /* mark current character exists */ - } - } + /** + * Check if a string is a pangram string or not + * + * @param s string to check + * @return {@code true} if given string is pangram, otherwise {@code false} + */ + public static boolean isPangram(String s) { + boolean[] marked = new boolean[26]; /* by default all letters don't exists */ + char[] values = s.toCharArray(); + for (char value : values) { + if (Character.isLetter(value)) { + int index = Character.isUpperCase(value) ? value - 'A' : value - 'a'; + marked[index] = true; /* mark current character exists */ + } + } - for (boolean b : marked) { - if (!b) { - return false; - } - } - return true; + for (boolean b : marked) { + if (!b) { + return false; + } } + return true; + } } diff --git a/strings/ReverseString.java b/strings/ReverseString.java index 71191731fe37..bcbe6925029d 100644 --- a/strings/ReverseString.java +++ b/strings/ReverseString.java @@ -1,44 +1,41 @@ package strings; -/** - * Reverse String using different version - */ +/** Reverse String using different version */ public class ReverseString { - public static void main(String[] args) { - assert reverse("abc123").equals("321cba"); - assert reverse2("abc123").equals("321cba"); - } + public static void main(String[] args) { + assert reverse("abc123").equals("321cba"); + assert reverse2("abc123").equals("321cba"); + } - /** - * easiest way to reverses the string str and returns it - * - * @param str string to be reversed - * @return reversed string - */ - public static String reverse(String str) { - return new StringBuilder(str).reverse().toString(); - } + /** + * easiest way to reverses the string str and returns it + * + * @param str string to be reversed + * @return reversed string + */ + public static String reverse(String str) { + return new StringBuilder(str).reverse().toString(); + } - /** - * second way to reverses the string str and returns it - * - * @param str string to be reversed - * @return reversed string - */ - public static String reverse2(String str) { + /** + * second way to reverses the string str and returns it + * + * @param str string to be reversed + * @return reversed string + */ + public static String reverse2(String str) { - if (str == null || str.isEmpty()) { - return str; - } - - char[] value = str.toCharArray(); - for (int i = 0, j = str.length() - 1; i < j; i++, j--) { - char temp = value[i]; - value[i] = value[j]; - value[j] = temp; - } - return new String(value); + if (str == null || str.isEmpty()) { + return str; } -} \ No newline at end of file + char[] value = str.toCharArray(); + for (int i = 0, j = str.length() - 1; i < j; i++, j--) { + char temp = value[i]; + value[i] = value[j]; + value[j] = temp; + } + return new String(value); + } +} diff --git a/strings/Rotation.java b/strings/Rotation.java index e1f0046f15f4..e855626b3de8 100644 --- a/strings/Rotation.java +++ b/strings/Rotation.java @@ -1,64 +1,58 @@ package strings; - /** - * Given a string, moving several characters - * in front of the string to the end of the string. - * For example, move the two characters'a' and 'b' in - * front of the string "abcdef" to the end of the string, - * so that the original string becomes the string "cdefab" + * Given a string, moving several characters in front of the string to the end of the string. For + * example, move the two characters'a' and 'b' in front of the string "abcdef" to the end of the + * string, so that the original string becomes the string "cdefab" */ public class Rotation { - public static void main(String[] args) { - assert rotation("abcdef", 2).equals("cdefab"); + public static void main(String[] args) { + assert rotation("abcdef", 2).equals("cdefab"); - char[] values = "abcdef".toCharArray(); - rotation(values, 2); - assert new String(values).equals("cdefab"); - } + char[] values = "abcdef".toCharArray(); + rotation(values, 2); + assert new String(values).equals("cdefab"); + } - /** - * Move {@code n} characters in front of given string to the end of string - * time complexity: O(n) - * space complexity: O(n) - * - * @param s given string - * @param n the total characters to be moved - * @return string after rotation - */ - public static String rotation(String s, int n) { - return s.substring(n) + s.substring(0, n); - } + /** + * Move {@code n} characters in front of given string to the end of string time complexity: O(n) + * space complexity: O(n) + * + * @param s given string + * @param n the total characters to be moved + * @return string after rotation + */ + public static String rotation(String s, int n) { + return s.substring(n) + s.substring(0, n); + } - /** - * Move {@code n} characters in front of given character array to the end of array - * time complexity: O(n) - * space complexity: O(1) - * - * @param values given character array - * @param n the total characters to be moved - */ - public static void rotation(char[] values, int n) { - reverse(values, 0, n - 1); - reverse(values, n, values.length - 1); - reverse(values, 0, values.length - 1); - } + /** + * Move {@code n} characters in front of given character array to the end of array time + * complexity: O(n) space complexity: O(1) + * + * @param values given character array + * @param n the total characters to be moved + */ + public static void rotation(char[] values, int n) { + reverse(values, 0, n - 1); + reverse(values, n, values.length - 1); + reverse(values, 0, values.length - 1); + } - /** - * Reverse character array - * - * @param values character array - * @param from begin index of given array - * @param to end index of given array - */ - public static void reverse(char[] values, int from, int to) { - while (from < to) { - char temp = values[from]; - values[from] = values[to]; - values[to] = temp; - from++; - to--; - } + /** + * Reverse character array + * + * @param values character array + * @param from begin index of given array + * @param to end index of given array + */ + public static void reverse(char[] values, int from, int to) { + while (from < to) { + char temp = values[from]; + values[from] = values[to]; + values[to] = temp; + from++; + to--; } - + } } diff --git a/strings/Upper.java b/strings/Upper.java index ef5a616d05f2..22becbf448aa 100644 --- a/strings/Upper.java +++ b/strings/Upper.java @@ -2,29 +2,27 @@ public class Upper { - /** - * Driver Code - */ - public static void main(String[] args) { - String[] strings = {"ABC", "ABC123", "abcABC", "abc123ABC"}; - for (String s : strings) { - assert toUpperCase(s).equals(s.toUpperCase()); - } + /** Driver Code */ + public static void main(String[] args) { + String[] strings = {"ABC", "ABC123", "abcABC", "abc123ABC"}; + for (String s : strings) { + assert toUpperCase(s).equals(s.toUpperCase()); } + } - /** - * Converts all of the characters in this {@code String} to upper case - * - * @param s the string to convert - * @return the {@code String}, converted to uppercase. - */ - public static String toUpperCase(String s) { - char[] values = s.toCharArray(); - for (int i = 0; i < values.length; ++i) { - if (Character.isLetter(values[i]) && Character.isLowerCase(values[i])) { - values[i] = Character.toUpperCase(values[i]); - } - } - return new String(values); + /** + * Converts all of the characters in this {@code String} to upper case + * + * @param s the string to convert + * @return the {@code String}, converted to uppercase. + */ + public static String toUpperCase(String s) { + char[] values = s.toCharArray(); + for (int i = 0; i < values.length; ++i) { + if (Character.isLetter(values[i]) && Character.isLowerCase(values[i])) { + values[i] = Character.toUpperCase(values[i]); + } } + return new String(values); + } }