From 00282efd8becbd0612cc710f49bf21a562deb034 Mon Sep 17 00:00:00 2001 From: acbin <44314231+acbin@users.noreply.github.com> Date: Fri, 9 Jun 2023 18:52:05 +0800 Subject: [PATCH] style: format code (#4212) close #4204 --- .../thealgorithms/audiofilters/IIRFilter.java | 20 +- .../AllPathsFromSourceToTarget.java | 33 +- .../backtracking/ArrayCombination.java | 2 +- .../backtracking/Combination.java | 6 +- .../thealgorithms/backtracking/FloodFill.java | 8 +- .../backtracking/KnightsTour.java | 41 +-- .../backtracking/MazeRecursion.java | 16 +- .../thealgorithms/backtracking/NQueens.java | 25 +- .../thealgorithms/backtracking/PowerSum.java | 22 +- .../backtracking/WordSearch.java | 16 +- .../java/com/thealgorithms/ciphers/AES.java | 104 ++---- .../thealgorithms/ciphers/AESEncryption.java | 20 +- .../thealgorithms/ciphers/AffineCipher.java | 19 +- .../com/thealgorithms/ciphers/Blowfish.java | 57 +-- .../com/thealgorithms/ciphers/Caesar.java | 15 +- .../ciphers/ColumnarTranspositionCipher.java | 59 +--- .../java/com/thealgorithms/ciphers/DES.java | 252 +++++--------- .../com/thealgorithms/ciphers/HillCipher.java | 21 +- .../com/thealgorithms/ciphers/Polybius.java | 13 +- .../java/com/thealgorithms/ciphers/RSA.java | 10 +- .../ciphers/SimpleSubCipher.java | 1 - .../com/thealgorithms/ciphers/Vigenere.java | 28 +- .../thealgorithms/ciphers/a5/A5Cipher.java | 3 +- .../ciphers/a5/A5KeyStreamGenerator.java | 15 +- .../ciphers/a5/CompositeLFSR.java | 8 +- .../com/thealgorithms/ciphers/a5/Utils.java | 9 +- .../conversions/AnyBaseToAnyBase.java | 16 +- .../conversions/DecimalToAnyBase.java | 17 +- .../conversions/DecimalToBinary.java | 4 +- .../thealgorithms/conversions/HexToOct.java | 3 +- .../conversions/RgbHsvConversion.java | 123 ++----- .../conversions/TurkishToLatinConversion.java | 7 +- .../buffers/CircularBuffer.java | 11 +- .../datastructures/caches/LFUCache.java | 3 +- .../datastructures/caches/LRUCache.java | 10 +- .../datastructures/caches/MRUCache.java | 10 +- .../dynamicarray/DynamicArray.java | 18 +- .../datastructures/graphs/A_Star.java | 170 ++------- .../datastructures/graphs/BellmanFord.java | 43 ++- .../graphs/BipartiteGrapfDFS.java | 15 +- .../graphs/ConnectedComponent.java | 8 +- .../datastructures/graphs/Cycles.java | 4 +- .../graphs/DIJSKSTRAS_ALGORITHM.java | 34 +- .../datastructures/graphs/FloydWarshall.java | 59 ++-- .../graphs/HamiltonianCycle.java | 11 +- .../datastructures/graphs/KahnsAlgorithm.java | 4 +- .../datastructures/graphs/Kosaraju.java | 73 ++-- .../datastructures/graphs/Kruskal.java | 38 +- .../datastructures/graphs/MatrixGraphs.java | 26 +- .../datastructures/graphs/PrimMST.java | 29 +- .../graphs/TarjansAlgorithm.java | 58 ++-- .../hashmap/hashing/HashMapCuckooHashing.java | 65 ++-- .../hashmap/hashing/Intersection.java | 7 +- .../datastructures/hashmap/hashing/Main.java | 46 ++- .../hashmap/hashing/MainCuckooHashing.java | 88 ++--- .../hashmap/hashing/MajorityElement.java | 29 +- .../datastructures/hashmap/hashing/Map.java | 1 - .../datastructures/heaps/FibonacciHeap.java | 61 ++-- .../datastructures/heaps/GenericHeap.java | 14 +- .../datastructures/heaps/HeapElement.java | 11 +- .../datastructures/heaps/LeftistHeap.java | 174 +++++----- .../datastructures/heaps/MaxHeap.java | 55 +-- .../datastructures/heaps/MinHeap.java | 55 +-- .../heaps/MinPriorityQueue.java | 15 +- .../lists/CircleLinkedList.java | 8 +- .../lists/CursorLinkedList.java | 3 +- .../lists/DoublyLinkedList.java | 20 +- .../lists/MergeSortedArrayList.java | 6 +- .../lists/MergeSortedSinglyLinkedList.java | 9 +- .../lists/Merge_K_SortedLinkedlist.java | 4 +- .../datastructures/lists/RandomNode.java | 22 +- .../SearchSinglyLinkedListRecursion.java | 5 +- .../lists/SinglyLinkedList.java | 34 +- .../datastructures/lists/SkipList.java | 43 +-- .../datastructures/queues/CircularQueue.java | 7 +- .../datastructures/queues/LinkedQueue.java | 13 +- .../datastructures/queues/PriorityQueues.java | 7 +- .../stacks/BalancedBrackets.java | 44 +-- .../stacks/CalculateMaxOfMin.java | 8 +- .../stacks/DecimalToAnyUsingStack.java | 7 +- .../stacks/DuplicateBrackets.java | 3 +- .../datastructures/stacks/InfixToPostfix.java | 28 +- .../stacks/LargestRectangle.java | 7 +- .../stacks/MaximumMinimumWindow.java | 4 +- .../stacks/NextGraterElement.java | 5 +- .../stacks/NextSmallerElement.java | 24 +- .../datastructures/stacks/NodeStack.java | 3 +- .../datastructures/stacks/PostfixToInfix.java | 22 +- .../datastructures/stacks/ReverseStack.java | 19 +- .../stacks/StackOfLinkedList.java | 8 +- .../datastructures/trees/AVLSimple.java | 46 +-- .../trees/BSTRecursiveGeneric.java | 34 +- .../datastructures/trees/BinaryTree.java | 6 +- .../trees/CheckBinaryTreeIsValidBST.java | 4 +- .../trees/CheckIfBinaryTreeBalanced.java | 17 +- .../trees/CheckTreeIsSymmetric.java | 6 +- .../CreateBinaryTreeFromInorderPreorder.java | 59 +--- .../datastructures/trees/GenericTree.java | 4 +- .../datastructures/trees/KDTree.java | 118 +++---- .../datastructures/trees/LCA.java | 23 +- .../datastructures/trees/LazySegmentTree.java | 32 +- .../datastructures/trees/RedBlackBST.java | 20 +- .../datastructures/trees/SameTreesCheck.java | 5 +- .../datastructures/trees/SegmentTree.java | 30 +- .../datastructures/trees/TreeRandomNode.java | 18 +- .../datastructures/trees/TrieImp.java | 89 +++-- .../trees/VerticalOrderTraversal.java | 38 +- .../datastructures/trees/ZigzagTraversal.java | 3 +- .../datastructures/trees/nearestRightKey.java | 2 +- .../devutils/entities/ProcessDetails.java | 1 - .../devutils/nodes/LargeTreeNode.java | 5 +- .../thealgorithms/devutils/nodes/Node.java | 3 +- .../devutils/nodes/SimpleTreeNode.java | 8 +- .../BinaryExponentiation.java | 2 +- .../divideandconquer/ClosestPair.java | 20 +- .../divideandconquer/SkylineAlgorithm.java | 15 +- .../StrassenMatrixMultiplication.java | 11 +- .../dynamicprogramming/BoardPath.java | 20 +- .../dynamicprogramming/BoundaryFill.java | 124 ++----- .../BruteForceKnapsack.java | 9 +- .../dynamicprogramming/CatalanNumber.java | 4 +- .../dynamicprogramming/ClimbingStairs.java | 7 +- .../dynamicprogramming/CoinChange.java | 23 +- .../CountFriendsPairing.java | 6 +- .../dynamicprogramming/DiceThrow.java | 11 +- .../DyanamicProgrammingKnapsack.java | 4 +- .../dynamicprogramming/EditDistance.java | 11 +- .../dynamicprogramming/EggDropping.java | 4 +- .../dynamicprogramming/Fibonacci.java | 25 +- .../dynamicprogramming/FordFulkerson.java | 15 +- .../dynamicprogramming/KadaneAlgorithm.java | 3 +- .../dynamicprogramming/Knapsack.java | 13 +- .../KnapsackMemoization.java | 13 +- .../LevenshteinDistance.java | 13 +- .../LongestAlternatingSubsequence.java | 34 +- .../LongestCommonSubsequence.java | 6 +- .../LongestIncreasingSubsequence.java | 4 +- .../LongestPalindromicSubsequence.java | 35 +- .../LongestValidParentheses.java | 5 +- .../MatrixChainMultiplication.java | 11 +- ...atrixChainRecursiveTopDownMemoisation.java | 16 +- .../dynamicprogramming/MinimumPathSum.java | 8 +- .../MinimumSumPartition.java | 6 +- .../dynamicprogramming/NewManShanksPrime.java | 3 +- .../OptimalJobScheduling.java | 58 ++-- .../PalindromicPartitioning.java | 26 +- .../dynamicprogramming/PartitionProblem.java | 12 +- .../dynamicprogramming/RegexMatching.java | 19 +- .../dynamicprogramming/RodCutting.java | 2 +- .../ShortestCommonSupersequenceLength.java | 7 +- .../dynamicprogramming/SubsetCount.java | 58 ++-- .../dynamicprogramming/SubsetSum.java | 2 +- .../dynamicprogramming/Sum_Of_Subset.java | 2 +- .../dynamicprogramming/UniquePaths.java | 18 +- .../dynamicprogramming/WineProblem.java | 6 +- .../thealgorithms/geometry/GrahamScan.java | 164 ++++----- .../com/thealgorithms/io/BufferedReader.java | 324 +++++++++--------- .../com/thealgorithms/maths/ADTFraction.java | 10 +- .../com/thealgorithms/maths/AbsoluteMin.java | 7 +- .../com/thealgorithms/maths/AliquotSum.java | 20 +- .../thealgorithms/maths/AmicableNumber.java | 36 +- .../java/com/thealgorithms/maths/Area.java | 3 +- .../maths/AutomorphicNumber.java | 12 +- .../maths/BinomialCoefficient.java | 14 +- .../maths/CircularConvolutionFFT.java | 10 +- .../com/thealgorithms/maths/Convolution.java | 5 +- .../thealgorithms/maths/ConvolutionFFT.java | 11 +- .../maths/DeterminantOfMatrix.java | 4 +- .../com/thealgorithms/maths/DigitalRoot.java | 16 +- .../thealgorithms/maths/DistanceFormula.java | 14 +- .../thealgorithms/maths/DudeneyNumber.java | 6 +- .../com/thealgorithms/maths/EulerMethod.java | 47 +-- .../java/com/thealgorithms/maths/FFT.java | 17 +- .../com/thealgorithms/maths/FFTBluestein.java | 19 +- .../com/thealgorithms/maths/Factorial.java | 3 +- .../thealgorithms/maths/FastInverseSqrt.java | 19 +- .../maths/FibonacciJavaStreams.java | 54 +-- .../thealgorithms/maths/FindMaxRecursion.java | 10 +- .../thealgorithms/maths/FindMinRecursion.java | 10 +- .../com/thealgorithms/maths/FrizzyNumber.java | 9 +- .../java/com/thealgorithms/maths/GCD.java | 8 +- .../com/thealgorithms/maths/Gaussian.java | 17 +- .../com/thealgorithms/maths/GenericRoot.java | 3 +- .../thealgorithms/maths/HarshadNumber.java | 6 +- .../thealgorithms/maths/JosephusProblem.java | 18 +- .../thealgorithms/maths/JugglerSequence.java | 5 +- .../thealgorithms/maths/KaprekarNumbers.java | 39 +-- .../com/thealgorithms/maths/KeithNumber.java | 31 +- .../maths/KrishnamurthyNumber.java | 34 +- .../maths/LeastCommonMultiple.java | 4 +- .../thealgorithms/maths/LeonardoNumber.java | 6 +- .../LinearDiophantineEquationsSolver.java | 52 +-- .../maths/LiouvilleLambdaFunction.java | 8 +- .../com/thealgorithms/maths/LongDivision.java | 18 +- .../com/thealgorithms/maths/LucasSeries.java | 4 +- .../com/thealgorithms/maths/MagicSquare.java | 10 +- .../com/thealgorithms/maths/MatrixUtil.java | 169 ++++----- .../java/com/thealgorithms/maths/Median.java | 5 +- .../thealgorithms/maths/MobiusFunction.java | 18 +- .../java/com/thealgorithms/maths/Mode.java | 17 +- .../maths/NonRepeatingElement.java | 39 +-- .../thealgorithms/maths/NthUglyNumber.java | 5 +- .../thealgorithms/maths/NumberOfDigits.java | 4 +- .../com/thealgorithms/maths/ParseInteger.java | 6 +- .../thealgorithms/maths/PascalTriangle.java | 26 +- .../com/thealgorithms/maths/PerfectCube.java | 2 +- .../thealgorithms/maths/PerfectNumber.java | 18 +- .../com/thealgorithms/maths/Perimeter.java | 17 +- .../com/thealgorithms/maths/PiNilakantha.java | 14 +- .../com/thealgorithms/maths/PollardRho.java | 28 +- .../com/thealgorithms/maths/PrimeCheck.java | 8 +- .../com/thealgorithms/maths/PronicNumber.java | 9 +- .../thealgorithms/maths/RomanNumeralUtil.java | 23 +- .../maths/SimpsonIntegration.java | 10 +- .../maths/SquareFreeInteger.java | 35 +- .../SquareRootWithNewtonRaphsonMethod.java | 10 +- .../maths/SumOfArithmeticSeries.java | 10 +- .../com/thealgorithms/maths/SumOfDigits.java | 18 +- .../maths/SumWithoutArithmeticOperators.java | 22 +- .../maths/TrinomialTriangle.java | 5 +- .../com/thealgorithms/maths/TwinPrime.java | 31 +- .../thealgorithms/maths/VampireNumber.java | 26 +- .../maths/VectorCrossProduct.java | 8 +- .../matrixexponentiation/Fibonacci.java | 37 +- .../MinimizingLateness.java | 16 +- .../misc/ColorContrastRatio.java | 37 +- .../thealgorithms/misc/InverseOfMatrix.java | 3 +- .../misc/MedianOfRunningArray.java | 2 +- .../thealgorithms/misc/PalindromePrime.java | 4 +- .../misc/RangeInSortedArray.java | 41 +-- .../java/com/thealgorithms/misc/Sort012D.java | 38 +- .../java/com/thealgorithms/misc/Sparcity.java | 12 +- .../thealgorithms/misc/ThreeSumProblem.java | 11 +- .../com/thealgorithms/misc/WordBoggle.java | 93 ++--- .../java/com/thealgorithms/others/BFPRT.java | 3 +- .../others/BankersAlgorithm.java | 55 +-- .../com/thealgorithms/others/BoyerMoore.java | 3 +- .../java/com/thealgorithms/others/CRC16.java | 33 +- .../java/com/thealgorithms/others/Conway.java | 15 +- .../java/com/thealgorithms/others/Damm.java | 31 +- .../com/thealgorithms/others/Dijkstra.java | 33 +- .../thealgorithms/others/FloydTriangle.java | 4 +- .../thealgorithms/others/HappyNumbersSeq.java | 5 +- .../com/thealgorithms/others/Huffman.java | 15 +- ...g_auto_completing_features_using_trie.java | 8 +- .../others/InsertDeleteInArray.java | 4 +- .../thealgorithms/others/KochSnowflake.java | 44 +-- .../com/thealgorithms/others/LineSweep.java | 22 +- .../others/LinearCongruentialGenerator.java | 19 +- .../others/LowestBasePalindrome.java | 15 +- .../java/com/thealgorithms/others/Luhn.java | 41 +-- .../com/thealgorithms/others/Mandelbrot.java | 97 ++---- .../others/MemoryManagementAlgorithms.java | 106 +++--- .../others/MiniMaxAlgorithm.java | 22 +- .../com/thealgorithms/others/PageRank.java | 56 +-- .../com/thealgorithms/others/PasswordGen.java | 6 +- .../com/thealgorithms/others/PerlinNoise.java | 35 +- .../others/PrintAMatrixInSpiralOrder.java | 3 - .../others/QueueUsingTwoStacks.java | 3 +- .../com/thealgorithms/others/RabinKarp.java | 23 +- .../others/RemoveDuplicateFromString.java | 8 +- .../others/ReturnSubsequence.java | 18 +- .../others/SieveOfEratosthenes.java | 6 +- .../thealgorithms/others/SkylineProblem.java | 10 +- .../java/com/thealgorithms/others/Sudoku.java | 18 +- .../com/thealgorithms/others/TopKWords.java | 7 +- .../thealgorithms/others/TowerOfHanoi.java | 15 +- .../com/thealgorithms/others/Verhoeff.java | 51 ++- .../others/cn/HammingDistance.java | 9 +- .../thealgorithms/others/countSetBits.java | 28 +- .../scheduling/FCFSScheduling.java | 22 +- .../scheduling/RRScheduling.java | 43 ++- .../scheduling/SJFScheduling.java | 92 +++-- .../thealgorithms/searches/BinarySearch.java | 30 +- .../searches/BinarySearch2dArray.java | 93 +++-- .../searches/DepthFirstSearch.java | 29 +- .../searches/ExponentalSearch.java | 30 +- .../searches/FibonacciSearch.java | 14 +- .../searches/HowManyTimesRotated.java | 20 +- .../searches/InterpolationSearch.java | 27 +- .../searches/IterativeBinarySearch.java | 21 +- .../searches/IterativeTernarySearch.java | 21 +- .../thealgorithms/searches/JumpSearch.java | 2 +- .../com/thealgorithms/searches/KMPSearch.java | 8 +- .../thealgorithms/searches/LinearSearch.java | 15 +- .../searches/LinearSearchThread.java | 6 +- .../thealgorithms/searches/LowerBound.java | 30 +- .../searches/MonteCarloTreeSearch.java | 37 +- .../searches/OrderAgnosticBinarySearch.java | 57 ++- .../searches/PerfectBinarySearch.java | 2 +- .../thealgorithms/searches/QuickSelect.java | 30 +- .../searches/RabinKarpAlgorithm.java | 2 +- ...owColumnWiseSorted2dArrayBinarySearch.java | 59 ++-- .../searches/SaddlebackSearch.java | 2 +- .../SearchInARowAndColWiseSortedMatrix.java | 3 +- .../searches/SquareRootBinarySearch.java | 4 +- .../thealgorithms/searches/TernarySearch.java | 38 +- .../com/thealgorithms/searches/UnionFind.java | 16 +- .../thealgorithms/searches/UpperBound.java | 30 +- .../sortOrderAgnosticBinarySearch.java | 36 +- .../com/thealgorithms/sorts/BeadSort.java | 59 ++-- .../com/thealgorithms/sorts/BitonicSort.java | 2 +- .../com/thealgorithms/sorts/BogoSort.java | 4 +- .../sorts/BubbleSortRecursion.java | 5 +- .../com/thealgorithms/sorts/BucketSort.java | 2 +- .../com/thealgorithms/sorts/CircleSort.java | 13 +- .../sorts/CocktailShakerSort.java | 4 +- .../com/thealgorithms/sorts/CountingSort.java | 20 +- .../java/com/thealgorithms/sorts/DNFSort.java | 40 +-- .../sorts/DualPivotQuickSort.java | 20 +- .../sorts/DutchNationalFlagSort.java | 25 +- .../thealgorithms/sorts/InsertionSort.java | 18 +- .../com/thealgorithms/sorts/LinkListSort.java | 181 +++++----- .../com/thealgorithms/sorts/MergeSort.java | 3 +- .../sorts/MergeSortNoExtraSpace.java | 12 +- .../sorts/MergeSortRecursive.java | 24 +- .../com/thealgorithms/sorts/OddEvenSort.java | 2 +- .../thealgorithms/sorts/PigeonholeSort.java | 2 +- .../com/thealgorithms/sorts/QuickSort.java | 18 +- .../com/thealgorithms/sorts/RadixSort.java | 2 +- .../thealgorithms/sorts/SelectionSort.java | 4 +- .../com/thealgorithms/sorts/ShellSort.java | 2 +- .../com/thealgorithms/sorts/SimpleSort.java | 2 +- .../thealgorithms/sorts/SortAlgorithm.java | 6 +- .../com/thealgorithms/sorts/SortUtils.java | 4 +- .../sorts/SortUtilsRandomGenerator.java | 5 +- .../com/thealgorithms/sorts/StoogeSort.java | 10 +- .../com/thealgorithms/sorts/StrandSort.java | 21 +- .../com/thealgorithms/sorts/SwapSort.java | 10 +- .../java/com/thealgorithms/sorts/TimSort.java | 4 +- .../thealgorithms/sorts/TopologicalSort.java | 42 +-- .../com/thealgorithms/sorts/TreeSort.java | 16 +- .../com/thealgorithms/sorts/WiggleSort.java | 35 +- .../thealgorithms/strings/Alphabetical.java | 5 +- .../com/thealgorithms/strings/Anagrams.java | 55 +-- .../thealgorithms/strings/CheckVowels.java | 5 +- .../strings/HammingDistance.java | 7 +- .../thealgorithms/strings/HorspoolSearch.java | 19 +- .../LetterCombinationsOfPhoneNumber.java | 25 +- .../strings/LongestPalindromicSubstring.java | 4 +- .../java/com/thealgorithms/strings/Lower.java | 7 +- .../com/thealgorithms/strings/MyAtoi.java | 27 +- .../com/thealgorithms/strings/Palindrome.java | 4 +- .../com/thealgorithms/strings/Pangram.java | 2 +- .../thealgorithms/strings/PermuteString.java | 16 +- .../strings/ReverseStringRecursive.java | 7 +- .../strings/StringCompression.java | 106 +++--- .../java/com/thealgorithms/strings/Upper.java | 7 +- .../strings/ValidParentheses.java | 56 ++- .../com/thealgorithms/strings/WordLadder.java | 14 +- .../strings/longestNonRepeativeSubstring.java | 3 +- .../strings/zigZagPattern/zigZagPattern.java | 12 +- .../AllPathsFromSourceToTargetTest.java | 41 ++- .../backtracking/CombinationTest.java | 15 +- .../backtracking/FloodFillTest.java | 72 ++-- .../backtracking/MazeRecursionTest.java | 34 +- .../backtracking/PermutationTest.java | 10 +- .../backtracking/PowerSumTest.java | 4 +- .../backtracking/WordSearchTest.java | 6 +- .../thealgorithms/ciphers/BlowfishTest.java | 12 +- .../com/thealgorithms/ciphers/CaesarTest.java | 5 +- .../com/thealgorithms/ciphers/DESTest.java | 41 ++- .../com/thealgorithms/ciphers/RSATest.java | 5 +- .../ciphers/SimpleSubCipherTest.java | 5 +- .../ciphers/SimpleSubstitutionCipherTest.java | 4 +- .../thealgorithms/ciphers/VigenereTest.java | 5 +- .../thealgorithms/ciphers/a5/LFSRTest.java | 8 +- .../conversions/BinaryToDecimalTest.java | 4 +- .../conversions/HexaDecimalToBinaryTest.java | 5 +- .../conversions/HexaDecimalToDecimalTest.java | 6 +- .../conversions/RomanToIntegerTest.java | 4 +- .../buffers/CircularBufferTest.java | 24 +- .../datastructures/caches/LFUCacheTest.java | 20 +- .../graphs/HamiltonianCycleTest.java | 34 +- .../datastructures/graphs/KosarajuTest.java | 12 +- .../graphs/TarjansAlgorithmTest.java | 14 +- .../hashmap/HashMapCuckooHashingTest.java | 2 +- .../hashmap/hashing/MajorityElementTest.java | 13 +- .../hashmap/hashing/MapTest.java | 5 +- .../datastructures/heaps/LeftistHeapTest.java | 42 +-- .../lists/SinglyLinkedListTest.java | 118 +++---- .../datastructures/lists/SkipListTest.java | 10 +- .../queues/LinkedQueueTest.java | 33 +- .../queues/PriorityQueuesTest.java | 4 +- .../trees/BSTFromSortedArrayTest.java | 6 +- .../datastructures/trees/BinaryTreeTest.java | 134 ++++---- .../trees/CeilInBinarySearchTreeTest.java | 18 +- .../trees/CheckBinaryTreeIsValidBSTTest.java | 15 +- .../trees/CheckTreeIsSymmetricTest.java | 11 +- ...eateBinaryTreeFromInorderPreorderTest.java | 21 +- .../trees/InorderTraversalTest.java | 10 +- .../datastructures/trees/KDTreeTest.java | 38 +- .../trees/LazySegmentTreeTest.java | 21 +- .../trees/LevelOrderTraversalTest.java | 16 +- .../trees/PostOrderTraversalTest.java | 10 +- .../trees/PreOrderTraversalTest.java | 10 +- .../trees/SameTreesCheckTest.java | 24 +- .../datastructures/trees/TreeTestUtils.java | 2 +- .../trees/VerticalOrderTraversalTest.java | 14 +- .../trees/ZigzagTraversalTest.java | 16 +- .../BinaryExponentiationTest.java | 1 - .../StrassenMatrixMultiplicationTest.java | 21 +- .../dynamicprogramming/EggDroppingTest.java | 20 +- .../KnapsackMemoizationTest.java | 16 +- .../LevenshteinDistanceTests.java | 5 +- .../OptimalJobSchedulingTest.java | 102 ++---- .../PartitionProblemTest.java | 20 +- .../dynamicprogramming/SubsetCountTest.java | 19 +- .../dynamicprogramming/climbStairsTest.java | 23 +- .../geometry/GrahamScanTest.java | 9 +- .../thealgorithms/io/BufferedReaderTest.java | 157 +++++---- .../thealgorithms/maths/ADTFractionTest.java | 6 +- .../thealgorithms/maths/AbsoluteMinTest.java | 6 +- .../maths/AbsoluteValueTest.java | 10 +- .../com/thealgorithms/maths/AreaTest.java | 70 ++-- .../maths/AutomorphicNumberTest.java | 11 +- .../com/thealgorithms/maths/AverageTest.java | 1 - .../maths/CollatzConjectureTest.java | 27 +- .../maths/DistanceFormulaTest.java | 62 ++-- .../maths/DudeneyNumberTest.java | 5 +- .../com/thealgorithms/maths/FindMaxTest.java | 20 +- .../com/thealgorithms/maths/FindMinTest.java | 16 +- .../thealgorithms/maths/FrizzyNumberTest.java | 40 +-- .../java/com/thealgorithms/maths/GCDTest.java | 28 +- .../maths/HarshadNumberTest.java | 3 +- .../maths/HeronsFormulaTest.java | 10 +- .../maths/KaprekarNumbersTest.java | 6 +- .../maths/LeonardoNumberTest.java | 7 +- .../maths/LiouvilleLambdaFunctionTest.java | 40 +-- .../thealgorithms/maths/LongDivisionTest.java | 35 +- .../thealgorithms/maths/LucasSeriesTest.java | 3 +- .../com/thealgorithms/maths/MedianTest.java | 3 +- .../maths/MobiusFunctionTest.java | 30 +- .../maths/NthUglyNumberTest.java | 14 +- .../maths/PascalTriangleTest.java | 30 +- .../maths/PerfectNumberTest.java | 5 +- .../maths/PerfectSquareTest.java | 6 +- .../thealgorithms/maths/PerimeterTest.java | 2 +- .../thealgorithms/maths/PollardRhoTest.java | 26 +- .../maths/PrimeFactorizationTest.java | 10 +- .../thealgorithms/maths/PronicNumberTest.java | 12 +- .../maths/ReverseNumberTest.java | 6 +- .../maths/SquareFreeIntegerTest.java | 181 +++++++--- ...SquareRootWithNewtonRaphsonTestMethod.java | 15 +- .../SquareRootwithBabylonianMethodTest.java | 20 +- .../maths/StandardDeviationTest.java | 21 +- .../maths/StandardScoreTest.java | 5 +- .../SumWithoutArithmeticOperatorsTest.java | 33 +- .../thealgorithms/maths/TwinPrimeTest.java | 102 +++--- .../com/thealgorithms/maths/VolumeTest.java | 1 + .../others/ArrayLeftRotationTest.java | 14 +- .../thealgorithms/others/BestFitCPUTest.java | 30 +- .../com/thealgorithms/others/CRC16Test.java | 5 +- .../others/CRCAlgorithmTest.java | 12 +- .../others/CalculateMaxOfMinTest.java | 14 +- .../com/thealgorithms/others/ConwayTest.java | 27 +- .../thealgorithms/others/CountCharTest.java | 7 +- .../others/CountFriendsPairingTest.java | 16 +- .../thealgorithms/others/CountWordsTest.java | 1 - .../thealgorithms/others/FirstFitCPUTest.java | 30 +- .../others/KadaneAlogrithmTest.java | 16 +- .../thealgorithms/others/LineSweepTest.java | 21 +- .../others/LinkListSortTest.java | 16 +- .../others/LowestBasePalindromeTest.java | 25 +- .../com/thealgorithms/others/NextFitTest.java | 30 +- .../thealgorithms/others/PasswordGenTest.java | 16 +- .../others/TestPrintMatrixInSpiralOrder.java | 23 +- .../thealgorithms/others/TwoPointersTest.java | 33 +- .../thealgorithms/others/WorstFitCPUTest.java | 39 +-- .../others/cn/HammingDistanceTest.java | 19 +- .../scheduling/FCFSSchedulingTest.java | 14 +- .../scheduling/RRSchedulingTest.java | 7 +- .../scheduling/SJFSchedulingTest.java | 143 ++++---- .../searches/BinarySearch2dArrayTest.java | 48 +-- .../searches/BreadthFirstSearchTest.java | 31 +- .../searches/HowManyTimesRotatedTest.java | 5 +- .../OrderAgnosticBinarySearchTest.java | 119 ++++--- .../searches/QuickSelectTest.java | 34 +- ...lumnWiseSorted2dArrayBinarySearchTest.java | 196 +++++------ ...estSearchInARowAndColWiseSortedMatrix.java | 23 +- .../sortOrderAgnosticBinarySearchTest.java | 19 +- .../com/thealgorithms/sorts/BeadSortTest.java | 14 +- .../sorts/BinaryInsertionSortTest.java | 8 +- .../com/thealgorithms/sorts/BogoSortTest.java | 30 +- .../thealgorithms/sorts/BubbleSortTest.java | 10 +- .../thealgorithms/sorts/BucketSortTest.java | 16 +- .../sorts/CocktailShakerSortTest.java | 14 +- .../com/thealgorithms/sorts/CombSortTest.java | 62 ++-- .../sorts/DualPivotQuickSortTest.java | 21 +- .../sorts/DutchNationalFlagSortTest.java | 32 +- .../sorts/InsertionSortTest.java | 7 +- .../sorts/IntrospectiveSortTest.java | 9 +- .../sorts/MergeSortRecursiveTest.java | 46 +-- .../thealgorithms/sorts/OddEvenSortTest.java | 7 +- .../sorts/SelectionSortTest.java | 14 +- .../thealgorithms/sorts/ShellSortTest.java | 31 +- .../thealgorithms/sorts/SimpleSortTest.java | 30 +- .../com/thealgorithms/sorts/SlowSortTest.java | 6 +- .../sorts/SortUtilsRandomGeneratorTest.java | 4 +- .../thealgorithms/sorts/SortUtilsTest.java | 5 +- .../sorts/SortingAlgorithmTest.java | 31 +- .../thealgorithms/sorts/StrandSortTest.java | 14 +- .../com/thealgorithms/sorts/TimSortTest.java | 4 +- .../sorts/TopologicalSortTest.java | 11 +- .../com/thealgorithms/sorts/TreeSortTest.java | 56 +-- .../thealgorithms/sorts/WiggleSortTest.java | 28 +- .../strings/HammingDistanceTest.java | 24 +- .../strings/HorspoolSearchTest.java | 11 +- .../LetterCombinationsOfPhoneNumberTest.java | 15 +- .../com/thealgorithms/strings/LowerTest.java | 6 +- .../com/thealgorithms/strings/MyAtoiTest.java | 12 +- .../thealgorithms/strings/PalindromeTest.java | 15 +- .../thealgorithms/strings/PangramTest.java | 9 +- .../strings/ReverseStringRecursiveTest.java | 16 +- .../strings/ReverseStringTest.java | 4 +- .../thealgorithms/strings/RotationTest.java | 2 +- .../strings/StringCompressionTest.java | 7 +- .../strings/ValidParenthesesTest.java | 11 +- .../thealgorithms/strings/WordLadderTest.java | 8 +- .../longestNonRepeativeSubstringTest.java | 10 +- .../zigZagPattern/zigZagPatternTest.java | 10 +- 521 files changed, 5233 insertions(+), 7309 deletions(-) diff --git a/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java b/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java index 4aca8fb4..21bb5a12 100644 --- a/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java +++ b/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java @@ -22,9 +22,7 @@ public class IIRFilter { */ public IIRFilter(int order) throws IllegalArgumentException { if (order < 1) { - throw new IllegalArgumentException( - "order must be greater than zero" - ); + throw new IllegalArgumentException("order must be greater than zero"); } this.order = order; @@ -47,24 +45,19 @@ public class IIRFilter { * @throws IllegalArgumentException if {@code aCoeffs} or {@code bCoeffs} is * not of size {@code order}, or if {@code aCoeffs[0]} is 0.0 */ - public void setCoeffs(double[] aCoeffs, double[] bCoeffs) - throws IllegalArgumentException { + public void setCoeffs(double[] aCoeffs, double[] bCoeffs) throws IllegalArgumentException { if (aCoeffs.length != order) { throw new IllegalArgumentException( - "aCoeffs must be of size " + order + ", got " + aCoeffs.length - ); + "aCoeffs must be of size " + order + ", got " + aCoeffs.length); } if (aCoeffs[0] == 0.0) { - throw new IllegalArgumentException( - "aCoeffs.get(0) must not be zero" - ); + throw new IllegalArgumentException("aCoeffs.get(0) must not be zero"); } if (bCoeffs.length != order) { throw new IllegalArgumentException( - "bCoeffs must be of size " + order + ", got " + bCoeffs.length - ); + "bCoeffs must be of size " + order + ", got " + bCoeffs.length); } for (int i = 0; i <= order; i++) { @@ -84,8 +77,7 @@ public class IIRFilter { // Process for (int i = 1; i <= order; i++) { - result += - (coeffsB[i] * historyX[i - 1] - coeffsA[i] * historyY[i - 1]); + result += (coeffsB[i] * historyX[i - 1] - coeffsA[i] * historyY[i - 1]); } result = (result + coeffsB[0] * sample) / coeffsA[0]; diff --git a/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java b/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java index 8acaa954..b840f6ad 100644 --- a/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java +++ b/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java @@ -1,4 +1,5 @@ -/** Author : Siddhant Swarup Mallick +/** + * Author : Siddhant Swarup Mallick * Github : https://github.com/siddhant2002 */ @@ -15,13 +16,12 @@ public class AllPathsFromSourceToTarget { private int v; // To store the paths from source to destination - static List> nm=new ArrayList<>(); + static List> nm = new ArrayList<>(); // adjacency list private ArrayList[] adjList; // Constructor - public AllPathsFromSourceToTarget(int vertices) - { + public AllPathsFromSourceToTarget(int vertices) { // initialise vertex count this.v = vertices; @@ -31,8 +31,7 @@ public class AllPathsFromSourceToTarget { } // utility method to initialise adjacency list - private void initAdjList() - { + private void initAdjList() { adjList = new ArrayList[v]; for (int i = 0; i < v; i++) { @@ -41,15 +40,12 @@ public class AllPathsFromSourceToTarget { } // add edge from u to v - public void addEdge(int u, int v) - { + public void addEdge(int u, int v) { // Add v to u's list. adjList[u].add(v); } - - public void storeAllPaths(int s, int d) - { + public void storeAllPaths(int s, int d) { boolean[] isVisited = new boolean[v]; ArrayList pathList = new ArrayList<>(); @@ -61,9 +57,9 @@ public class AllPathsFromSourceToTarget { // A recursive function to print all paths from 'u' to 'd'. // isVisited[] keeps track of vertices in current path. - // localPathList<> stores actual vertices in the current path - private void storeAllPathsUtil(Integer u, Integer d, boolean[] isVisited, List localPathList) - { + // localPathList<> stores actual vertices in the current path + private void storeAllPathsUtil( + Integer u, Integer d, boolean[] isVisited, List localPathList) { if (u.equals(d)) { nm.add(new ArrayList<>(localPathList)); @@ -74,7 +70,7 @@ public class AllPathsFromSourceToTarget { isVisited[u] = true; // Recursion for all the vertices adjacent to current vertex - + for (Integer i : adjList[u]) { if (!isVisited[i]) { // store current node in path[] @@ -91,12 +87,11 @@ public class AllPathsFromSourceToTarget { } // Driver program - public static List> allPathsFromSourceToTarget(int vertices, int[][] a, int source, int destination) - { + public static List> allPathsFromSourceToTarget( + int vertices, int[][] a, int source, int destination) { // Create a sample graph AllPathsFromSourceToTarget g = new AllPathsFromSourceToTarget(vertices); - for(int i=0 ; i the type of elements in the array. */ private static void backtracking( - T[] arr, - int index, - TreeSet currSet, - List> result - ) { + T[] arr, int index, TreeSet currSet, List> result) { if (index + length - currSet.size() > arr.length) return; if (length - 1 == currSet.size()) { for (int i = index; i < arr.length; i++) { diff --git a/src/main/java/com/thealgorithms/backtracking/FloodFill.java b/src/main/java/com/thealgorithms/backtracking/FloodFill.java index 6c4446a4..b6b1c5ee 100644 --- a/src/main/java/com/thealgorithms/backtracking/FloodFill.java +++ b/src/main/java/com/thealgorithms/backtracking/FloodFill.java @@ -38,13 +38,7 @@ public class FloodFill { * @param newColor The new color which to be filled in the image * @param oldColor The old color which is to be replaced in the image */ - public static void floodFill( - int[][] image, - int x, - int y, - int newColor, - int oldColor - ) { + public static void floodFill(int[][] image, int x, int y, int newColor, int oldColor) { if (x < 0 || x >= image.length) return; if (y < 0 || y >= image[x].length) return; if (getPixel(image, x, y) != oldColor) return; diff --git a/src/main/java/com/thealgorithms/backtracking/KnightsTour.java b/src/main/java/com/thealgorithms/backtracking/KnightsTour.java index a2075fd9..882b4353 100644 --- a/src/main/java/com/thealgorithms/backtracking/KnightsTour.java +++ b/src/main/java/com/thealgorithms/backtracking/KnightsTour.java @@ -4,9 +4,10 @@ import java.util.*; /* * Problem Statement: - - - Given a N*N board with the Knight placed on the first block of an empty board. Moving according to the rules of - chess knight must visit each square exactly once. Print the order of each cell in which they are visited. + + Given a N*N board with the Knight placed on the first block of an empty board. Moving according + to the rules of chess knight must visit each square exactly once. Print the order of each cell in + which they are visited. Example: - @@ -27,14 +28,14 @@ public class KnightsTour { private static final int base = 12; private static final int[][] moves = { - { 1, -2 }, - { 2, -1 }, - { 2, 1 }, - { 1, 2 }, - { -1, 2 }, - { -2, 1 }, - { -2, -1 }, - { -1, -2 }, + {1, -2}, + {2, -1}, + {2, 1}, + {1, 2}, + {-1, 2}, + {-2, 1}, + {-2, -1}, + {-1, -2}, }; // Possible moves by knight on chess private static int[][] grid; // chess grid private static int total; // total squares in chess @@ -75,23 +76,17 @@ public class KnightsTour { return false; } - Collections.sort( - neighbor, - new Comparator() { - public int compare(int[] a, int[] b) { - return a[2] - b[2]; - } + Collections.sort(neighbor, new Comparator() { + public int compare(int[] a, int[] b) { + return a[2] - b[2]; } - ); + }); for (int[] nb : neighbor) { row = nb[0]; column = nb[1]; grid[row][column] = count; - if ( - !orphanDetected(count, row, column) && - solve(row, column, count + 1) - ) { + if (!orphanDetected(count, row, column) && solve(row, column, count + 1)) { return true; } grid[row][column] = 0; @@ -109,7 +104,7 @@ public class KnightsTour { int y = m[1]; if (grid[row + y][column + x] == 0) { int num = countNeighbors(row + y, column + x); - neighbour.add(new int[] { row + y, column + x, num }); + neighbour.add(new int[] {row + y, column + x, num}); } } return neighbour; diff --git a/src/main/java/com/thealgorithms/backtracking/MazeRecursion.java b/src/main/java/com/thealgorithms/backtracking/MazeRecursion.java index 0e1cd308..d66d1482 100644 --- a/src/main/java/com/thealgorithms/backtracking/MazeRecursion.java +++ b/src/main/java/com/thealgorithms/backtracking/MazeRecursion.java @@ -51,9 +51,7 @@ public class MazeRecursion { setWay2(map2, 1, 1); // Print out the new map1, with the ball footprint - System.out.println( - "After the ball goes through the map1,show the current map1 condition" - ); + System.out.println("After the ball goes through the map1,show the current map1 condition"); for (int i = 0; i < 8; i++) { for (int j = 0; j < 7; j++) { System.out.print(map[i][j] + " "); @@ -62,9 +60,7 @@ public class MazeRecursion { } // Print out the new map2, with the ball footprint - System.out.println( - "After the ball goes through the map2,show the current map2 condition" - ); + System.out.println("After the ball goes through the map2,show the current map2 condition"); for (int i = 0; i < 8; i++) { for (int j = 0; j < 7; j++) { System.out.print(map2[i][j] + " "); @@ -85,7 +81,7 @@ public class MazeRecursion { * means the ball has gone through the path but this path is dead end * 5. We will need strategy for the ball to pass through the maze for example: * Down -> Right -> Up -> Left, if the path doesn't work, then backtrack - * + * * @author OngLipWei * @version Jun 23, 2021 11:36:14 AM * @param map The maze @@ -99,7 +95,8 @@ public class MazeRecursion { } if (map[i][j] == 0) { // if the ball haven't gone through this point // then the ball follows the move strategy : down -> right -> up -> left - map[i][j] = 2; // we assume that this path is feasible first, set the current point to 2 first。 + map[i][j] = 2; // we assume that this path is feasible first, set the current point to 2 + // first。 if (setWay(map, i + 1, j)) { // go down return true; } else if (setWay(map, i, j + 1)) { // go right @@ -129,7 +126,8 @@ public class MazeRecursion { } if (map[i][j] == 0) { // if the ball haven't gone through this point // then the ball follows the move strategy : up->right->down->left - map[i][j] = 2; // we assume that this path is feasible first, set the current point to 2 first。 + map[i][j] = 2; // we assume that this path is feasible first, set the current point to 2 + // first。 if (setWay2(map, i - 1, j)) { // go up return true; } else if (setWay2(map, i, j + 1)) { // go right diff --git a/src/main/java/com/thealgorithms/backtracking/NQueens.java b/src/main/java/com/thealgorithms/backtracking/NQueens.java index a567c57b..6d45a73a 100644 --- a/src/main/java/com/thealgorithms/backtracking/NQueens.java +++ b/src/main/java/com/thealgorithms/backtracking/NQueens.java @@ -47,14 +47,8 @@ public class NQueens { List> arrangements = new ArrayList>(); getSolution(queens, arrangements, new int[queens], 0); if (arrangements.isEmpty()) { - System.out.println( - "There is no way to place " + - queens + - " queens on board of size " + - queens + - "x" + - queens - ); + System.out.println("There is no way to place " + queens + " queens on board of size " + + queens + "x" + queens); } else { System.out.println("Arrangement for placing " + queens + " queens"); } @@ -73,11 +67,7 @@ public class NQueens { * @param columnIndex: This is the column in which queen is being placed */ private static void getSolution( - int boardSize, - List> solutions, - int[] columns, - int columnIndex - ) { + int boardSize, List> solutions, int[] columns, int columnIndex) { if (columnIndex == boardSize) { // this means that all queens have been placed List sol = new ArrayList(); @@ -96,7 +86,8 @@ public class NQueens { for (int rowIndex = 0; rowIndex < boardSize; rowIndex++) { columns[columnIndex] = rowIndex; if (isPlacedCorrectly(columns, rowIndex, columnIndex)) { - // If queen is placed successfully at rowIndex in column=columnIndex then try placing queen in next column + // If queen is placed successfully at rowIndex in column=columnIndex then try + // placing queen in next column getSolution(boardSize, solutions, columns, columnIndex + 1); } } @@ -111,11 +102,7 @@ public class NQueens { * @param columnIndex: column in which queen is being placed * @return true: if queen can be placed safely false: otherwise */ - private static boolean isPlacedCorrectly( - int[] columns, - int rowIndex, - int columnIndex - ) { + private static boolean isPlacedCorrectly(int[] columns, int rowIndex, int columnIndex) { for (int i = 0; i < columnIndex; i++) { int diff = Math.abs(columns[i] - rowIndex); if (diff == 0 || columnIndex - i == diff) { diff --git a/src/main/java/com/thealgorithms/backtracking/PowerSum.java b/src/main/java/com/thealgorithms/backtracking/PowerSum.java index dc473858..72af17d4 100644 --- a/src/main/java/com/thealgorithms/backtracking/PowerSum.java +++ b/src/main/java/com/thealgorithms/backtracking/PowerSum.java @@ -1,11 +1,10 @@ package com.thealgorithms.backtracking; - /* * Problem Statement : - * Find the number of ways that a given integer, N , can be expressed as the sum of the Xth powers of unique, natural numbers. - * For example, if N=100 and X=3, we have to find all combinations of unique cubes adding up to 100. The only solution is 1^3+2^3+3^3+4^3. - * Therefore output will be 1. + * Find the number of ways that a given integer, N , can be expressed as the sum of the Xth powers + * of unique, natural numbers. For example, if N=100 and X=3, we have to find all combinations of + * unique cubes adding up to 100. The only solution is 1^3+2^3+3^3+4^3. Therefore output will be 1. */ public class PowerSum { @@ -16,26 +15,29 @@ public class PowerSum { return count; } - //here i is the natural number which will be raised by X and added in sum. + // here i is the natural number which will be raised by X and added in sum. public void Sum(int N, int X, int i) { - //if sum is equal to N that is one of our answer and count is increased. + // if sum is equal to N that is one of our answer and count is increased. if (sum == N) { count++; return; - } //we will be adding next natural number raised to X only if on adding it in sum the result is less than N. + } // we will be adding next natural number raised to X only if on adding it in sum the + // result is less than N. else if (sum + power(i, X) <= N) { sum += power(i, X); Sum(N, X, i + 1); - //backtracking and removing the number added last since no possible combination is there with it. + // backtracking and removing the number added last since no possible combination is + // there with it. sum -= power(i, X); } if (power(i, X) < N) { - //calling the sum function with next natural number after backtracking if when it is raised to X is still less than X. + // calling the sum function with next natural number after backtracking if when it is + // raised to X is still less than X. Sum(N, X, i + 1); } } - //creating a separate power function so that it can be used again and again when required. + // creating a separate power function so that it can be used again and again when required. private int power(int a, int b) { return (int) Math.pow(a, b); } diff --git a/src/main/java/com/thealgorithms/backtracking/WordSearch.java b/src/main/java/com/thealgorithms/backtracking/WordSearch.java index affac0ee..4ab81bfd 100644 --- a/src/main/java/com/thealgorithms/backtracking/WordSearch.java +++ b/src/main/java/com/thealgorithms/backtracking/WordSearch.java @@ -1,13 +1,12 @@ package com.thealgorithms.backtracking; - /* Word Search Problem (https://en.wikipedia.org/wiki/Word_search) Given an m x n grid of characters board and a string word, return true if word exists in the grid. -The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or -vertically neighboring. The same letter cell may not be used more than once. +The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are +those horizontally or vertically neighboring. The same letter cell may not be used more than once. For example, Given board = @@ -27,8 +26,8 @@ word = "ABCB", -> returns false. Depth First Search in matrix (as multiple sources possible) with backtracking like finding cycle in a directed graph. Maintain a record of path - Tx = O(m * n * 3^L): for each cell, we look at 3 options (not 4 as that one will be visited), we do it L times - Sx = O(L) : stack size is max L + Tx = O(m * n * 3^L): for each cell, we look at 3 options (not 4 as that one will be visited), we + do it L times Sx = O(L) : stack size is max L */ public class WordSearch { @@ -52,8 +51,7 @@ public class WordSearch { int yi = y + dy[i]; if (isValid(xi, yi) && board[xi][yi] == word.charAt(nextIdx) && !visited[xi][yi]) { boolean exists = doDFS(xi, yi, nextIdx + 1); - if (exists) - return true; + if (exists) return true; } } visited[x][y] = false; @@ -68,12 +66,10 @@ public class WordSearch { if (board[i][j] == word.charAt(0)) { visited = new boolean[board.length][board[0].length]; boolean exists = doDFS(i, j, 1); - if (exists) - return true; + if (exists) return true; } } } return false; } } - diff --git a/src/main/java/com/thealgorithms/ciphers/AES.java b/src/main/java/com/thealgorithms/ciphers/AES.java index c5cb286c..46886cbc 100644 --- a/src/main/java/com/thealgorithms/ciphers/AES.java +++ b/src/main/java/com/thealgorithms/ciphers/AES.java @@ -2395,9 +2395,7 @@ public class AES { // apply S-Box to all 8-Bit Substrings for (int i = 0; i < 4; i++) { - StringBuilder currentByteBits = new StringBuilder( - rBytes.substring(i * 2, (i + 1) * 2) - ); + StringBuilder currentByteBits = new StringBuilder(rBytes.substring(i * 2, (i + 1) * 2)); int currentByte = Integer.parseInt(currentByteBits.toString(), 16); currentByte = SBOX[currentByte]; @@ -2407,8 +2405,7 @@ public class AES { currentByte = currentByte ^ RCON[rconCounter]; } - currentByteBits = - new StringBuilder(Integer.toHexString(currentByte)); + currentByteBits = new StringBuilder(Integer.toHexString(currentByte)); // Add zero padding while (currentByteBits.length() < 2) { @@ -2416,12 +2413,8 @@ public class AES { } // replace bytes in original string - rBytes = - new StringBuilder( - rBytes.substring(0, i * 2) + - currentByteBits + - rBytes.substring((i + 1) * 2) - ); + rBytes = new StringBuilder( + rBytes.substring(0, i * 2) + currentByteBits + rBytes.substring((i + 1) * 2)); } // t = new BigInteger(rBytes, 16); @@ -2438,16 +2431,16 @@ public class AES { public static BigInteger[] keyExpansion(BigInteger initialKey) { BigInteger[] roundKeys = { initialKey, - BigInteger.ZERO, - BigInteger.ZERO, - BigInteger.ZERO, - BigInteger.ZERO, - BigInteger.ZERO, - BigInteger.ZERO, - BigInteger.ZERO, - BigInteger.ZERO, - BigInteger.ZERO, - BigInteger.ZERO, + BigInteger.ZERO, + BigInteger.ZERO, + BigInteger.ZERO, + BigInteger.ZERO, + BigInteger.ZERO, + BigInteger.ZERO, + BigInteger.ZERO, + BigInteger.ZERO, + BigInteger.ZERO, + BigInteger.ZERO, }; // initialize rcon iteration @@ -2455,23 +2448,18 @@ public class AES { for (int i = 1; i < 11; i++) { // get the previous 32 bits the key - BigInteger t = - roundKeys[i - 1].remainder(new BigInteger("100000000", 16)); + 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) - ) + roundKeys[i - 1] + .remainder(new BigInteger("10000000000000000", 16)) .divide(new BigInteger("100000000", 16)), - roundKeys[i - 1].remainder( - new BigInteger("1000000000000000000000000", 16) - ) + roundKeys[i - 1] + .remainder(new BigInteger("1000000000000000000000000", 16)) .divide(new BigInteger("10000000000000000", 16)), - roundKeys[i - 1].divide( - new BigInteger("1000000000000000000000000", 16) - ), + roundKeys[i - 1].divide(new BigInteger("1000000000000000000000000", 16)), }; // run schedule core @@ -2527,9 +2515,7 @@ public class AES { public static BigInteger mergeCellsIntoBlock(int[] cells) { StringBuilder blockBits = new StringBuilder(); for (int i = 0; i < 16; i++) { - StringBuilder cellBits = new StringBuilder( - Integer.toBinaryString(cells[i]) - ); + StringBuilder cellBits = new StringBuilder(Integer.toBinaryString(cells[i])); // Append leading 0 for full "8-bit" strings while (cellBits.length() < 8) { @@ -2545,10 +2531,7 @@ public class AES { /** * @return ciphertext XOR key */ - public static BigInteger addRoundKey( - BigInteger ciphertext, - BigInteger key - ) { + public static BigInteger addRoundKey(BigInteger ciphertext, BigInteger key) { return ciphertext.xor(key); } @@ -2669,14 +2652,10 @@ public class AES { 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]]; + 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); } @@ -2697,26 +2676,13 @@ public class AES { 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]]; + 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); } @@ -2780,9 +2746,7 @@ public class AES { 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 :" - ); + System.out.println("Enter (e) letter for encrpyt or (d) letter for decrypt :"); char choice = input.nextLine().charAt(0); String in; switch (choice) { diff --git a/src/main/java/com/thealgorithms/ciphers/AESEncryption.java b/src/main/java/com/thealgorithms/ciphers/AESEncryption.java index 051b34c2..c010d532 100644 --- a/src/main/java/com/thealgorithms/ciphers/AESEncryption.java +++ b/src/main/java/com/thealgorithms/ciphers/AESEncryption.java @@ -1,10 +1,10 @@ package com.thealgorithms.ciphers; +import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.*; import javax.crypto.spec.GCMParameterSpec; -import java.security.InvalidAlgorithmParameterException; /** * This example program shows how AES encryption and decryption can be done in @@ -29,12 +29,8 @@ public class AESEncryption { 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("AES Key (Hex Form):" + bytesToHex(secKey.getEncoded())); + System.out.println("Encrypted Text (Hex Form):" + bytesToHex(cipherText)); System.out.println("Descrypted Text:" + decryptedText); } @@ -45,8 +41,7 @@ public class AESEncryption { * @return secKey (Secret key that we encrypt using it) * @throws NoSuchAlgorithmException (from KeyGenrator) */ - public static SecretKey getSecretEncryptionKey() - throws NoSuchAlgorithmException { + public static SecretKey getSecretEncryptionKey() throws NoSuchAlgorithmException { KeyGenerator aesKeyGenerator = KeyGenerator.getInstance("AES"); aesKeyGenerator.init(128); // The AES key size in number of bits return aesKeyGenerator.generateKey(); @@ -63,7 +58,8 @@ public class AESEncryption { * @throws IllegalBlockSizeException (from Cipher) */ public static byte[] encryptText(String plainText, SecretKey secKey) - throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { + throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, + IllegalBlockSizeException, BadPaddingException { // AES defaults to AES/ECB/PKCS5Padding in Java 7 aesCipher = Cipher.getInstance("AES/GCM/NoPadding"); aesCipher.init(Cipher.ENCRYPT_MODE, secKey); @@ -76,8 +72,8 @@ public class AESEncryption { * @return plainText */ public static String decryptText(byte[] byteCipherText, SecretKey secKey) - throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, - IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException { + throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, + IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException { // AES defaults to AES/ECB/PKCS5Padding in Java 7 Cipher decryptionCipher = Cipher.getInstance("AES/GCM/NoPadding"); GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, aesCipher.getIV()); diff --git a/src/main/java/com/thealgorithms/ciphers/AffineCipher.java b/src/main/java/com/thealgorithms/ciphers/AffineCipher.java index a6fe0ab9..9ff63ddf 100644 --- a/src/main/java/com/thealgorithms/ciphers/AffineCipher.java +++ b/src/main/java/com/thealgorithms/ciphers/AffineCipher.java @@ -15,8 +15,7 @@ class AffineCipher { {here x is msg[i] and m is 26} and added 'A' to bring it in range of ascii alphabet[ 65-90 | A-Z ] */ if (msg[i] != ' ') { - cipher = - cipher + (char) ((((a * (msg[i] - 'A')) + b) % 26) + 'A'); + cipher = cipher + (char) ((((a * (msg[i] - 'A')) + b) % 26) + 'A'); } else { // else simply append space character cipher += msg[i]; } @@ -29,8 +28,8 @@ class AffineCipher { int a_inv = 0; int flag = 0; - //Find a^-1 (the multiplicative inverse of a - //in the group of integers modulo m.) + // Find a^-1 (the multiplicative inverse of a + // in the group of integers modulo m.) for (int i = 0; i < 26; i++) { flag = (a * i) % 26; @@ -45,12 +44,8 @@ class AffineCipher { {here x is cipher[i] and m is 26} and added 'A' to bring it in range of ASCII alphabet[ 65-90 | A-Z ] */ if (cipher.charAt(i) != ' ') { - msg = - msg + - (char) ( - ((a_inv * ((cipher.charAt(i) + 'A' - b)) % 26)) + 'A' - ); - } else { //else simply append space character + msg = msg + (char) (((a_inv * ((cipher.charAt(i) + 'A' - b)) % 26)) + 'A'); + } else { // else simply append space character msg += cipher.charAt(i); } } @@ -67,8 +62,6 @@ class AffineCipher { System.out.println("Encrypted Message is : " + cipherText); // Calling Decryption function - System.out.println( - "Decrypted Message is: " + decryptCipher(cipherText) - ); + System.out.println("Decrypted Message is: " + decryptCipher(cipherText)); } } diff --git a/src/main/java/com/thealgorithms/ciphers/Blowfish.java b/src/main/java/com/thealgorithms/ciphers/Blowfish.java index 8864fc75..bce7f699 100644 --- a/src/main/java/com/thealgorithms/ciphers/Blowfish.java +++ b/src/main/java/com/thealgorithms/ciphers/Blowfish.java @@ -10,7 +10,7 @@ package com.thealgorithms.ciphers; public class Blowfish { - //Initializing substitution boxes + // Initializing substitution boxes String[][] S = { { "d1310ba6", @@ -1046,7 +1046,7 @@ public class Blowfish { }, }; - //Initializing subkeys with digits of pi + // Initializing subkeys with digits of pi String[] P = { "243f6a88", "85a308d3", @@ -1068,7 +1068,7 @@ public class Blowfish { "8979fb1b", }; - //Initializing modVal to 2^32 + // Initializing modVal to 2^32 long modVal = 4294967296L; /** @@ -1098,7 +1098,8 @@ public class Blowfish { * This method returns hexadecimal representation of the binary number passed as parameter * * @param binary Number for which hexadecimal representation is required - * @return String object which is a hexadecimal representation of the binary number passed as parameter + * @return String object which is a hexadecimal representation of the binary number passed as + * parameter */ private String binToHex(String binary) { long num = Long.parseUnsignedLong(binary, 2); @@ -1109,7 +1110,8 @@ public class Blowfish { } /** - * This method returns a string obtained by XOR-ing two strings of same length passed a method parameters + * This method returns a string obtained by XOR-ing two strings of same length passed a method + * parameters * * @param String a and b are string objects which will be XORed and are to be of same length * @return String object obtained by XOR operation on String a and String b @@ -1118,17 +1120,19 @@ public class Blowfish { a = hexToBin(a); b = hexToBin(b); String ans = ""; - for (int i = 0; i < a.length(); i++) ans += - (char) (((a.charAt(i) - '0') ^ (b.charAt(i) - '0')) + '0'); + for (int i = 0; i < a.length(); i++) + ans += (char) (((a.charAt(i) - '0') ^ (b.charAt(i) - '0')) + '0'); ans = binToHex(ans); return ans; } /** - * This method returns addition of two hexadecimal numbers passed as parameters and moded with 2^32 + * This method returns addition of two hexadecimal numbers passed as parameters and moded with + * 2^32 * * @param String a and b are hexadecimal numbers - * @return String object which is a is addition that is then moded with 2^32 of hex numbers passed as parameters + * @return String object which is a is addition that is then moded with 2^32 of hex numbers + * passed as parameters */ private String addBin(String a, String b) { String ans = ""; @@ -1140,20 +1144,17 @@ public class Blowfish { return ans.substring(ans.length() - 8); } - /*F-function splits the 32-bit input into four 8-bit quarters - and uses the quarters as input to the S-boxes. - The S-boxes accept 8-bit input and produce 32-bit output. - The outputs are added modulo 232 and XORed to produce the final 32-bit output - */ + /*F-function splits the 32-bit input into four 8-bit quarters + and uses the quarters as input to the S-boxes. + The S-boxes accept 8-bit input and produce 32-bit output. + The outputs are added modulo 232 and XORed to produce the final 32-bit output + */ private String f(String plainText) { String[] a = new String[4]; String ans = ""; for (int i = 0; i < 8; i += 2) { - //column number for S-box is a 8-bit value - long col = Long.parseUnsignedLong( - hexToBin(plainText.substring(i, i + 2)), - 2 - ); + // column number for S-box is a 8-bit value + long col = Long.parseUnsignedLong(hexToBin(plainText.substring(i, i + 2)), 2); a[i / 2] = S[i / 2][(int) col]; } ans = addBin(a[0], a[1]); @@ -1162,30 +1163,30 @@ public class Blowfish { return ans; } - //generate subkeys + // generate subkeys private void keyGenerate(String key) { int j = 0; for (int i = 0; i < P.length; i++) { - //XOR-ing 32-bit parts of the key with initial subkeys + // XOR-ing 32-bit parts of the key with initial subkeys P[i] = xor(P[i], key.substring(j, j + 8)); j = (j + 8) % key.length(); } } - //round function + // round function private String round(int time, String plainText) { String left, right; left = plainText.substring(0, 8); right = plainText.substring(8, 16); left = xor(left, P[time]); - //output from F function + // output from F function String fOut = f(left); right = xor(fOut, right); - //swap left and right + // swap left and right return right + left; } @@ -1198,12 +1199,12 @@ public class Blowfish { * @return String cipherText is the encrypted value */ String encrypt(String plainText, String key) { - //generating key + // generating key keyGenerate(key); for (int i = 0; i < 16; i++) plainText = round(i, plainText); - //postprocessing + // postprocessing String right = plainText.substring(0, 8); String left = plainText.substring(8, 16); right = xor(right, P[16]); @@ -1220,12 +1221,12 @@ public class Blowfish { * @return String plainText is the decrypted text */ String decrypt(String cipherText, String key) { - //generating key + // generating key keyGenerate(key); for (int i = 17; i > 1; i--) cipherText = round(i, cipherText); - //postprocessing + // postprocessing String right = cipherText.substring(0, 8); String left = cipherText.substring(8, 16); right = xor(right, P[1]); diff --git a/src/main/java/com/thealgorithms/ciphers/Caesar.java b/src/main/java/com/thealgorithms/ciphers/Caesar.java index a5f89fba..6011909a 100644 --- a/src/main/java/com/thealgorithms/ciphers/Caesar.java +++ b/src/main/java/com/thealgorithms/ciphers/Caesar.java @@ -23,16 +23,19 @@ public class Caesar { final int length = message.length(); for (int i = 0; i < length; i++) { - // int current = message.charAt(i); //using char to shift characters because ascii + // 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)) { current += shift; - encoded.append((char) (current > 'Z' ? current - 26 : current)); // 26 = number of latin letters + encoded.append(( + char) (current > 'Z' ? current - 26 : current)); // 26 = number of latin letters } else if (isSmallLatinLetter(current)) { current += shift; - encoded.append((char) (current > 'z' ? current - 26 : current)); // 26 = number of latin letters + encoded.append(( + char) (current > 'z' ? current - 26 : current)); // 26 = number of latin letters } else { encoded.append(current); } @@ -56,10 +59,12 @@ public class Caesar { char current = encryptedMessage.charAt(i); if (isCapitalLatinLetter(current)) { current -= shift; - decoded.append((char) (current < 'A' ? current + 26 : current)); // 26 = number of latin letters + decoded.append(( + char) (current < 'A' ? current + 26 : current)); // 26 = number of latin letters } else if (isSmallLatinLetter(current)) { current -= shift; - decoded.append((char) (current < 'a' ? current + 26 : current)); // 26 = number of latin letters + decoded.append(( + char) (current < 'a' ? current + 26 : current)); // 26 = number of latin letters } else { decoded.append(current); } diff --git a/src/main/java/com/thealgorithms/ciphers/ColumnarTranspositionCipher.java b/src/main/java/com/thealgorithms/ciphers/ColumnarTranspositionCipher.java index 35f15e58..70b1f7ea 100644 --- a/src/main/java/com/thealgorithms/ciphers/ColumnarTranspositionCipher.java +++ b/src/main/java/com/thealgorithms/ciphers/ColumnarTranspositionCipher.java @@ -12,9 +12,8 @@ public class ColumnarTranspositionCipher { private static String keyword; private static Object[][] table; private static String abecedarium; - public static final String ABECEDARIUM = - "abcdefghijklmnopqrstuvwxyzABCDEFG" + - "HIJKLMNOPQRSTUVWXYZ0123456789,.;:-@"; + public static final String ABECEDARIUM = "abcdefghijklmnopqrstuvwxyzABCDEFG" + + "HIJKLMNOPQRSTUVWXYZ0123456789,.;:-@"; private static final String ENCRYPTION_FIELD = "≈"; private static final char ENCRYPTION_FIELD_CHAR = '≈'; @@ -50,14 +49,10 @@ public class ColumnarTranspositionCipher { * @return a String with the word encrypted by the Columnar Transposition * Cipher Rule */ - public static String encrpyter( - String word, - String keyword, - String abecedarium - ) { + public static String encrpyter(String word, String keyword, String abecedarium) { ColumnarTranspositionCipher.keyword = keyword; - ColumnarTranspositionCipher.abecedarium = - Objects.requireNonNullElse(abecedarium, ABECEDARIUM); + ColumnarTranspositionCipher.abecedarium + = Objects.requireNonNullElse(abecedarium, ABECEDARIUM); table = tableBuilder(word); Object[][] sortedTable = sortTable(table); StringBuilder wordEncrypted = new StringBuilder(); @@ -120,9 +115,7 @@ public class ColumnarTranspositionCipher { * order to respect the Columnar Transposition Cipher Rule. */ private static int numberOfRows(String word) { - if ( - word.length() / keyword.length() > word.length() / keyword.length() - ) { + if (word.length() / keyword.length() > word.length() / keyword.length()) { return (word.length() / keyword.length()) + 1; } else { return word.length() / keyword.length(); @@ -147,22 +140,12 @@ public class ColumnarTranspositionCipher { 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 - ); + 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 - ); + Object[] column = getColumn(tableSorted, tableSorted.length, i); switchColumns(tableSorted, j, i, column); } } @@ -182,11 +165,7 @@ public class ColumnarTranspositionCipher { } private static void switchColumns( - Object[][] table, - int firstColumnIndex, - int secondColumnIndex, - Object[] columnToSwitch - ) { + 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]; @@ -217,22 +196,12 @@ public class ColumnarTranspositionCipher { 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" - ); + 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("Word encrypted ->>> " + + ColumnarTranspositionCipher.encrpyter(wordBeingEncrypted, keywordForExample)); + System.out.println("Word decryped ->>> " + ColumnarTranspositionCipher.decrypter()); System.out.println("\n### Encrypted Table ###"); showTable(); } diff --git a/src/main/java/com/thealgorithms/ciphers/DES.java b/src/main/java/com/thealgorithms/ciphers/DES.java index aae8282e..b6ca8fb8 100644 --- a/src/main/java/com/thealgorithms/ciphers/DES.java +++ b/src/main/java/com/thealgorithms/ciphers/DES.java @@ -1,8 +1,9 @@ package com.thealgorithms.ciphers; /** - * This class is build to demonstrate the application of the DES-algorithm (https://en.wikipedia.org/wiki/Data_Encryption_Standard) on a - * plain English message. The supplied key must be in form of a 64 bit binary String. + * This class is build to demonstrate the application of the DES-algorithm + * (https://en.wikipedia.org/wiki/Data_Encryption_Standard) on a plain English message. The supplied + * key must be in form of a 64 bit binary String. */ public class DES { @@ -12,7 +13,8 @@ public class DES { private void sanitize(String key) { int length = key.length(); if (length != 64) { - throw new IllegalArgumentException("DES key must be supplied as a 64 character binary string"); + throw new IllegalArgumentException( + "DES key must be supplied as a 64 character binary string"); } } @@ -30,170 +32,102 @@ public class DES { sanitize(key); this.key = key; } - - //Permutation table to convert initial 64 bit key to 56 bit key - private static int[] PC1 = - { - 57, 49, 41, 33, 25, 17, 9, - 1, 58, 50, 42, 34, 26, 18, - 10, 2, 59, 51, 43, 35, 27, - 19, 11, 3, 60, 52, 44, 36, - 63, 55, 47, 39, 31, 23, 15, - 7, 62, 54, 46, 38, 30, 22, - 14, 6, 61, 53, 45, 37, 29, - 21, 13, 5, 28, 20, 12, 4 - }; - //Lookup table used to shift the initial key, in order to generate the subkeys - private static int[] KEY_SHIFTS = - { - 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 - }; + // Permutation table to convert initial 64 bit key to 56 bit key + private static int[] PC1 = {57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, + 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, + 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4}; - //Table to convert the 56 bit subkeys to 48 bit subkeys - private static int[] PC2 = - { - 14, 17, 11, 24, 1, 5, - 3, 28, 15, 6, 21, 10, - 23, 19, 12, 4, 26, 8, - 16, 7, 27, 20, 13, 2, - 41, 52, 31, 37, 47, 55, - 30, 40, 51, 45, 33, 48, - 44, 49, 39, 56, 34, 53, - 46, 42, 50, 36, 29, 32 - }; + // Lookup table used to shift the initial key, in order to generate the subkeys + private static int[] KEY_SHIFTS = {1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1}; - //Initial permutatation of each 64 but message block - private static int[] IP = - { - 58, 50, 42, 34, 26, 18, 10 , 2, - 60, 52, 44, 36, 28, 20, 12, 4, - 62, 54, 46, 38, 30, 22, 14, 6, - 64, 56, 48, 40, 32, 24, 16, 8, - 57, 49, 41, 33, 25, 17, 9, 1, - 59, 51, 43, 35, 27, 19, 11, 3, - 61, 53, 45, 37, 29, 21, 13, 5, - 63, 55, 47, 39, 31, 23, 15, 7 - }; + // Table to convert the 56 bit subkeys to 48 bit subkeys + private static int[] PC2 = {14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, + 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, + 53, 46, 42, 50, 36, 29, 32}; - //Expansion table to convert right half of message blocks from 32 bits to 48 bits - private static int[] expansion = - { - 32, 1, 2, 3, 4, 5, - 4, 5, 6, 7, 8, 9, - 8, 9, 10, 11, 12, 13, - 12, 13, 14, 15, 16, 17, - 16, 17, 18, 19, 20, 21, - 20, 21, 22, 23, 24, 25, - 24, 25, 26, 27, 28, 29, - 28, 29, 30, 31, 32, 1 - }; - - //The eight substitution boxes are defined below - private static int[][] s1 = { - {14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7}, - {0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8}, - {4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0}, - {15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13} - }; + // Initial permutatation of each 64 but message block + private static int[] IP = {58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, + 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, + 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7}; - private static int[][] s2 = { - {15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10}, - {3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5}, - {0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15}, - {13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9} - }; - - private static int[][] s3 = { - {10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8}, - {13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1}, - {13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7}, - {1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12} - }; - - private static int[][] s4 = { - {7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15}, - {13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9}, - {10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4}, - {3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14} - }; - - private static int[][] s5 = { - {2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9}, - {14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6}, - {4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14}, - {11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3} - }; - - private static int[][] s6 = { - {12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11}, - {10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8}, - {9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6}, - {4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13} - }; - - private static int[][] s7 = { - {4, 11, 2, 14, 15, 0, 8, 13 , 3, 12, 9 , 7, 5, 10, 6, 1}, - {13 , 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6}, - {1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2}, - {6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12} - }; - - private static int[][] s8 = { - {13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7}, - {1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6 ,11, 0, 14, 9, 2}, - {7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10 ,13, 15, 3, 5, 8}, - {2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6 ,11} - }; - - private static int[][][] s = {s1, s2, s3, s4, s5, s6, s7, s8}; + // Expansion table to convert right half of message blocks from 32 bits to 48 bits + private static int[] expansion = {32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13, 12, + 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25, 24, 25, 26, 27, 28, 29, + 28, 29, 30, 31, 32, 1}; - //Permutation table, used in the feistel function post s-box usage - static int[] permutation = - { - 16, 7, 20, 21, - 29, 12, 28, 17, - 1, 15, 23, 26, - 5, 18, 31, 10, - 2, 8, 24, 14, - 32, 27, 3, 9, - 19, 13, 30, 6, - 22, 11, 4, 25 - }; + // The eight substitution boxes are defined below + private static int[][] s1 = {{14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7}, + {0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8}, + {4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0}, + {15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13}}; - //Table used for final inversion of the message box after 16 rounds of Feistel Function - static int[] IPinverse = - { - 40, 8, 48, 16, 56, 24, 64, 32, - 39, 7, 47, 15, 55, 23, 63, 31, - 38, 6, 46, 14, 54, 22, 62, 30, - 37, 5, 45, 13, 53, 21, 61, 29, - 36, 4, 44, 12, 52, 20, 60, 28, - 35, 3, 43 ,11, 51, 19, 59, 27, - 34, 2, 42, 10, 50, 18, 58, 26, - 33, 1, 41, 9, 49, 17, 57, 25 - }; + private static int[][] s2 = {{15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10}, + {3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5}, + {0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15}, + {13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9}}; + + private static int[][] s3 = {{10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8}, + {13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1}, + {13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7}, + {1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12}}; + + private static int[][] s4 = {{7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15}, + {13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9}, + {10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4}, + {3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14}}; + + private static int[][] s5 = {{2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9}, + {14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6}, + {4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14}, + {11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3}}; + + private static int[][] s6 = {{12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11}, + {10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8}, + {9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6}, + {4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13}}; + + private static int[][] s7 = {{4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1}, + {13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6}, + {1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2}, + {6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12}}; + + private static int[][] s8 = {{13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7}, + {1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2}, + {7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8}, + {2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11}}; + + private static int[][][] s = {s1, s2, s3, s4, s5, s6, s7, s8}; + + // Permutation table, used in the feistel function post s-box usage + static int[] permutation = {16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, + 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25}; + + // Table used for final inversion of the message box after 16 rounds of Feistel Function + static int[] IPinverse = {40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31, 38, 6, + 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, + 43, 11, 51, 19, 59, 27, 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25}; private String[] getSubkeys(String originalKey) { - StringBuilder permutedKey = new StringBuilder(); //Initial permutation of keys via PC1 + StringBuilder permutedKey = new StringBuilder(); // Initial permutation of keys via PC1 int i, j; for (i = 0; i < 56; i++) { - permutedKey.append(originalKey.charAt(PC1[i] - 1)); + permutedKey.append(originalKey.charAt(PC1[i] - 1)); } String subKeys[] = new String[16]; String initialPermutedKey = permutedKey.toString(); String C0 = initialPermutedKey.substring(0, 28), D0 = initialPermutedKey.substring(28); - - //We will now operate on the left and right halves of the permutedKey + + // We will now operate on the left and right halves of the permutedKey for (i = 0; i < 16; i++) { String Cn = C0.substring(KEY_SHIFTS[i]) + C0.substring(0, KEY_SHIFTS[i]); String Dn = D0.substring(KEY_SHIFTS[i]) + D0.substring(0, KEY_SHIFTS[i]); subKeys[i] = Cn + Dn; - C0 = Cn; //Re-assign the values to create running permutation + C0 = Cn; // Re-assign the values to create running permutation D0 = Dn; } - //Let us shrink the keys to 48 bits (well, characters here) using PC2 + // Let us shrink the keys to 48 bits (well, characters here) using PC2 for (i = 0; i < 16; i++) { String key = subKeys[i]; permutedKey.setLength(0); @@ -244,16 +178,17 @@ public class DES { String mixedKey = XOR(expandedKey.toString(), key); StringBuilder substitutedString = new StringBuilder(); - //Let us now use the s-boxes to transform each 6 bit (length here) block to 4 bits + // Let us now use the s-boxes to transform each 6 bit (length here) block to 4 bits for (i = 0; i < 48; i += 6) { String block = mixedKey.substring(i, i + 6); int row = (block.charAt(0) - 48) * 2 + (block.charAt(5) - 48); - int col = (block.charAt(1) - 48) * 8 + (block.charAt(2) - 48) * 4 + (block.charAt(3) - 48) * 2 + (block.charAt(4) - 48); + int col = (block.charAt(1) - 48) * 8 + (block.charAt(2) - 48) * 4 + + (block.charAt(3) - 48) * 2 + (block.charAt(4) - 48); String substitutedBlock = pad(Integer.toBinaryString(s[i / 6][row][col]), 4); substitutedString.append(substitutedBlock); } - StringBuilder permutedString = new StringBuilder(); + StringBuilder permutedString = new StringBuilder(); for (i = 0; i < 32; i++) { permutedString.append(substitutedString.charAt(permutation[i] - 1)); } @@ -269,7 +204,7 @@ public class DES { } String L0 = permutedMessage.substring(0, 32), R0 = permutedMessage.substring(32); - //Iterate 16 times + // Iterate 16 times for (i = 0; i < 16; i++) { String Ln = R0; // Previous Right block String Rn = XOR(L0, feistel(R0, keys[i])); @@ -277,7 +212,7 @@ public class DES { R0 = Rn; } - String combinedBlock = R0 + L0; //Reverse the 16th block + String combinedBlock = R0 + L0; // Reverse the 16th block permutedMessage.setLength(0); for (i = 0; i < 64; i++) { permutedMessage.append(combinedBlock.charAt(IPinverse[i] - 1)); @@ -285,7 +220,7 @@ public class DES { return permutedMessage.toString(); } - //To decode, we follow the same process as encoding, but with reversed keys + // To decode, we follow the same process as encoding, but with reversed keys private String decryptBlock(String message, String keys[]) { String reversedKeys[] = new String[keys.length]; for (int i = 0; i < keys.length; i++) { @@ -307,7 +242,7 @@ public class DES { message = padLast(message, desiredLength); } - for (i = 0; i < l; i+= 8) { + for (i = 0; i < l; i += 8) { String block = message.substring(i, i + 8); StringBuilder bitBlock = new StringBuilder(); byte[] bytes = block.getBytes(); @@ -327,18 +262,19 @@ public class DES { StringBuilder decryptedMessage = new StringBuilder(); int l = message.length(), i, j; if (l % 64 != 0) { - throw new IllegalArgumentException("Encrypted message should be a multiple of 64 characters in length"); + throw new IllegalArgumentException( + "Encrypted message should be a multiple of 64 characters in length"); } - for (i = 0; i < l; i+= 64) { + for (i = 0; i < l; i += 64) { String block = message.substring(i, i + 64); String result = decryptBlock(block.toString(), subKeys); byte res[] = new byte[8]; - for (j = 0; j < 64; j+=8) { - res[j / 8] = (byte)Integer.parseInt(result.substring(j, j + 8), 2); + for (j = 0; j < 64; j += 8) { + res[j / 8] = (byte) Integer.parseInt(result.substring(j, j + 8), 2); } decryptedMessage.append(new String(res)); } - return decryptedMessage.toString().replace("\0", ""); // Get rid of the null bytes used for padding + return decryptedMessage.toString().replace( + "\0", ""); // Get rid of the null bytes used for padding } - } diff --git a/src/main/java/com/thealgorithms/ciphers/HillCipher.java b/src/main/java/com/thealgorithms/ciphers/HillCipher.java index ffc7e08b..a3226cef 100644 --- a/src/main/java/com/thealgorithms/ciphers/HillCipher.java +++ b/src/main/java/com/thealgorithms/ciphers/HillCipher.java @@ -4,10 +4,11 @@ import java.util.Scanner; /* * Java Implementation of Hill Cipher - * Hill cipher is a polyalphabetic substitution cipher. Each letter is represented by a number belonging to the set Z26 where A=0 , B=1, ..... Z=25. - * To encrypt a message, each block of n letters (since matrix size is n x n) is multiplied by an invertible n × n matrix, against modulus 26. - * To decrypt the message, each block is multiplied by the inverse of the matrix used for encryption. - * The cipher key and plaintext/ciphertext are user inputs. + * Hill cipher is a polyalphabetic substitution cipher. Each letter is represented by a number + * belonging to the set Z26 where A=0 , B=1, ..... Z=25. To encrypt a message, each block of n + * letters (since matrix size is n x n) is multiplied by an invertible n × n matrix, against + * modulus 26. To decrypt the message, each block is multiplied by the inverse of the matrix used + * for encryption. The cipher key and plaintext/ciphertext are user inputs. * @author Ojasva Jain */ public class HillCipher { @@ -28,7 +29,7 @@ public class HillCipher { keyMatrix[i][j] = userInput.nextInt(); } } - //check if det = 0 + // check if det = 0 validateDeterminant(keyMatrix, matrixSize); int[][] messageVector = new int[matrixSize][1]; @@ -62,7 +63,7 @@ public class HillCipher { System.out.println("Ciphertext: " + CipherText); } - //Following function decrypts a message + // Following function decrypts a message static void decrypt(String message) { message = message.toUpperCase(); // Get key matrix @@ -75,10 +76,10 @@ public class HillCipher { keyMatrix[i][j] = userInput.nextInt(); } } - //check if det = 0 + // check if det = 0 validateDeterminant(keyMatrix, n); - //solving for the required plaintext message + // solving for the required plaintext message int[][] messageVector = new int[n][1]; String PlainText = ""; int[][] plainMatrix = new int[n][1]; @@ -157,9 +158,7 @@ public class HillCipher { static void validateDeterminant(int[][] keyMatrix, int n) { if (determinant(keyMatrix, n) % 26 == 0) { - System.out.println( - "Invalid key, as determinant = 0. Program Terminated" - ); + System.out.println("Invalid key, as determinant = 0. Program Terminated"); } } diff --git a/src/main/java/com/thealgorithms/ciphers/Polybius.java b/src/main/java/com/thealgorithms/ciphers/Polybius.java index 30eba498..7b5a2780 100644 --- a/src/main/java/com/thealgorithms/ciphers/Polybius.java +++ b/src/main/java/com/thealgorithms/ciphers/Polybius.java @@ -7,7 +7,8 @@ package com.thealgorithms.ciphers; * Letters in alphabet takes place to two dimension table. * Encrypted text is created according to row and column in two dimension table * Decrypted text is generated by looking at the row and column respectively - * Additionally, some letters in english alphabet deliberately throws such as U because U is very similar with V + * Additionally, some letters in english alphabet deliberately throws such as U because U is very + * similar with V * * @author Hikmet ÇAKIR * @since 08-07-2022+03:00 @@ -16,11 +17,11 @@ public class Polybius { private static final char[][] key = { // 0 1 2 3 4 - /* 0 */{ 'A', 'B', 'C', 'D', 'E' }, - /* 1 */{ 'F', 'G', 'H', 'I', 'J' }, - /* 2 */{ 'K', 'L', 'M', 'N', 'O' }, - /* 3 */{ 'P', 'Q', 'R', 'S', 'T' }, - /* 4 */{ 'V', 'W', 'X', 'Y', 'Z' }, + /* 0 */ {'A', 'B', 'C', 'D', 'E'}, + /* 1 */ {'F', 'G', 'H', 'I', 'J'}, + /* 2 */ {'K', 'L', 'M', 'N', 'O'}, + /* 3 */ {'P', 'Q', 'R', 'S', 'T'}, + /* 4 */ {'V', 'W', 'X', 'Y', 'Z'}, }; private static String findLocationByCharacter(final char character) { diff --git a/src/main/java/com/thealgorithms/ciphers/RSA.java b/src/main/java/com/thealgorithms/ciphers/RSA.java index 08f4e198..e28eaecb 100644 --- a/src/main/java/com/thealgorithms/ciphers/RSA.java +++ b/src/main/java/com/thealgorithms/ciphers/RSA.java @@ -20,8 +20,7 @@ public class RSA { * @return encrypted message */ public synchronized String encrypt(String message) { - return (new BigInteger(message.getBytes())).modPow(publicKey, modulus) - .toString(); + return (new BigInteger(message.getBytes())).modPow(publicKey, modulus).toString(); } /** @@ -36,9 +35,7 @@ public class RSA { */ public synchronized String decrypt(String encryptedMessage) { return new String( - (new BigInteger(encryptedMessage)).modPow(privateKey, modulus) - .toByteArray() - ); + (new BigInteger(encryptedMessage)).modPow(privateKey, modulus).toByteArray()); } /** @@ -57,8 +54,7 @@ public class RSA { BigInteger q = new BigInteger(bits / 2, 100, r); modulus = p.multiply(q); - BigInteger m = - (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE)); + BigInteger m = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE)); publicKey = BigInteger.valueOf(3L); diff --git a/src/main/java/com/thealgorithms/ciphers/SimpleSubCipher.java b/src/main/java/com/thealgorithms/ciphers/SimpleSubCipher.java index 32b08f0c..f6c88ef7 100644 --- a/src/main/java/com/thealgorithms/ciphers/SimpleSubCipher.java +++ b/src/main/java/com/thealgorithms/ciphers/SimpleSubCipher.java @@ -82,5 +82,4 @@ public class SimpleSubCipher { return decoded.toString(); } - } diff --git a/src/main/java/com/thealgorithms/ciphers/Vigenere.java b/src/main/java/com/thealgorithms/ciphers/Vigenere.java index fe7ff8d0..1702f1ab 100644 --- a/src/main/java/com/thealgorithms/ciphers/Vigenere.java +++ b/src/main/java/com/thealgorithms/ciphers/Vigenere.java @@ -16,21 +16,9 @@ public class Vigenere { char c = message.charAt(i); if (Character.isLetter(c)) { if (Character.isUpperCase(c)) { - result.append( - (char) ( - (c + key.toUpperCase().charAt(j) - 2 * 'A') % - 26 + - 'A' - ) - ); + result.append((char) ((c + key.toUpperCase().charAt(j) - 2 * 'A') % 26 + 'A')); } else { - result.append( - (char) ( - (c + key.toLowerCase().charAt(j) - 2 * 'a') % - 26 + - 'a' - ) - ); + result.append((char) ((c + key.toLowerCase().charAt(j) - 2 * 'a') % 26 + 'a')); } } else { result.append(c); @@ -48,17 +36,9 @@ public class Vigenere { char c = message.charAt(i); if (Character.isLetter(c)) { if (Character.isUpperCase(c)) { - result.append( - (char) ( - 'Z' - (25 - (c - key.toUpperCase().charAt(j))) % 26 - ) - ); + result.append((char) ('Z' - (25 - (c - key.toUpperCase().charAt(j))) % 26)); } else { - result.append( - (char) ( - 'z' - (25 - (c - key.toLowerCase().charAt(j))) % 26 - ) - ); + result.append((char) ('z' - (25 - (c - key.toLowerCase().charAt(j))) % 26)); } } else { result.append(c); diff --git a/src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java b/src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java index b7d36db5..809f8507 100644 --- a/src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java +++ b/src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java @@ -6,7 +6,8 @@ import java.util.BitSet; public class A5Cipher { private final A5KeyStreamGenerator keyStreamGenerator; - private static final int KEY_STREAM_LENGTH = 228; // 28.5 bytes so we need to pad bytes or something + private static final int KEY_STREAM_LENGTH + = 228; // 28.5 bytes so we need to pad bytes or something public A5Cipher(BitSet sessionKey, BitSet frameCounter) { keyStreamGenerator = new A5KeyStreamGenerator(); diff --git a/src/main/java/com/thealgorithms/ciphers/a5/A5KeyStreamGenerator.java b/src/main/java/com/thealgorithms/ciphers/a5/A5KeyStreamGenerator.java index 7788efc1..148a49cf 100644 --- a/src/main/java/com/thealgorithms/ciphers/a5/A5KeyStreamGenerator.java +++ b/src/main/java/com/thealgorithms/ciphers/a5/A5KeyStreamGenerator.java @@ -9,7 +9,8 @@ public class A5KeyStreamGenerator extends CompositeLFSR { private BitSet frameCounter; private BitSet sessionKey; private static final int INITIAL_CLOCKING_CYCLES = 100; - private static final int KEY_STREAM_LENGTH = 228; // 28.5 bytes so we need to pad bytes or something + private static final int KEY_STREAM_LENGTH + = 228; // 28.5 bytes so we need to pad bytes or something @Override public void initialize(BitSet sessionKey, BitSet frameCounter) { @@ -17,9 +18,9 @@ public class A5KeyStreamGenerator extends CompositeLFSR { this.frameCounter = (BitSet) frameCounter.clone(); this.initialFrameCounter = (BitSet) frameCounter.clone(); registers.clear(); - LFSR lfsr1 = new LFSR(19, 8, new int[] { 13, 16, 17, 18 }); - LFSR lfsr2 = new LFSR(22, 10, new int[] { 20, 21 }); - LFSR lfsr3 = new LFSR(23, 10, new int[] { 7, 20, 21, 22 }); + LFSR lfsr1 = new LFSR(19, 8, new int[] {13, 16, 17, 18}); + LFSR lfsr2 = new LFSR(22, 10, new int[] {20, 21}); + LFSR lfsr3 = new LFSR(23, 10, new int[] {7, 20, 21, 22}); registers.add(lfsr1); registers.add(lfsr2); registers.add(lfsr3); @@ -31,11 +32,7 @@ public class A5KeyStreamGenerator extends CompositeLFSR { } public BitSet getNextKeyStream() { - for ( - int cycle = 1; - cycle <= INITIAL_CLOCKING_CYCLES; - ++cycle - ) this.clock(); + for (int cycle = 1; cycle <= INITIAL_CLOCKING_CYCLES; ++cycle) this.clock(); BitSet result = new BitSet(KEY_STREAM_LENGTH); for (int cycle = 1; cycle <= KEY_STREAM_LENGTH; ++cycle) { diff --git a/src/main/java/com/thealgorithms/ciphers/a5/CompositeLFSR.java b/src/main/java/com/thealgorithms/ciphers/a5/CompositeLFSR.java index 05065716..2d0309a9 100644 --- a/src/main/java/com/thealgorithms/ciphers/a5/CompositeLFSR.java +++ b/src/main/java/com/thealgorithms/ciphers/a5/CompositeLFSR.java @@ -29,12 +29,8 @@ public abstract class CompositeLFSR implements BaseLFSR { bitCount.put(false, 0); bitCount.put(true, 0); - registers.forEach(lfsr -> - bitCount.put( - lfsr.getClockBit(), - bitCount.get(lfsr.getClockBit()) + 1 - ) - ); + registers.forEach( + lfsr -> bitCount.put(lfsr.getClockBit(), bitCount.get(lfsr.getClockBit()) + 1)); return bitCount.get(false) <= bitCount.get(true); } } diff --git a/src/main/java/com/thealgorithms/ciphers/a5/Utils.java b/src/main/java/com/thealgorithms/ciphers/a5/Utils.java index b9220d11..abdd11d6 100644 --- a/src/main/java/com/thealgorithms/ciphers/a5/Utils.java +++ b/src/main/java/com/thealgorithms/ciphers/a5/Utils.java @@ -1,8 +1,9 @@ package com.thealgorithms.ciphers.a5; -// Source http://www.java2s.com/example/java-utility-method/bitset/increment-bitset-bits-int-size-9fd84.html -//package com.java2s; -//License from project: Open Source License +// Source +// http://www.java2s.com/example/java-utility-method/bitset/increment-bitset-bits-int-size-9fd84.html +// package com.java2s; +// License from project: Open Source License import java.util.BitSet; @@ -11,7 +12,7 @@ public class Utils { public static boolean increment(BitSet bits, int size) { int i = size - 1; while (i >= 0 && bits.get(i)) { - bits.set(i--, false);/*from w w w . j a v a 2s .c o m*/ + bits.set(i--, false); /*from w w w . j a v a 2s .c o m*/ } if (i < 0) { return false; diff --git a/src/main/java/com/thealgorithms/conversions/AnyBaseToAnyBase.java b/src/main/java/com/thealgorithms/conversions/AnyBaseToAnyBase.java index b5974dd6..c6450a45 100644 --- a/src/main/java/com/thealgorithms/conversions/AnyBaseToAnyBase.java +++ b/src/main/java/com/thealgorithms/conversions/AnyBaseToAnyBase.java @@ -30,13 +30,8 @@ public class AnyBaseToAnyBase { try { System.out.print("Enter number: "); n = in.next(); - System.out.print( - "Enter beginning base (between " + - MINIMUM_BASE + - " and " + - MAXIMUM_BASE + - "): " - ); + 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!"); @@ -47,12 +42,7 @@ public class AnyBaseToAnyBase { continue; } System.out.print( - "Enter end base (between " + - MINIMUM_BASE + - " and " + - MAXIMUM_BASE + - "): " - ); + "Enter end base (between " + MINIMUM_BASE + " and " + MAXIMUM_BASE + "): "); b2 = in.nextInt(); if (b2 > MAXIMUM_BASE || b2 < MINIMUM_BASE) { System.out.println("Invalid base!"); diff --git a/src/main/java/com/thealgorithms/conversions/DecimalToAnyBase.java b/src/main/java/com/thealgorithms/conversions/DecimalToAnyBase.java index df547ffb..a77be2f5 100644 --- a/src/main/java/com/thealgorithms/conversions/DecimalToAnyBase.java +++ b/src/main/java/com/thealgorithms/conversions/DecimalToAnyBase.java @@ -11,9 +11,7 @@ import java.util.ArrayList; public class DecimalToAnyBase { public static void main(String[] args) throws Exception { - BufferedReader br = new BufferedReader( - new InputStreamReader(System.in) - ); + 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(); @@ -22,15 +20,10 @@ public class DecimalToAnyBase { 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) - ); + System.out.println("Decimal Input" + + " is: " + decInput); + System.out.println("Value of " + decInput + " in base " + base + + " is: " + convertToAnyBase(decInput, base)); br.close(); } diff --git a/src/main/java/com/thealgorithms/conversions/DecimalToBinary.java b/src/main/java/com/thealgorithms/conversions/DecimalToBinary.java index c87508c6..a6119cfb 100644 --- a/src/main/java/com/thealgorithms/conversions/DecimalToBinary.java +++ b/src/main/java/com/thealgorithms/conversions/DecimalToBinary.java @@ -24,9 +24,7 @@ class DecimalToBinary { 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: " - ); + System.out.printf("Conventional conversion.%n Enter the decimal number: "); n = input.nextInt(); while (n != 0) { d = n % 2; diff --git a/src/main/java/com/thealgorithms/conversions/HexToOct.java b/src/main/java/com/thealgorithms/conversions/HexToOct.java index 2a57fbde..69707c80 100644 --- a/src/main/java/com/thealgorithms/conversions/HexToOct.java +++ b/src/main/java/com/thealgorithms/conversions/HexToOct.java @@ -61,7 +61,8 @@ public class HexToOct { hexadecnum = scan.nextLine(); // first convert hexadecimal to decimal - decnum = hex2decimal(hexadecnum); // Pass the string to the hex2decimal function and get the decimal form in + decnum = hex2decimal( + hexadecnum); // Pass the string to the hex2decimal function and get the decimal form in // variable decnum // convert decimal to octal diff --git a/src/main/java/com/thealgorithms/conversions/RgbHsvConversion.java b/src/main/java/com/thealgorithms/conversions/RgbHsvConversion.java index 4fad34ec..dc731006 100644 --- a/src/main/java/com/thealgorithms/conversions/RgbHsvConversion.java +++ b/src/main/java/com/thealgorithms/conversions/RgbHsvConversion.java @@ -19,69 +19,30 @@ public class RgbHsvConversion { // Expected RGB-values taken from https://www.rapidtables.com/convert/color/hsv-to-rgb.html // Test hsvToRgb-method - assert Arrays.equals(hsvToRgb(0, 0, 0), new int[] { 0, 0, 0 }); - assert Arrays.equals(hsvToRgb(0, 0, 1), new int[] { 255, 255, 255 }); - assert Arrays.equals(hsvToRgb(0, 1, 1), new int[] { 255, 0, 0 }); - assert Arrays.equals(hsvToRgb(60, 1, 1), new int[] { 255, 255, 0 }); - assert Arrays.equals(hsvToRgb(120, 1, 1), new int[] { 0, 255, 0 }); - assert Arrays.equals(hsvToRgb(240, 1, 1), new int[] { 0, 0, 255 }); - assert Arrays.equals(hsvToRgb(300, 1, 1), new int[] { 255, 0, 255 }); - assert Arrays.equals( - hsvToRgb(180, 0.5, 0.5), - new int[] { 64, 128, 128 } - ); - assert Arrays.equals( - hsvToRgb(234, 0.14, 0.88), - new int[] { 193, 196, 224 } - ); - assert Arrays.equals( - hsvToRgb(330, 0.75, 0.5), - new int[] { 128, 32, 80 } - ); + assert Arrays.equals(hsvToRgb(0, 0, 0), new int[] {0, 0, 0}); + assert Arrays.equals(hsvToRgb(0, 0, 1), new int[] {255, 255, 255}); + assert Arrays.equals(hsvToRgb(0, 1, 1), new int[] {255, 0, 0}); + assert Arrays.equals(hsvToRgb(60, 1, 1), new int[] {255, 255, 0}); + assert Arrays.equals(hsvToRgb(120, 1, 1), new int[] {0, 255, 0}); + assert Arrays.equals(hsvToRgb(240, 1, 1), new int[] {0, 0, 255}); + assert Arrays.equals(hsvToRgb(300, 1, 1), new int[] {255, 0, 255}); + assert Arrays.equals(hsvToRgb(180, 0.5, 0.5), new int[] {64, 128, 128}); + assert Arrays.equals(hsvToRgb(234, 0.14, 0.88), new int[] {193, 196, 224}); + assert Arrays.equals(hsvToRgb(330, 0.75, 0.5), new int[] {128, 32, 80}); // Test rgbToHsv-method // approximate-assertions needed because of small deviations due to converting between // int-values and double-values. - assert approximatelyEqualHsv( - rgbToHsv(0, 0, 0), - new double[] { 0, 0, 0 } - ); - assert approximatelyEqualHsv( - rgbToHsv(255, 255, 255), - new double[] { 0, 0, 1 } - ); - assert approximatelyEqualHsv( - rgbToHsv(255, 0, 0), - new double[] { 0, 1, 1 } - ); - assert approximatelyEqualHsv( - rgbToHsv(255, 255, 0), - new double[] { 60, 1, 1 } - ); - assert approximatelyEqualHsv( - rgbToHsv(0, 255, 0), - new double[] { 120, 1, 1 } - ); - assert approximatelyEqualHsv( - rgbToHsv(0, 0, 255), - new double[] { 240, 1, 1 } - ); - assert approximatelyEqualHsv( - rgbToHsv(255, 0, 255), - new double[] { 300, 1, 1 } - ); - assert approximatelyEqualHsv( - rgbToHsv(64, 128, 128), - new double[] { 180, 0.5, 0.5 } - ); - assert approximatelyEqualHsv( - rgbToHsv(193, 196, 224), - new double[] { 234, 0.14, 0.88 } - ); - assert approximatelyEqualHsv( - rgbToHsv(128, 32, 80), - new double[] { 330, 0.75, 0.5 } - ); + assert approximatelyEqualHsv(rgbToHsv(0, 0, 0), new double[] {0, 0, 0}); + assert approximatelyEqualHsv(rgbToHsv(255, 255, 255), new double[] {0, 0, 1}); + assert approximatelyEqualHsv(rgbToHsv(255, 0, 0), new double[] {0, 1, 1}); + assert approximatelyEqualHsv(rgbToHsv(255, 255, 0), new double[] {60, 1, 1}); + assert approximatelyEqualHsv(rgbToHsv(0, 255, 0), new double[] {120, 1, 1}); + assert approximatelyEqualHsv(rgbToHsv(0, 0, 255), new double[] {240, 1, 1}); + assert approximatelyEqualHsv(rgbToHsv(255, 0, 255), new double[] {300, 1, 1}); + assert approximatelyEqualHsv(rgbToHsv(64, 128, 128), new double[] {180, 0.5, 0.5}); + assert approximatelyEqualHsv(rgbToHsv(193, 196, 224), new double[] {234, 0.14, 0.88}); + assert approximatelyEqualHsv(rgbToHsv(128, 32, 80), new double[] {330, 0.75, 0.5}); } /** @@ -94,35 +55,23 @@ public class RgbHsvConversion { */ public static int[] hsvToRgb(double hue, double saturation, double value) { if (hue < 0 || hue > 360) { - throw new IllegalArgumentException( - "hue should be between 0 and 360" - ); + throw new IllegalArgumentException("hue should be between 0 and 360"); } if (saturation < 0 || saturation > 1) { - throw new IllegalArgumentException( - "saturation should be between 0 and 1" - ); + throw new IllegalArgumentException("saturation should be between 0 and 1"); } if (value < 0 || value > 1) { - throw new IllegalArgumentException( - "value should be between 0 and 1" - ); + throw new IllegalArgumentException("value should be between 0 and 1"); } double chroma = value * saturation; double hueSection = hue / 60; - double secondLargestComponent = - chroma * (1 - Math.abs(hueSection % 2 - 1)); + double secondLargestComponent = chroma * (1 - Math.abs(hueSection % 2 - 1)); double matchValue = value - chroma; - return getRgbBySection( - hueSection, - chroma, - matchValue, - secondLargestComponent - ); + return getRgbBySection(hueSection, chroma, matchValue, secondLargestComponent); } /** @@ -135,21 +84,15 @@ public class RgbHsvConversion { */ public static double[] rgbToHsv(int red, int green, int blue) { if (red < 0 || red > 255) { - throw new IllegalArgumentException( - "red should be between 0 and 255" - ); + throw new IllegalArgumentException("red should be between 0 and 255"); } if (green < 0 || green > 255) { - throw new IllegalArgumentException( - "green should be between 0 and 255" - ); + throw new IllegalArgumentException("green should be between 0 and 255"); } if (blue < 0 || blue > 255) { - throw new IllegalArgumentException( - "blue should be between 0 and 255" - ); + throw new IllegalArgumentException("blue should be between 0 and 255"); } double dRed = (double) red / 255; @@ -172,7 +115,7 @@ public class RgbHsvConversion { hue = (hue + 360) % 360; - return new double[] { hue, saturation, value }; + return new double[] {hue, saturation, value}; } private static boolean approximatelyEqualHsv(double[] hsv1, double[] hsv2) { @@ -184,11 +127,7 @@ public class RgbHsvConversion { } private static int[] getRgbBySection( - double hueSection, - double chroma, - double matchValue, - double secondLargestComponent - ) { + double hueSection, double chroma, double matchValue, double secondLargestComponent) { int red; int green; int blue; @@ -219,7 +158,7 @@ public class RgbHsvConversion { blue = convertToInt(secondLargestComponent + matchValue); } - return new int[] { red, green, blue }; + return new int[] {red, green, blue}; } private static int convertToInt(double input) { diff --git a/src/main/java/com/thealgorithms/conversions/TurkishToLatinConversion.java b/src/main/java/com/thealgorithms/conversions/TurkishToLatinConversion.java index 81c8d9bd..39e0c443 100644 --- a/src/main/java/com/thealgorithms/conversions/TurkishToLatinConversion.java +++ b/src/main/java/com/thealgorithms/conversions/TurkishToLatinConversion.java @@ -58,11 +58,8 @@ public class TurkishToLatinConversion { 'G', }; for (int i = 0; i < turkishChars.length; i++) { - param = - param.replaceAll( - new String(new char[] { turkishChars[i] }), - new String(new char[] { latinChars[i] }) - ); + param = param.replaceAll( + new String(new char[] {turkishChars[i]}), new String(new char[] {latinChars[i]})); } return param; } diff --git a/src/main/java/com/thealgorithms/datastructures/buffers/CircularBuffer.java b/src/main/java/com/thealgorithms/datastructures/buffers/CircularBuffer.java index 96c72fc0..5e1c815f 100644 --- a/src/main/java/com/thealgorithms/datastructures/buffers/CircularBuffer.java +++ b/src/main/java/com/thealgorithms/datastructures/buffers/CircularBuffer.java @@ -9,7 +9,7 @@ public class CircularBuffer { private final AtomicInteger size = new AtomicInteger(0); public CircularBuffer(int size) { - //noinspection unchecked + // noinspection unchecked this.buffer = (Item[]) new Object[size]; this.putPointer = new CircularPointer(0, size); this.getPointer = new CircularPointer(0, size); @@ -24,8 +24,7 @@ public class CircularBuffer { } public Item get() { - if (isEmpty()) - return null; + if (isEmpty()) return null; Item item = buffer[getPointer.getAndIncrement()]; size.decrementAndGet(); @@ -33,8 +32,7 @@ public class CircularBuffer { } public boolean put(Item item) { - if (isFull()) - return false; + if (isFull()) return false; buffer[putPointer.getAndIncrement()] = item; size.incrementAndGet(); @@ -51,8 +49,7 @@ public class CircularBuffer { } public int getAndIncrement() { - if (pointer == max) - pointer = 0; + if (pointer == max) pointer = 0; int tmp = pointer; pointer++; return tmp; diff --git a/src/main/java/com/thealgorithms/datastructures/caches/LFUCache.java b/src/main/java/com/thealgorithms/datastructures/caches/LFUCache.java index de1f6af6..03a1d59e 100644 --- a/src/main/java/com/thealgorithms/datastructures/caches/LFUCache.java +++ b/src/main/java/com/thealgorithms/datastructures/caches/LFUCache.java @@ -43,7 +43,8 @@ public class LFUCache { * This method returns value present in the cache corresponding to the key passed as parameter * * @param key for which value is to be retrieved - * @returns object corresponding to the key passed as parameter, returns null if key is not present in the cache + * @returns object corresponding to the key passed as parameter, returns null if key is + * not present in the cache */ public V get(K key) { if (this.map.get(key) == null) { diff --git a/src/main/java/com/thealgorithms/datastructures/caches/LRUCache.java b/src/main/java/com/thealgorithms/datastructures/caches/LRUCache.java index 976a4fef..fcb7d975 100644 --- a/src/main/java/com/thealgorithms/datastructures/caches/LRUCache.java +++ b/src/main/java/com/thealgorithms/datastructures/caches/LRUCache.java @@ -126,14 +126,10 @@ public class LRUCache { private I key; private J value; - public Entry() {} + public Entry() { + } - public Entry( - Entry preEntry, - Entry nextEntry, - I key, - J value - ) { + public Entry(Entry preEntry, Entry nextEntry, I key, J value) { this.preEntry = preEntry; this.nextEntry = nextEntry; this.key = key; diff --git a/src/main/java/com/thealgorithms/datastructures/caches/MRUCache.java b/src/main/java/com/thealgorithms/datastructures/caches/MRUCache.java index fc55c4e4..30f91496 100644 --- a/src/main/java/com/thealgorithms/datastructures/caches/MRUCache.java +++ b/src/main/java/com/thealgorithms/datastructures/caches/MRUCache.java @@ -124,14 +124,10 @@ public class MRUCache { private I key; private J value; - public Entry() {} + public Entry() { + } - public Entry( - Entry preEntry, - Entry nextEntry, - I key, - J value - ) { + public Entry(Entry preEntry, Entry nextEntry, I key, J value) { this.preEntry = preEntry; this.nextEntry = nextEntry; this.key = key; diff --git a/src/main/java/com/thealgorithms/datastructures/dynamicarray/DynamicArray.java b/src/main/java/com/thealgorithms/datastructures/dynamicarray/DynamicArray.java index 1b6dd0c5..fb778357 100644 --- a/src/main/java/com/thealgorithms/datastructures/dynamicarray/DynamicArray.java +++ b/src/main/java/com/thealgorithms/datastructures/dynamicarray/DynamicArray.java @@ -44,8 +44,7 @@ public class DynamicArray implements Iterable { */ public void add(final E element) { if (this.size == this.elements.length) { - this.elements = - Arrays.copyOf(this.elements, newCapacity(2 * this.capacity)); + this.elements = Arrays.copyOf(this.elements, newCapacity(2 * this.capacity)); } this.elements[this.size] = element; @@ -84,8 +83,7 @@ public class DynamicArray implements Iterable { fastRemove(this.elements, index); if (this.capacity > DEFAULT_CAPACITY && size * 4 <= this.capacity) { - this.elements = - Arrays.copyOf(this.elements, newCapacity(this.capacity / 2)); + this.elements = Arrays.copyOf(this.elements, newCapacity(this.capacity / 2)); } return oldElement; } @@ -116,13 +114,7 @@ public class DynamicArray implements Iterable { final int newSize = this.size - 1; if (newSize > index) { - System.arraycopy( - elements, - index + 1, - elements, - index, - newSize - index - ); + System.arraycopy(elements, index + 1, elements, index, newSize - index); } elements[this.size = newSize] = null; @@ -144,9 +136,7 @@ public class DynamicArray implements Iterable { */ @Override public String toString() { - return Arrays.toString( - Arrays.stream(this.elements).filter(Objects::nonNull).toArray() - ); + return Arrays.toString(Arrays.stream(this.elements).filter(Objects::nonNull).toArray()); } /** diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/A_Star.java b/src/main/java/com/thealgorithms/datastructures/graphs/A_Star.java index fe01cecd..ea75e067 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/A_Star.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/A_Star.java @@ -1,5 +1,5 @@ /* - Time Complexity = O(E), where E is equal to the number of edges + Time Complexity = O(E), where E is equal to the number of edges */ package com.thealgorithms.datastructures.graphs; @@ -64,13 +64,10 @@ public class A_Star { 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). + private int + estimated; // heuristic value associated to the last node od the path (current node). - public PathAndDistance( - int distance, - ArrayList path, - int estimated - ) { + public PathAndDistance(int distance, ArrayList path, int estimated) { this.distance = distance; this.path = path; this.estimated = estimated; @@ -90,25 +87,16 @@ public class A_Star { private void printSolution() { if (this.path != null) { - System.out.println( - "Optimal path: " + - this.path + - ", distance: " + - this.distance - ); + System.out.println("Optimal path: " + this.path + ", distance: " + this.distance); } else { - System.out.println( - "There is no path available to connect the points" - ); + System.out.println("There is no path available to connect the points"); } } } 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)) - ); + graph.addEdge(new Edge(data.get(i), data.get(i + 1), data.get(i + 2))); } /* .x. node @@ -165,123 +153,24 @@ public class A_Star { }; 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 - ) - ); + 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 - ) { + 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())) - ); + Comparator.comparingInt(a -> (a.getDistance() + a.getEstimated()))); // dummy data to start the algorithm from the beginning point queue.add(new PathAndDistance(0, new ArrayList<>(List.of(from)), 0)); @@ -290,34 +179,25 @@ public class A_Star { 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. + 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, + 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()] - ) - ); + 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 + 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/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java b/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java index aba37732..2998f7e9 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java @@ -2,8 +2,10 @@ package com.thealgorithms.datastructures.graphs; import java.util.*; -class BellmanFord /*Implementation of Bellman ford to detect negative cycles. Graph accepts inputs in form of edges which have -start vertex, end vertex and weights. Vertices should be labelled with a number between 0 and total number of vertices-1,both inclusive*/{ +class BellmanFord /*Implementation of Bellman ford to detect negative cycles. Graph accepts inputs +in form of edges which have start vertex, end vertex 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; @@ -49,7 +51,8 @@ start vertex, end vertex and weights. Vertices should be labelled with a number obj.go(); } - public void go() { // shows distance to all vertices // Interactive run for understanding the class first time. Assumes source vertex is 0 and + public void go() { // shows distance to all vertices // Interactive run for understanding the + // class first time. Assumes source vertex is 0 and 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"); @@ -63,7 +66,8 @@ start vertex, end vertex and weights. Vertices should be labelled with a number w = sc.nextInt(); arr[i] = new Edge(u, ve, w); } - int[] dist = new int[v]; // Distance array for holding the finalized shortest path distance between source + 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; i < v; i++) { @@ -73,10 +77,8 @@ start vertex, end vertex and weights. Vertices should be labelled with a number p[0] = -1; for (i = 0; i < v - 1; i++) { for (j = 0; j < e; j++) { - if ( - dist[arr[j].u] != Integer.MAX_VALUE && - dist[arr[j].v] > dist[arr[j].u] + arr[j].w - ) { + if (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; } @@ -84,10 +86,7 @@ start vertex, end vertex and weights. Vertices should be labelled with a number } // Final cycle for negative checking for (j = 0; j < e; j++) { - if ( - dist[arr[j].u] != Integer.MAX_VALUE && - dist[arr[j].v] > dist[arr[j].u] + arr[j].w - ) { + if (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; @@ -113,9 +112,13 @@ start vertex, end vertex and weights. Vertices should be labelled with a number * @param end Ending vertex * @param Edge Array of edges */ - public void show(int source, int end, Edge[] arr) { // be created by using addEdge() method and passed by calling getEdgeArray() method // Just shows results of computation, if graph is passed to it. The graph should + public void show(int source, int end, + Edge[] arr) { // be created by using addEdge() method and passed by calling getEdgeArray() + // method // Just shows results of computation, if graph is passed to it. The + // graph should 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 + 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++) { @@ -125,10 +128,8 @@ start vertex, end vertex and weights. Vertices should be labelled with a number 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 - ) { + 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; } @@ -136,10 +137,8 @@ start vertex, end vertex and weights. Vertices should be labelled with a number } // 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 - ) { + 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; diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/BipartiteGrapfDFS.java b/src/main/java/com/thealgorithms/datastructures/graphs/BipartiteGrapfDFS.java index 651b3e61..0bdc5340 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/BipartiteGrapfDFS.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/BipartiteGrapfDFS.java @@ -17,11 +17,7 @@ import java.util.Arrays; public class BipartiteGrapfDFS { private static boolean bipartite( - int V, - ArrayList> adj, - int[] color, - int node - ) { + int V, ArrayList> adj, int[] color, int node) { if (color[node] == -1) { color[node] = 1; } @@ -38,10 +34,7 @@ public class BipartiteGrapfDFS { return true; } - public static boolean isBipartite( - int V, - ArrayList> adj - ) { + public static boolean isBipartite(int V, ArrayList> adj) { // Code here int[] color = new int[V + 1]; Arrays.fill(color, -1); @@ -57,9 +50,7 @@ public class BipartiteGrapfDFS { } public static void main(String[] args) throws IOException { - BufferedReader read = new BufferedReader( - new InputStreamReader(System.in) - ); + BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(read.readLine().trim()); while (t-- > 0) { String[] S = read.readLine().trim().split(" "); diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/ConnectedComponent.java b/src/main/java/com/thealgorithms/datastructures/graphs/ConnectedComponent.java index 306abd7e..b0add255 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/ConnectedComponent.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/ConnectedComponent.java @@ -137,11 +137,7 @@ public class ConnectedComponent { 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/src/main/java/com/thealgorithms/datastructures/graphs/Cycles.java b/src/main/java/com/thealgorithms/datastructures/graphs/Cycles.java index 3d6e8a51..5d5bd3c7 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/Cycles.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/Cycles.java @@ -24,9 +24,7 @@ class Cycle { visited[i] = false; } - System.out.println( - "Enter the details of each edges " - ); + System.out.println("Enter the details of each edges "); for (int i = 0; i < edges; i++) { int start, end; diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/DIJSKSTRAS_ALGORITHM.java b/src/main/java/com/thealgorithms/datastructures/graphs/DIJSKSTRAS_ALGORITHM.java index 31ed7ef2..1811d4a1 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/DIJSKSTRAS_ALGORITHM.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/DIJSKSTRAS_ALGORITHM.java @@ -1,6 +1,6 @@ /* Refer https://www.geeksforgeeks.org/dijkstras-shortest-path-algorithm-greedy-algo-7/ -for better understanding +for better understanding */ package com.thealgorithms.datastructures.graphs; @@ -45,12 +45,8 @@ class dijkstras { Set[u] = true; for (int v = 0; v < k; v++) { - if ( - !Set[v] && - graph[u][v] != 0 && - dist[u] != Integer.MAX_VALUE && - dist[u] + graph[u][v] < dist[v] - ) { + if (!Set[v] && graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE + && dist[u] + graph[u][v] < dist[v]) { dist[v] = dist[u] + graph[u][v]; } } @@ -61,23 +57,23 @@ class dijkstras { public static void main(String[] args) { int[][] graph = new int[][] { - { 0, 4, 0, 0, 0, 0, 0, 8, 0 }, - { 4, 0, 8, 0, 0, 0, 0, 11, 0 }, - { 0, 8, 0, 7, 0, 4, 0, 0, 2 }, - { 0, 0, 7, 0, 9, 14, 0, 0, 0 }, - { 0, 0, 0, 9, 0, 10, 0, 0, 0 }, - { 0, 0, 4, 14, 10, 0, 2, 0, 0 }, - { 0, 0, 0, 0, 0, 2, 0, 1, 6 }, - { 8, 11, 0, 0, 0, 0, 1, 0, 7 }, - { 0, 0, 2, 0, 0, 0, 6, 7, 0 }, + {0, 4, 0, 0, 0, 0, 0, 8, 0}, + {4, 0, 8, 0, 0, 0, 0, 11, 0}, + {0, 8, 0, 7, 0, 4, 0, 0, 2}, + {0, 0, 7, 0, 9, 14, 0, 0, 0}, + {0, 0, 0, 9, 0, 10, 0, 0, 0}, + {0, 0, 4, 14, 10, 0, 2, 0, 0}, + {0, 0, 0, 0, 0, 2, 0, 1, 6}, + {8, 11, 0, 0, 0, 0, 1, 0, 7}, + {0, 0, 2, 0, 0, 0, 6, 7, 0}, }; dijkstras t = new dijkstras(); t.dijkstra(graph, 0); - } //main -} //djikstras + } // main +} // djikstras /* OUTPUT : -Vertex Distance +Vertex Distance 0 0 1 4 2 12 diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java b/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java index bf3ef8e6..673b795b 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java @@ -9,42 +9,32 @@ public class FloydWarshall { 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 + DistanceMatrix = new int[numberofvertices + 1][numberofvertices + + 1]; // stores the value of distance from all the possible path form the source // vertex to destination vertex // The matrix is initialized with 0's by default this.numberofvertices = numberofvertices; } - public void floydwarshall(int[][] AdjacencyMatrix) { // calculates all the distances from source to destination vertex + 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 destination = 1; destination <= numberofvertices; destination++) { + DistanceMatrix[source][destination] = AdjacencyMatrix[source][destination]; } } - for ( - int intermediate = 1; - intermediate <= numberofvertices; - intermediate++ - ) { + 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] - ) { // calculated distance it get replaced as new shortest distance // if the new distance calculated is less then the earlier shortest - DistanceMatrix[source][destination] = - DistanceMatrix[source][intermediate] + - DistanceMatrix[intermediate][destination]; + for (int destination = 1; destination <= numberofvertices; destination++) { + if (DistanceMatrix[source][intermediate] + + DistanceMatrix[intermediate][destination] + < DistanceMatrix[source] + [destination]) { // calculated distance it get replaced as + // new shortest distance // if the new + // distance calculated is less then the + // earlier shortest + DistanceMatrix[source][destination] = DistanceMatrix[source][intermediate] + + DistanceMatrix[intermediate][destination]; } } } @@ -55,11 +45,7 @@ public class FloydWarshall { System.out.println(); for (int source = 1; source <= numberofvertices; source++) { System.out.print(source + "\t"); - for ( - int destination = 1; - destination <= numberofvertices; - destination++ - ) { + for (int destination = 1; destination <= numberofvertices; destination++) { System.out.print(DistanceMatrix[source][destination] + "\t"); } System.out.println(); @@ -70,15 +56,10 @@ public class FloydWarshall { 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]; + 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++ - ) { + for (int destination = 1; destination <= numberOfVertices; destination++) { adjacencyMatrix[source][destination] = scan.nextInt(); if (source == destination) { adjacencyMatrix[source][destination] = 0; diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java b/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java index 1430f1a2..d4d6a381 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java @@ -21,7 +21,7 @@ public class HamiltonianCycle { this.V = graph.length; this.cycle = new int[this.V + 1]; - //Initialize path array with -1 value + // Initialize path array with -1 value for (int i = 0; i < this.cycle.length; i++) { this.cycle[i] = -1; } @@ -41,13 +41,15 @@ public class HamiltonianCycle { return cycle; } - /** function to find paths recursively + /** + * function to find paths recursively * Find paths recursively from given vertex * @param vertex Vertex from which path is to be found * @returns true if path is found false otherwise */ public boolean isPathFound(int vertex) { - boolean isLastVertexConnectedToStart = this.graph[vertex][0] == 1 && this.pathCount == this.V; + boolean isLastVertexConnectedToStart + = this.graph[vertex][0] == 1 && this.pathCount == this.V; if (isLastVertexConnectedToStart) { return true; } @@ -83,7 +85,8 @@ public class HamiltonianCycle { return false; } - /** function to check if path is already selected + /** + * function to check if path is already selected * Check if path is already selected * @param vertex Starting vertex */ diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithm.java b/src/main/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithm.java index 350d7d27..e978ddc1 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithm.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithm.java @@ -133,7 +133,7 @@ class TopologicalSort> { public class KahnsAlgorithm { public static void main(String[] args) { - //Graph definition and initialization + // Graph definition and initialization AdjacencyList graph = new AdjacencyList<>(); graph.addEdge("a", "b"); graph.addEdge("c", "a"); @@ -144,7 +144,7 @@ public class KahnsAlgorithm { TopologicalSort topSort = new TopologicalSort<>(graph); - //Printing the order + // Printing the order for (String s : topSort.topSortOrder()) { System.out.print(s + " "); } diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/Kosaraju.java b/src/main/java/com/thealgorithms/datastructures/graphs/Kosaraju.java index f24791dc..c24046f5 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/Kosaraju.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/Kosaraju.java @@ -7,17 +7,18 @@ import java.util.Stack; /** * Java program that implements Kosaraju Algorithm. * @author Shivanagouda S A (https://github.com/shivu2002a) - * + * */ /** - * Kosaraju algorithm is a linear time algorithm to find the strongly connected components of a - directed graph, which, from here onwards will be referred by SCC. It leverages the fact that the transpose - graph (same graph with all the edges reversed) has exactly the same SCCs as the original graph. - - * A graph is said to be strongly connected if every vertex is reachable from every other vertex. - The SCCs of a directed graph form a partition into subgraphs that are themselves strongly connected. - Single node is always a SCC. + * Kosaraju algorithm is a linear time algorithm to find the strongly connected components of a + directed graph, which, from here onwards will be referred by SCC. It leverages the fact that the + transpose graph (same graph with all the edges reversed) has exactly the same SCCs as the original + graph. + + * A graph is said to be strongly connected if every vertex is reachable from every other vertex. + The SCCs of a directed graph form a partition into subgraphs that are themselves strongly + connected. Single node is always a SCC. * Example: @@ -26,19 +27,20 @@ import java.util.Stack; | / | \ / | / | \ / v / v \ / - 1 5 --> 6 + 1 5 --> 6 For the above graph, the SCC list goes as follows: - 0, 1, 2 + 0, 1, 2 3 4, 5, 6 7 - + We can also see that order of the nodes in an SCC doesn't matter since they are in cycle. {@summary} - * Kosaraju Algorithm: - 1. Perform DFS traversal of the graph. Push node to stack before returning. This gives edges sorted by lowest finish time. + * Kosaraju Algorithm: + 1. Perform DFS traversal of the graph. Push node to stack before returning. This gives edges + sorted by lowest finish time. 2. Find the transpose graph by reversing the edges. 3. Pop nodes one by one from the stack and again to DFS on the modified graph. @@ -48,7 +50,7 @@ import java.util.Stack; | / | \ / | / | \ / | v | v v - 1 5 <--- 6 + 1 5 <--- 6 We can observe that this graph has the same SCC as that of original graph. @@ -59,33 +61,33 @@ public class Kosaraju { // Sort edges according to lowest finish time Stack stack = new Stack(); - //Store each component + // Store each component private List scc = new ArrayList<>(); - //All the strongly connected components + // All the strongly connected components private List> sccsList = new ArrayList<>(); /** - * + * * @param v Node count * @param list Adjacency list of graph * @return List of SCCs */ - public List> kosaraju(int v, List> list){ - + public List> kosaraju(int v, List> list) { + sortEdgesByLowestFinishTime(v, list); - + List> transposeGraph = createTransposeMatrix(v, list); findStronglyConnectedComponents(v, transposeGraph); - + return sccsList; } - private void sortEdgesByLowestFinishTime(int v, List> list){ + private void sortEdgesByLowestFinishTime(int v, List> list) { int[] vis = new int[v]; for (int i = 0; i < v; i++) { - if(vis[i] == 0){ + if (vis[i] == 0) { dfs(i, vis, list); } } @@ -105,15 +107,15 @@ public class Kosaraju { } /** - * + * * @param v Node count * @param transposeGraph Transpose of the given adjacency list */ - public void findStronglyConnectedComponents(int v, List> transposeGraph){ + public void findStronglyConnectedComponents(int v, List> transposeGraph) { int[] vis = new int[v]; while (!stack.isEmpty()) { var node = stack.pop(); - if(vis[node] == 0){ + if (vis[node] == 0) { dfs2(node, vis, transposeGraph); sccsList.add(scc); scc = new ArrayList<>(); @@ -121,24 +123,21 @@ public class Kosaraju { } } - //Dfs to store the nodes in order of lowest finish time - private void dfs(int node, int[] vis, List> list){ + // Dfs to store the nodes in order of lowest finish time + private void dfs(int node, int[] vis, List> list) { vis[node] = 1; - for(Integer neighbour : list.get(node)){ - if(vis[neighbour] == 0) - dfs(neighbour, vis, list); + for (Integer neighbour : list.get(node)) { + if (vis[neighbour] == 0) dfs(neighbour, vis, list); } stack.push(node); } - //Dfs to find all the nodes of each strongly connected component - private void dfs2(int node, int[] vis, List> list){ + // Dfs to find all the nodes of each strongly connected component + private void dfs2(int node, int[] vis, List> list) { vis[node] = 1; - for(Integer neighbour : list.get(node)){ - if(vis[neighbour] == 0) - dfs2(neighbour, vis, list); + for (Integer neighbour : list.get(node)) { + if (vis[neighbour] == 0) dfs2(neighbour, vis, list); } scc.add(node); } - } diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/Kruskal.java b/src/main/java/com/thealgorithms/datastructures/graphs/Kruskal.java index 5d326576..3c41a30b 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/Kruskal.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/Kruskal.java @@ -15,8 +15,8 @@ import java.util.PriorityQueue; 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; @@ -30,12 +30,7 @@ public class Kruskal { } } - private static void addEdge( - HashSet[] graph, - int from, - int to, - int weight - ) { + private static void addEdge(HashSet[] graph, int from, int to, int weight) { graph[from].add(new Edge(from, to, weight)); } @@ -58,9 +53,7 @@ public class Kruskal { 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(i + " <-- weight " + edge.weight + " --> " + edge.to); } } @@ -70,9 +63,7 @@ public class Kruskal { 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(i + " <-- weight " + edge.weight + " --> " + edge.to); } } } @@ -83,9 +74,8 @@ public class Kruskal { // 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)) - ); + PriorityQueue edges + = new PriorityQueue<>((Comparator.comparingInt(edge -> edge.weight))); for (int i = 0; i < nodes; i++) { minGraph[i] = new HashSet<>(); connectedGroups[i] = new HashSet<>(); @@ -98,18 +88,12 @@ public class Kruskal { 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) - ) { + 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]] - ); + 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] - ); + 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 diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/MatrixGraphs.java b/src/main/java/com/thealgorithms/datastructures/graphs/MatrixGraphs.java index 7593a9cf..701eec60 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/MatrixGraphs.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/MatrixGraphs.java @@ -71,9 +71,7 @@ class AdjacencyMatrixGraph { public AdjacencyMatrixGraph(int givenNumberOfVertices) { this.setNumberOfVertices(givenNumberOfVertices); this.setNumberOfEdges(0); - this.setAdjacency( - new int[givenNumberOfVertices][givenNumberOfVertices] - ); + 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; @@ -247,11 +245,7 @@ class AdjacencyMatrixGraph { * has been visited * @param orderList the list to add vertices to as they are visited */ - private void depthFirstOrder( - int currentVertex, - boolean[] visited, - List orderList - ) { + private void depthFirstOrder(int currentVertex, boolean[] visited, List orderList) { // If this vertex has already been visited, do nothing and return if (visited[currentVertex]) { return; @@ -264,11 +258,9 @@ class AdjacencyMatrixGraph { // Get the adjacency array for this vertex int[] adjacent = _adjacency[currentVertex]; - for ( - int i = 0; - i < adjacent.length; - i++ - ) { // we are considering exploring, recurse on it // If an edge exists between the currentVertex and the vertex + for (int i = 0; i < adjacent.length; + i++) { // we are considering exploring, recurse on it // If an edge exists between the + // currentVertex and the vertex if (adjacent[i] == AdjacencyMatrixGraph.EDGE_EXIST) { depthFirstOrder(i, visited, orderList); } @@ -317,11 +309,9 @@ class AdjacencyMatrixGraph { // Get the adjacency array for the currentVertex and // check each node int[] adjacent = _adjacency[currentVertex]; - for ( - int vertex = 0; - vertex < adjacent.length; - vertex++ - ) { // vertex we are considering exploring, we add it to the queue // If an edge exists between the current vertex and the + for (int vertex = 0; vertex < adjacent.length; + vertex++) { // vertex we are considering exploring, we add it to the queue // If an + // edge exists between the current vertex and the if (adjacent[vertex] == AdjacencyMatrixGraph.EDGE_EXIST) { queue.add(vertex); } diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/PrimMST.java b/src/main/java/com/thealgorithms/datastructures/graphs/PrimMST.java index 893b835e..e1876289 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/PrimMST.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/PrimMST.java @@ -31,9 +31,7 @@ class PrimMST { 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]] - ); + System.out.println(parent[i] + " - " + i + " " + graph[i][parent[i]]); } } @@ -72,17 +70,12 @@ class PrimMST { // 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++ - ) // Update the key only if graph[u][v] is smaller than key[v] // mstSet[v] is false for vertices not yet included in MST // graph[u][v] is non zero only for adjacent vertices of m + for (int v = 0; v < V; + v++) // Update the key only if graph[u][v] is smaller than key[v] // mstSet[v] is + // false for vertices not yet included in MST // graph[u][v] is non zero only + // for adjacent vertices of m { - if ( - graph[u][v] != 0 && - !mstSet[v] && - graph[u][v] < key[v] - ) { + if (graph[u][v] != 0 && !mstSet[v] && graph[u][v] < key[v]) { parent[v] = u; key[v] = graph[u][v]; } @@ -104,11 +97,11 @@ class PrimMST { 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 }, + {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 diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java b/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java index 497daeca..e63de0ad 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java @@ -8,16 +8,16 @@ import java.util.Stack; /** * Java program that implements Tarjan's Algorithm. * @author Shivanagouda S A (https://github.com/shivu2002a) - * + * */ /** - * Tarjan's algorithm is a linear time algorithm to find the strongly connected components of a - directed graph, which, from here onwards will be referred as SCC. - - * A graph is said to be strongly connected if every vertex is reachable from every other vertex. - The SCCs of a directed graph form a partition into subgraphs that are themselves strongly connected. - Single node is always a SCC. + * Tarjan's algorithm is a linear time algorithm to find the strongly connected components of a + directed graph, which, from here onwards will be referred as SCC. + + * A graph is said to be strongly connected if every vertex is reachable from every other vertex. + The SCCs of a directed graph form a partition into subgraphs that are themselves strongly + connected. Single node is always a SCC. * Example: 0 --------> 1 -------> 3 --------> 4 @@ -38,24 +38,25 @@ import java.util.Stack; 1, 2, 0 3 4 - + We can also see that order of the nodes in an SCC doesn't matter since they are in cycle. {@summary} - Tarjan's Algorithm: - * DFS search produces a DFS tree - * Strongly Connected Components form subtrees of the DFS tree. - * If we can find the head of these subtrees, we can get all the nodes in that subtree (including the head) - and that will be one SCC. - * There is no back edge from one SCC to another (here can be cross edges, but they will not be used). + Tarjan's Algorithm: + * DFS search produces a DFS tree + * Strongly Connected Components form subtrees of the DFS tree. + * If we can find the head of these subtrees, we can get all the nodes in that subtree (including + the head) and that will be one SCC. + * There is no back edge from one SCC to another (here can be cross edges, but they will not be + used). - * Kosaraju Algorithm aims at doing the same but uses two DFS traversalse whereas Tarjan’s algorithm does - the same in a single DFS, which leads to much lower constant factors in the latter. + * Kosaraju Algorithm aims at doing the same but uses two DFS traversalse whereas Tarjan’s + algorithm does the same in a single DFS, which leads to much lower constant factors in the latter. */ public class TarjansAlgorithm { - //Timer for tracking lowtime and insertion time + // Timer for tracking lowtime and insertion time private int Time; private List> SCClist = new ArrayList>(); @@ -66,15 +67,15 @@ public class TarjansAlgorithm { // insertionTime:Time when a node is visited 1st time while DFS traversal - // lowTime: indicates the earliest visited vertex (the vertex with minimum insertion time) that can - // be reached from a subtree rooted with a particular node. + // lowTime: indicates the earliest visited vertex (the vertex with minimum insertion time) + // that can be reached from a subtree rooted with a particular node. int[] lowTime = new int[V]; int[] insertionTime = new int[V]; for (int i = 0; i < V; i++) { insertionTime[i] = -1; lowTime[i] = -1; } - + // To check if element is present in stack boolean[] isInStack = new boolean[V]; @@ -90,36 +91,36 @@ public class TarjansAlgorithm { } private void stronglyConnCompsUtil(int u, int[] lowTime, int[] insertionTime, - boolean[] isInStack, Stack st, List> graph) { + boolean[] isInStack, Stack st, List> graph) { // Initialize insertion time and lowTime value of current node insertionTime[u] = Time; lowTime[u] = Time; Time += 1; - //Push current node into stack + // Push current node into stack isInStack[u] = true; st.push(u); // Go through all vertices adjacent to this for (Integer vertex : graph.get(u)) { - //If the adjacent node is unvisited, do DFS + // If the adjacent node is unvisited, do DFS if (insertionTime[vertex] == -1) { stronglyConnCompsUtil(vertex, lowTime, insertionTime, isInStack, st, graph); - //update lowTime for the current node comparing lowtime of adj node + // update lowTime for the current node comparing lowtime of adj node lowTime[u] = Math.min(lowTime[u], lowTime[vertex]); } else if (isInStack[vertex]) { - //If adj node is in stack, update low + // If adj node is in stack, update low lowTime[u] = Math.min(lowTime[u], insertionTime[vertex]); } } - //If lowtime and insertion time are same, current node is the head of an SCC - // head node found, get all the nodes in this SCC + // If lowtime and insertion time are same, current node is the head of an SCC + // head node found, get all the nodes in this SCC if (lowTime[u] == insertionTime[u]) { int w = -1; var scc = new ArrayList(); - //Stack has all the nodes of the current SCC + // Stack has all the nodes of the current SCC while (w != u) { w = st.pop(); scc.add(w); @@ -128,5 +129,4 @@ public class TarjansAlgorithm { SCClist.add(scc); } } - } diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapCuckooHashing.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapCuckooHashing.java index a7f1cbf1..d4f8cda9 100644 --- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapCuckooHashing.java +++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapCuckooHashing.java @@ -33,7 +33,8 @@ public class HashMapCuckooHashing { } /** - * The 2 Hash Functions takes a given key and finds an index based on its data, 2 distinctive ways to minimize collisions + * The 2 Hash Functions takes a given key and finds an index based on its data, 2 distinctive + * ways to minimize collisions * * @param key the desired key to be converted * @return int an index corresponding to the key @@ -57,10 +58,10 @@ public class HashMapCuckooHashing { } /** - * inserts the key into the hash map by wrapping it as an Integer object, then uses while loop to insert new key - * if desired place is empty, return. - * if already occupied, continue while loop over the new key that has just been pushed out. - * if while loop continues more than Thresh, rehash table to new size, then push again. + * inserts the key into the hash map by wrapping it as an Integer object, then uses while loop + * to insert new key if desired place is empty, return. if already occupied, continue while loop + * over the new key that has just been pushed out. if while loop continues more than Thresh, + * rehash table to new size, then push again. * * @param key the desired key to be inserted in the hash map */ @@ -70,26 +71,19 @@ public class HashMapCuckooHashing { int hash, loopCounter = 0; if (isFull()) { - System.out.println( - "Hash table is full, lengthening & rehashing table" - ); + System.out.println("Hash table is full, lengthening & rehashing table"); reHashTableIncreasesTableSize(); } if (checkTableContainsKey(key)) { - throw new IllegalArgumentException( - "Key already inside, no duplicates allowed" - ); + throw new IllegalArgumentException("Key already inside, no duplicates allowed"); } while (loopCounter <= thresh) { loopCounter++; hash = hashFunction1(key); - if ( - (buckets[hash] == null) || - Objects.equals(buckets[hash], AVAILABLE) - ) { + if ((buckets[hash] == null) || Objects.equals(buckets[hash], AVAILABLE)) { buckets[hash] = wrappedInt; size++; checkLoadFactor(); @@ -116,16 +110,14 @@ public class HashMapCuckooHashing { buckets[hash] = wrappedInt; wrappedInt = temp; } - System.out.println( - "Infinite loop occurred, lengthening & rehashing table" - ); + System.out.println("Infinite loop occurred, lengthening & rehashing table"); reHashTableIncreasesTableSize(); insertKey2HashTable(key); } /** - * creates new HashMapCuckooHashing object, then inserts each of the elements in the previous table to it with its new hash functions. - * then refers current array to new table. + * creates new HashMapCuckooHashing object, then inserts each of the elements in the previous + * table to it with its new hash functions. then refers current array to new table. * */ public void reHashTableIncreasesTableSize() { @@ -164,9 +156,7 @@ public class HashMapCuckooHashing { size--; return; } - throw new IllegalArgumentException( - "Key " + key + " already inside, no duplicates allowed" - ); + throw new IllegalArgumentException("Key " + key + " already inside, no duplicates allowed"); } /** @@ -177,9 +167,7 @@ public class HashMapCuckooHashing { if ((buckets[i] == null) || Objects.equals(buckets[i], AVAILABLE)) { System.out.println("Bucket " + i + ": Empty"); } else { - System.out.println( - "Bucket " + i + ": " + buckets[i].toString() - ); + System.out.println("Bucket " + i + ": " + buckets[i].toString()); } } System.out.println(); @@ -202,11 +190,9 @@ public class HashMapCuckooHashing { if (Objects.equals(buckets[hash], wrappedInt)) return hash; hash = hashFunction2(key); - if ( - !Objects.equals(buckets[hash], wrappedInt) - ) throw new IllegalArgumentException( - "Key " + key + " not found in table" - ); else { + if (!Objects.equals(buckets[hash], wrappedInt)) + throw new IllegalArgumentException("Key " + key + " not found in table"); + else { return hash; } } @@ -218,16 +204,8 @@ public class HashMapCuckooHashing { * @return int the index where the key is located */ public boolean checkTableContainsKey(int key) { - return ( - ( - buckets[hashFunction1(key)] != null && - buckets[hashFunction1(key)].equals(key) - ) || - ( - buckets[hashFunction2(key)] != null && - buckets[hashFunction2(key)] == key - ) - ); + return ((buckets[hashFunction1(key)] != null && buckets[hashFunction1(key)].equals(key)) + || (buckets[hashFunction2(key)] != null && buckets[hashFunction2(key)] == key)); } /** @@ -237,10 +215,7 @@ public class HashMapCuckooHashing { public double checkLoadFactor() { double factor = (double) size / tableSize; if (factor > .7) { - System.out.printf( - "Load factor is %.2f , rehashing table\n", - factor - ); + System.out.printf("Load factor is %.2f , rehashing table\n", factor); reHashTableIncreasesTableSize(); } return factor; diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Intersection.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Intersection.java index f89f9204..ad3f617c 100644 --- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Intersection.java +++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Intersection.java @@ -15,9 +15,7 @@ import java.util.Map; public class Intersection { public static List intersection(int[] arr1, int[] arr2) { - if ( - arr1 == null || arr2 == null || arr1.length == 0 || arr2.length == 0 - ) { + if (arr1 == null || arr2 == null || arr1.length == 0 || arr2.length == 0) { return Collections.emptyList(); } Map cnt = new HashMap<>(16); @@ -34,5 +32,6 @@ public class Intersection { return res; } - private Intersection() {} + private Intersection() { + } } diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Main.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Main.java index f6aa18b4..d68e0128 100644 --- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Main.java +++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Main.java @@ -20,31 +20,27 @@ public class Main { 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 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/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MainCuckooHashing.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MainCuckooHashing.java index 90ff839c..94d370b6 100644 --- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MainCuckooHashing.java +++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MainCuckooHashing.java @@ -24,59 +24,41 @@ public class MainCuckooHashing { choice = In.nextInt(); switch (choice) { - case 1: - { - System.out.println("Enter the Key: "); - key = In.nextInt(); - h.insertKey2HashTable(key); - break; - } - case 2: - { - System.out.println("Enter the Key delete: "); - key = In.nextInt(); - h.deleteKeyFromHashTable(key); - break; - } - case 3: - { - System.out.println("Print table:\n"); - 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.findKeyInTable(key) + - "\n" - ); - break; - } - case 6: - { - System.out.printf( - "Load factor is: %.2f\n", - h.checkLoadFactor() - ); - break; - } - case 7: - { - h.reHashTableIncreasesTableSize(); - break; - } + case 1: { + System.out.println("Enter the Key: "); + key = In.nextInt(); + h.insertKey2HashTable(key); + break; + } + case 2: { + System.out.println("Enter the Key delete: "); + key = In.nextInt(); + h.deleteKeyFromHashTable(key); + break; + } + case 3: { + System.out.println("Print table:\n"); + 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.findKeyInTable(key) + "\n"); + break; + } + case 6: { + System.out.printf("Load factor is: %.2f\n", h.checkLoadFactor()); + break; + } + case 7: { + h.reHashTableIncreasesTableSize(); + break; + } } } } diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElement.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElement.java index 5231431e..e3364b0e 100644 --- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElement.java +++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElement.java @@ -1,31 +1,32 @@ package com.thealgorithms.datastructures.hashmap.hashing; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; -import java.util.ArrayList; /* This class finds the majority element(s) in an array of integers. -A majority element is an element that appears more than or equal to n/2 times, where n is the length of the array. +A majority element is an element that appears more than or equal to n/2 times, where n is the length +of the array. */ public class MajorityElement { - /* - This method returns the majority element(s) in the given array of integers. - @param nums: an array of integers - @return a list of majority elements - */ - public static List majority(int[] nums){ - HashMap numToCount = new HashMap<>(); + /* + This method returns the majority element(s) in the given array of integers. + @param nums: an array of integers + @return a list of majority elements + */ + public static List majority(int[] nums) { + HashMap numToCount = new HashMap<>(); int n = nums.length; for (int i = 0; i < n; i++) { - if (numToCount.containsKey(nums[i])){ - numToCount.put(nums[i],numToCount.get(nums[i])+1); + if (numToCount.containsKey(nums[i])) { + numToCount.put(nums[i], numToCount.get(nums[i]) + 1); } else { - numToCount.put(nums[i],1); + numToCount.put(nums[i], 1); } } List majorityElements = new ArrayList<>(); - for (int key: numToCount.keySet()) { - if (numToCount.get(key) >= n/2){ + for (int key : numToCount.keySet()) { + if (numToCount.get(key) >= n / 2) { majorityElements.add(key); } } diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Map.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Map.java index cd27b0a7..4605883f 100644 --- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Map.java +++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Map.java @@ -19,5 +19,4 @@ public abstract class Map { protected int hash(Key key, int size) { return (key.hashCode() & Integer.MAX_VALUE) % size; } - } diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java index eeeb591c..34afa420 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java @@ -47,10 +47,10 @@ public class FibonacciHeap { * $ret = the HeapNode we inserted */ public HeapNode insert(int key) { - HeapNode toInsert = new HeapNode(key); //creates the node + HeapNode toInsert = new HeapNode(key); // creates the node if (this.empty()) { this.min = toInsert; - } else { //tree is not empty + } else { // tree is not empty min.setNext(toInsert); this.updateMin(toInsert); } @@ -69,14 +69,14 @@ public class FibonacciHeap { if (this.empty()) { return; } - if (this.numOfHeapNodes == 1) { //if there is only one tree + if (this.numOfHeapNodes == 1) { // if there is only one tree this.min = null; this.numOfTrees--; this.numOfHeapNodes--; return; } - //change all children's parent to null// - if (this.min.child != null) { //min has a child + // change all children's parent to null// + if (this.min.child != null) { // min has a child HeapNode child = this.min.child; HeapNode tmpChild = child; child.parent = null; @@ -85,14 +85,14 @@ public class FibonacciHeap { child.parent = null; } } - //delete the node// + // delete the node// if (this.numOfTrees > 1) { (this.min.prev).next = this.min.next; (this.min.next).prev = this.min.prev; if (this.min.child != null) { (this.min.prev).setNext(this.min.child); } - } else { //this.numOfTrees = 1 + } else { // this.numOfTrees = 1 this.min = this.min.child; } this.numOfHeapNodes--; @@ -136,17 +136,15 @@ public class FibonacciHeap { } /** - * Return a counters array, where the value of the i-th index is the number of trees with rank i in the heap. - * returns an empty array for an empty heap + * Return a counters array, where the value of the i-th index is the number of trees with rank i + * in the heap. returns an empty array for an empty heap */ public int[] countersRep() { if (this.empty()) { - return new int[0]; ///return an empty array + return new int[0]; /// return an empty array } - int[] rankArray = new int[(int) Math.floor( - Math.log(this.size()) / Math.log(GOLDEN_RATIO) - ) + - 1]; //creates the array + int[] rankArray = new int[(int) Math.floor(Math.log(this.size()) / Math.log(GOLDEN_RATIO)) + + 1]; // creates the array rankArray[this.min.rank]++; HeapNode curr = this.min.next; while (curr != this.min) { @@ -163,8 +161,8 @@ public class FibonacciHeap { * @post (numOfnodes = = $prev numOfnodes - 1) */ public void delete(HeapNode x) { - this.decreaseKey(x, x.getKey() + 1); //change key to be the minimal (-1) - this.deleteMin(); //delete it + this.decreaseKey(x, x.getKey() + 1); // change key to be the minimal (-1) + this.deleteMin(); // delete it } /** @@ -176,13 +174,13 @@ public class FibonacciHeap { private void decreaseKey(HeapNode x, int delta) { int newKey = x.getKey() - delta; x.key = newKey; - if (x.isRoot()) { //no parent to x + if (x.isRoot()) { // no parent to x this.updateMin(x); return; } if (x.getKey() >= x.parent.getKey()) { return; - } //we don't need to cut + } // we don't need to cut HeapNode prevParent = x.parent; this.cut(x); this.cascadingCuts(prevParent); @@ -197,17 +195,18 @@ public class FibonacciHeap { } /** - * This static function returns the total number of link operations made during the run-time of the program. - * A link operation is the operation which gets as input two trees of the same rank, and generates a tree of - * rank bigger by one. + * This static function returns the total number of link operations made during the run-time of + * the program. A link operation is the operation which gets as input two trees of the same + * rank, and generates a tree of rank bigger by one. */ public static int totalLinks() { return totalLinks; } /** - * This static function returns the total number of cut operations made during the run-time of the program. - * A cut operation is the operation which disconnects a subtree from its parent (during decreaseKey/delete methods). + * This static function returns the total number of cut operations made during the run-time of + * the program. A cut operation is the operation which disconnects a subtree from its parent + * (during decreaseKey/delete methods). */ public static int totalCuts() { return totalCuts; @@ -231,7 +230,7 @@ public class FibonacciHeap { * @post (numOfnodes == $prev numOfnodes) */ private void cascadingCuts(HeapNode curr) { - if (!curr.isMarked()) { //stop the recursion + if (!curr.isMarked()) { // stop the recursion curr.mark(); if (!curr.isRoot()) this.markedHeapNoodesCounter++; } else { @@ -255,10 +254,10 @@ public class FibonacciHeap { this.markedHeapNoodesCounter--; curr.marked = false; } - if (curr.parent.child == curr) { //we should change the parent's child - if (curr.next == curr) { //curr do not have brothers + if (curr.parent.child == curr) { // we should change the parent's child + if (curr.next == curr) { // curr do not have brothers curr.parent.child = null; - } else { //curr have brothers + } else { // curr have brothers curr.parent.child = curr.next; } } @@ -285,10 +284,8 @@ public class FibonacciHeap { * */ private HeapNode[] toBuckets(HeapNode curr) { - HeapNode[] buckets = new HeapNode[(int) Math.floor( - Math.log(this.size()) / Math.log(GOLDEN_RATIO) - ) + - 1]; + HeapNode[] buckets + = new HeapNode[(int) Math.floor(Math.log(this.size()) / Math.log(GOLDEN_RATIO)) + 1]; curr.prev.next = null; HeapNode tmpCurr; while (curr != null) { @@ -398,7 +395,7 @@ public class FibonacciHeap { private void mark() { if (this.isRoot()) { return; - } //check if the node is a root + } // check if the node is a root this.marked = true; } diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/GenericHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/GenericHeap.java index 2ceb86a7..23c26cfd 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/GenericHeap.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/GenericHeap.java @@ -45,16 +45,10 @@ public class GenericHeap> { int lci = 2 * pi + 1; int rci = 2 * pi + 2; int mini = pi; - if ( - lci < this.size() && - isLarger(this.data.get(lci), this.data.get(mini)) > 0 - ) { + if (lci < this.size() && isLarger(this.data.get(lci), this.data.get(mini)) > 0) { mini = lci; } - if ( - rci < this.size() && - isLarger(this.data.get(rci), this.data.get(mini)) > 0 - ) { + if (rci < this.size() && isLarger(this.data.get(rci), this.data.get(mini)) > 0) { mini = rci; } if (mini != pi) { @@ -67,7 +61,7 @@ public class GenericHeap> { return this.data.get(0); } - //t has higher property then return +ve + // t has higher property then return +ve private int isLarger(T t, T o) { return t.compareTo(o); } @@ -83,7 +77,7 @@ public class GenericHeap> { public void updatePriority(T item) { int index = map.get(item); - //because we enter lesser value then old vale + // because we enter lesser value then old vale upHeapify(index); } } diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/HeapElement.java b/src/main/java/com/thealgorithms/datastructures/heaps/HeapElement.java index bf095706..be5e42c9 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/HeapElement.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/HeapElement.java @@ -122,10 +122,8 @@ public class HeapElement { return false; } HeapElement otherHeapElement = (HeapElement) o; - return ( - (this.key == otherHeapElement.key) && - (this.additionalInfo.equals(otherHeapElement.additionalInfo)) - ); + return ((this.key == otherHeapElement.key) + && (this.additionalInfo.equals(otherHeapElement.additionalInfo))); } return false; } @@ -134,10 +132,7 @@ public class HeapElement { public int hashCode() { int result = 0; result = 31 * result + (int) key; - result = - 31 * - result + - (additionalInfo != null ? additionalInfo.hashCode() : 0); + result = 31 * result + (additionalInfo != null ? additionalInfo.hashCode() : 0); return result; } } diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/LeftistHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/LeftistHeap.java index 66861ac1..f64781f1 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/LeftistHeap.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/LeftistHeap.java @@ -2,117 +2,113 @@ package com.thealgorithms.datastructures.heaps; import java.util.ArrayList; -/* +/* * This is a leftist heap that follows the same operations as a * binary min heap, but may be unbalanced at times and follows a * leftist property, in which the left side is more heavy on the * right based on the null-path length (npl) values. - * + * * Source: https://iq.opengenus.org/leftist-heap/ - * + * */ public class LeftistHeap { - private class Node { - private int element, npl; - private Node left, right; + private class Node { + private int element, npl; + private Node left, right; - // Node constructor setting the data element and left/right pointers to null - private Node(int element) { - this.element = element; - left = right = null; - npl = 0; - } - } + // Node constructor setting the data element and left/right pointers to null + private Node(int element) { + this.element = element; + left = right = null; + npl = 0; + } + } - private Node root; + private Node root; - // Constructor - public LeftistHeap() { - root = null; - } + // Constructor + public LeftistHeap() { + root = null; + } - // Checks if heap is empty - public boolean isEmpty() { - return root == null; - } + // Checks if heap is empty + public boolean isEmpty() { + return root == null; + } - // Resets structure to initial state - public void clear() { - // We will put head is null - root = null; - } + // Resets structure to initial state + public void clear() { + // We will put head is null + root = null; + } - // Merge function that merges the contents of another leftist heap with the - // current one - public void merge(LeftistHeap h1) { - // If the present function is rhs then we ignore the merge - root = merge(root, h1.root); - h1.root = null; - } + // Merge function that merges the contents of another leftist heap with the + // current one + public void merge(LeftistHeap h1) { + // If the present function is rhs then we ignore the merge + root = merge(root, h1.root); + h1.root = null; + } - // Function merge with two Nodes a and b - public Node merge(Node a, Node b) { - if (a == null) - return b; + // Function merge with two Nodes a and b + public Node merge(Node a, Node b) { + if (a == null) return b; - if (b == null) - return a; + if (b == null) return a; - // Violates leftist property, so must do a swap - if (a.element > b.element) { - Node temp = a; - a = b; - b = temp; - } + // Violates leftist property, so must do a swap + if (a.element > b.element) { + Node temp = a; + a = b; + b = temp; + } - // Now we call the function merge to merge a and b - a.right = merge(a.right, b); + // Now we call the function merge to merge a and b + a.right = merge(a.right, b); - // Violates leftist property so must swap here - if (a.left == null) { - a.left = a.right; - a.right = null; - } else { - if (a.left.npl < a.right.npl) { - Node temp = a.left; - a.left = a.right; - a.right = temp; - } - a.npl = a.right.npl + 1; - } - return a; - } + // Violates leftist property so must swap here + if (a.left == null) { + a.left = a.right; + a.right = null; + } else { + if (a.left.npl < a.right.npl) { + Node temp = a.left; + a.left = a.right; + a.right = temp; + } + a.npl = a.right.npl + 1; + } + return a; + } - // Function insert. Uses the merge function to add the data - public void insert(int a) { - root = merge(new Node(a), root); - } + // Function insert. Uses the merge function to add the data + public void insert(int a) { + root = merge(new Node(a), root); + } - // Returns and removes the minimum element in the heap - public int extract_min() { - // If is empty return -1 - if (isEmpty()) - return -1; + // Returns and removes the minimum element in the heap + public int extract_min() { + // If is empty return -1 + if (isEmpty()) return -1; - int min = root.element; - root = merge(root.left, root.right); - return min; - } + int min = root.element; + root = merge(root.left, root.right); + return min; + } - // Function returning a list of an in order traversal of the data structure - public ArrayList in_order() { - ArrayList lst = new ArrayList<>(); - in_order_aux(root, lst); - return new ArrayList<>(lst); - } + // Function returning a list of an in order traversal of the data structure + public ArrayList in_order() { + ArrayList lst = new ArrayList<>(); + in_order_aux(root, lst); + return new ArrayList<>(lst); + } - // Auxiliary function for in_order - private void in_order_aux(Node n, ArrayList lst) { - if (n == null) - return; - in_order_aux(n.left, lst); - lst.add(n.element); - in_order_aux(n.right, lst); - } + // Auxiliary function for in_order + private void in_order_aux(Node n, ArrayList lst) { + if (n == null) return; + in_order_aux(n.left, lst); + lst.add(n.element); + in_order_aux(n.right, lst); + } } \ No newline at end of file diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java index 64731fd2..591b4439 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java @@ -70,30 +70,20 @@ public class MaxHeap implements Heap { // 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()))); + 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) - ) - ) { + 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())) - ); + wrongOrder = (key < getElementKey(elementIndex * 2)) + || (key < getElementKey(Math.min(elementIndex * 2, maxHeap.size()))); } } @@ -112,12 +102,10 @@ public class MaxHeap implements Heap { @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(); - } + 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"); } @@ -125,22 +113,13 @@ public class MaxHeap implements Heap { 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)) - ) { + 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)) - ) - ) { + else if (((2 * elementIndex <= maxHeap.size()) + && (getElementKey(elementIndex) < getElementKey(elementIndex * 2))) + || ((2 * elementIndex < maxHeap.size()) + && (getElementKey(elementIndex) < getElementKey(elementIndex * 2)))) { toggleDown(elementIndex); } } @@ -150,9 +129,7 @@ public class MaxHeap implements Heap { try { return extractMax(); } catch (Exception e) { - throw new EmptyHeapException( - "Heap is empty. Error retrieving element" - ); + throw new EmptyHeapException("Heap is empty. Error retrieving element"); } } } diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java index a28a8e5f..5c2cb5cc 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java @@ -64,30 +64,20 @@ public class MinHeap implements Heap { // 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()))); + 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) - ) - ) { + 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())) - ); + wrongOrder = (key > getElementKey(elementIndex * 2)) + || (key > getElementKey(Math.min(elementIndex * 2, minHeap.size()))); } } @@ -106,12 +96,10 @@ public class MinHeap implements Heap { @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(); - } + 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"); } @@ -119,22 +107,13 @@ public class MinHeap implements Heap { 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)) - ) { + 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)) - ) - ) { + else if (((2 * elementIndex <= minHeap.size()) + && (getElementKey(elementIndex) > getElementKey(elementIndex * 2))) + || ((2 * elementIndex < minHeap.size()) + && (getElementKey(elementIndex) > getElementKey(elementIndex * 2)))) { toggleDown(elementIndex); } } @@ -144,9 +123,7 @@ public class MinHeap implements Heap { try { return extractMin(); } catch (Exception e) { - throw new EmptyHeapException( - "Heap is empty. Error retrieving element" - ); + throw new EmptyHeapException("Heap is empty. Error retrieving element"); } } } diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java b/src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java index 23ac5d3a..2ad4ed53 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java @@ -82,10 +82,7 @@ public class MinPriorityQueue { 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] - ) { + if (2 * k + 1 <= this.size && this.heap[2 * k + 1] >= this.heap[k]) { break; } else if (2 * k + 1 > this.size) { break; @@ -94,14 +91,8 @@ public class MinPriorityQueue { 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; + 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; } diff --git a/src/main/java/com/thealgorithms/datastructures/lists/CircleLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/CircleLinkedList.java index f5edc6c0..5d9f0b3a 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/CircleLinkedList.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/CircleLinkedList.java @@ -38,9 +38,7 @@ public class CircleLinkedList { 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" - ); + throw new NullPointerException("Cannot add null element to the list"); } // head.next points to the last element; if (tail == null) { @@ -70,9 +68,7 @@ public class CircleLinkedList { public E remove(int pos) { if (pos > size || pos < 0) { // catching errors - throw new IndexOutOfBoundsException( - "position cannot be greater than size or negative" - ); + 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. diff --git a/src/main/java/com/thealgorithms/datastructures/lists/CursorLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/CursorLinkedList.java index 6ed317d6..cefc47c2 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/CursorLinkedList.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/CursorLinkedList.java @@ -120,8 +120,7 @@ public class CursorLinkedList { while (current_index != -1) { T current_element = cursorSpace[current_index].element; if (current_element.equals(element)) { - cursorSpace[prev_index].next = - cursorSpace[current_index].next; + cursorSpace[prev_index].next = cursorSpace[current_index].next; free(current_index); break; } diff --git a/src/main/java/com/thealgorithms/datastructures/lists/DoublyLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/DoublyLinkedList.java index 2d048d99..74aa4b8b 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/DoublyLinkedList.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/DoublyLinkedList.java @@ -217,7 +217,8 @@ class LinkOperations { public void insertTail(int x, DoublyLinkedList doublyLinkedList) { Link newLink = new Link(x); newLink.next = null; // currentTail(tail) newlink --> - if (doublyLinkedList.isEmpty()) { // Check if there are no elements in list then it adds first element + if (doublyLinkedList + .isEmpty()) { // Check if there are no elements in list then it adds first element tail = newLink; head = tail; } else { @@ -234,15 +235,9 @@ class LinkOperations { * @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, - DoublyLinkedList doublyLinkedList - ) { + public void insertElementByIndex(int x, int index, DoublyLinkedList doublyLinkedList) { if (index > size) { - throw new IndexOutOfBoundsException( - "Index: " + index + ", Size: " + size - ); + throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); } if (index == 0) { insertHead(x, doublyLinkedList); @@ -277,7 +272,8 @@ class LinkOperations { if (head == null) { tail = null; } else { - head.previous = null; // oldHead --> 2ndElement(head) nothing pointing at old head so will be removed + head.previous = null; // oldHead --> 2ndElement(head) nothing pointing at old head so + // will be removed } --size; return temp; @@ -314,9 +310,7 @@ class LinkOperations { 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!" - ); + throw new RuntimeException("The element to be deleted does not exist!"); } } diff --git a/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedArrayList.java b/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedArrayList.java index f9a80d98..80b36b8e 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedArrayList.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedArrayList.java @@ -36,11 +36,7 @@ public class MergeSortedArrayList { * @param listB the second list to merge * @param listC the result list after merging */ - public static void merge( - List listA, - List listB, - List listC - ) { + public static void merge(List listA, List listB, List listC) { int pa = 0; /* the index of listA */ int pb = 0; diff --git a/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedSinglyLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedSinglyLinkedList.java index 4ea0127f..2bee945c 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedSinglyLinkedList.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedSinglyLinkedList.java @@ -12,9 +12,7 @@ public class MergeSortedSinglyLinkedList extends SinglyLinkedList { } 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"); + assert merge(listA, listB).toString().equals("1->2->3->4->5->6->7->8->9->10"); } /** @@ -24,10 +22,7 @@ public class MergeSortedSinglyLinkedList extends SinglyLinkedList { * @param listB the second sored list * @return merged sorted list */ - public static SinglyLinkedList merge( - SinglyLinkedList listA, - SinglyLinkedList listB - ) { + public static SinglyLinkedList merge(SinglyLinkedList listA, SinglyLinkedList listB) { Node headA = listA.getHead(); Node headB = listB.getHead(); diff --git a/src/main/java/com/thealgorithms/datastructures/lists/Merge_K_SortedLinkedlist.java b/src/main/java/com/thealgorithms/datastructures/lists/Merge_K_SortedLinkedlist.java index 840b935e..9d26645c 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/Merge_K_SortedLinkedlist.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/Merge_K_SortedLinkedlist.java @@ -18,9 +18,7 @@ public class Merge_K_SortedLinkedlist { */ Node mergeKList(Node[] a, int N) { // Min Heap - PriorityQueue min = new PriorityQueue<>( - Comparator.comparingInt(x -> x.data) - ); + 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)); diff --git a/src/main/java/com/thealgorithms/datastructures/lists/RandomNode.java b/src/main/java/com/thealgorithms/datastructures/lists/RandomNode.java index e173da2f..7318b802 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/RandomNode.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/RandomNode.java @@ -1,25 +1,30 @@ -/** Author : Suraj Kumar +/** + * Author : Suraj Kumar * Github : https://github.com/skmodi649 */ -/** PROBLEM DESCRIPTION : +/** + * PROBLEM DESCRIPTION : * There is a single linked list and we are supposed to find a random node in the given linked list */ -/** ALGORITHM : +/** + * ALGORITHM : * Step 1 : START * Step 2 : Create an arraylist of type integer * Step 3 : Declare an integer type variable for size and linked list type for head - * Step 4 : We will use two methods, one for traversing through the linked list using while loop and also increase the size by 1 + * Step 4 : We will use two methods, one for traversing through the linked list using while loop and + * also increase the size by 1 * * (a) RandomNode(head) * (b) run a while loop till null; * (c) add the value to arraylist; * (d) increase the size; * - * Step 5 : Now use another method for getting random values using Math.random() and return the value present in arraylist for the calculated index - * Step 6 : Now in main() method we will simply insert nodes in the linked list and then call the appropriate method and then print the random node generated - * Step 7 : STOP + * Step 5 : Now use another method for getting random values using Math.random() and return the + * value present in arraylist for the calculated index Step 6 : Now in main() method we will simply + * insert nodes in the linked list and then call the appropriate method and then print the random + * node generated Step 7 : STOP */ package com.thealgorithms.datastructures.lists; @@ -86,6 +91,7 @@ public class RandomNode { * Time Complexity : O(n) * Auxiliary Space Complexity : O(1) */ -/** Time Complexity : O(n) +/** + * Time Complexity : O(n) * Auxiliary Space Complexity : O(1) */ diff --git a/src/main/java/com/thealgorithms/datastructures/lists/SearchSinglyLinkedListRecursion.java b/src/main/java/com/thealgorithms/datastructures/lists/SearchSinglyLinkedListRecursion.java index bd3dd51b..35f8c9a9 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/SearchSinglyLinkedListRecursion.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/SearchSinglyLinkedListRecursion.java @@ -23,10 +23,7 @@ public class SearchSinglyLinkedListRecursion extends SinglyLinkedList { * {@code false}. */ private boolean searchRecursion(Node node, int key) { - return ( - node != null && - (node.value == key || searchRecursion(node.next, key)) - ); + return (node != null && (node.value == key || searchRecursion(node.next, key))); } @Override diff --git a/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java index df460938..8d150593 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java @@ -125,19 +125,20 @@ public class SinglyLinkedList extends Node { public Node reverseList(Node node) { Node prev = null; Node curr = node; - + while (curr != null && curr.next != null) { - Node next=curr.next; + Node next = curr.next; curr.next = prev; prev = curr; curr = next; } - //when curr.next==null, the current element is left without pointing it to its prev,so - if(curr != null){ + // when curr.next==null, the current element is left without pointing it to its prev,so + if (curr != null) { curr.next = prev; - prev=curr; + prev = curr; } - //prev will be pointing to the last element in the Linkedlist, it will be the new head of the reversed linkedlist + // prev will be pointing to the last element in the Linkedlist, it will be the new head of + // the reversed linkedlist return prev; } @@ -244,9 +245,7 @@ public class SinglyLinkedList extends Node { // skip all duplicates if (newHead.next != null && newHead.value == newHead.next.value) { // move till the end of duplicates sublist - while ( - newHead.next != null && newHead.value == newHead.next.value - ) { + while (newHead.next != null && newHead.value == newHead.next.value) { newHead = newHead.next; } // skip all duplicates @@ -412,15 +411,10 @@ public class SinglyLinkedList extends Node { assert list.toString().equals("10->7->5->3->1"); System.out.println(list); /* Test search function */ - assert list.search(10) && - list.search(5) && - list.search(1) && - !list.search(100); + 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; + assert list.getNth(0) == 10 && list.getNth(2) == 5 && list.getNth(4) == 1; /* Test delete function */ list.deleteHead(); @@ -443,10 +437,7 @@ public class SinglyLinkedList extends Node { } SinglyLinkedList instance = new SinglyLinkedList(); - Node head = new Node( - 0, - new Node(2, new Node(3, new Node(3, new Node(4)))) - ); + Node head = new Node(0, new Node(2, new Node(3, new Node(3, new Node(4))))); instance.setHead(head); instance.deleteDuplicates(); instance.print(); @@ -469,7 +460,8 @@ class Node { */ Node next; - Node() {} + Node() { + } /** * Constructor diff --git a/src/main/java/com/thealgorithms/datastructures/lists/SkipList.java b/src/main/java/com/thealgorithms/datastructures/lists/SkipList.java index 34efde76..6a079ac8 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/SkipList.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/SkipList.java @@ -189,25 +189,23 @@ public class SkipList> { } Collections.reverse(layers); - String result = layers - .stream() - .map(layer -> { - StringBuilder acc = new StringBuilder(); - for (boolean b : layer) { - if (b) { - acc.append("[ ]"); - } else { - acc.append("---"); - } - acc.append(" "); - } - return acc.toString(); - }) - .collect(Collectors.joining("\n")); - String positions = IntStream - .range(0, sizeWithHeader - 1) - .mapToObj(i -> String.format("%3d", i)) - .collect(Collectors.joining(" ")); + String result = layers.stream() + .map(layer -> { + StringBuilder acc = new StringBuilder(); + for (boolean b : layer) { + if (b) { + acc.append("[ ]"); + } else { + acc.append("---"); + } + acc.append(" "); + } + return acc.toString(); + }) + .collect(Collectors.joining("\n")); + String positions = IntStream.range(0, sizeWithHeader - 1) + .mapToObj(i -> String.format("%3d", i)) + .collect(Collectors.joining(" ")); return result + String.format("%n H %s%n", positions); } @@ -299,17 +297,14 @@ public class SkipList> { public BernoulliHeightStrategy(double probability) { if (probability <= 0 || probability >= 1) { throw new IllegalArgumentException( - "Probability should be from 0 to 1. But was: " + probability - ); + "Probability should be from 0 to 1. But was: " + probability); } this.probability = probability; } @Override public int height(int expectedSize) { - long height = Math.round( - Math.log10(expectedSize) / Math.log10(1 / probability) - ); + long height = Math.round(Math.log10(expectedSize) / Math.log10(1 / probability)); if (height > Integer.MAX_VALUE) { throw new IllegalArgumentException(); } diff --git a/src/main/java/com/thealgorithms/datastructures/queues/CircularQueue.java b/src/main/java/com/thealgorithms/datastructures/queues/CircularQueue.java index e5bedd9b..9530c5a6 100644 --- a/src/main/java/com/thealgorithms/datastructures/queues/CircularQueue.java +++ b/src/main/java/com/thealgorithms/datastructures/queues/CircularQueue.java @@ -1,7 +1,7 @@ package com.thealgorithms.datastructures.queues; -//This program implements the concept of CircularQueue in Java -//Link to the concept: (https://en.wikipedia.org/wiki/Circular_buffer) +// This program implements the concept of CircularQueue in Java +// Link to the concept: (https://en.wikipedia.org/wiki/Circular_buffer) public class CircularQueue { int[] arr; @@ -23,7 +23,8 @@ public class CircularQueue { public boolean isFull() { if (topOfQueue + 1 == beginningOfQueue) { return true; - } else return topOfQueue == size - 1 && beginningOfQueue == 0; + } else + return topOfQueue == size - 1 && beginningOfQueue == 0; } public void enQueue(int value) { diff --git a/src/main/java/com/thealgorithms/datastructures/queues/LinkedQueue.java b/src/main/java/com/thealgorithms/datastructures/queues/LinkedQueue.java index 79fddb0e..7fa769c6 100644 --- a/src/main/java/com/thealgorithms/datastructures/queues/LinkedQueue.java +++ b/src/main/java/com/thealgorithms/datastructures/queues/LinkedQueue.java @@ -124,11 +124,9 @@ public class LinkedQueue implements Iterable { public T peek(int pos) { if (pos > size) - throw new IndexOutOfBoundsException( - "Position %s out of range!".formatted(pos)); + throw new IndexOutOfBoundsException("Position %s out of range!".formatted(pos)); Node node = front; - while (pos-- > 0) - node = node.next; + while (pos-- > 0) node = node.next; return node.data; } @@ -140,7 +138,6 @@ public class LinkedQueue implements Iterable { @Override public Iterator iterator() { return new Iterator<>() { - Node node = front; @Override @@ -168,16 +165,14 @@ public class LinkedQueue implements Iterable { * Clear all nodes in queue */ public void clear() { - while (size > 0) - dequeue(); + while (size > 0) dequeue(); } @Override public String toString() { StringJoiner join = new StringJoiner(", "); // separator of ', ' Node travel = front; - while ((travel = travel.next) != null) - join.add(String.valueOf(travel.data)); + while ((travel = travel.next) != null) join.add(String.valueOf(travel.data)); return '[' + join.toString() + ']'; } diff --git a/src/main/java/com/thealgorithms/datastructures/queues/PriorityQueues.java b/src/main/java/com/thealgorithms/datastructures/queues/PriorityQueues.java index 21432a53..dec25d2f 100644 --- a/src/main/java/com/thealgorithms/datastructures/queues/PriorityQueues.java +++ b/src/main/java/com/thealgorithms/datastructures/queues/PriorityQueues.java @@ -1,8 +1,5 @@ package com.thealgorithms.datastructures.queues; - - - /** * This class implements a PriorityQueue. * @@ -126,7 +123,8 @@ class PriorityQueue { if (isEmpty()) { throw new RuntimeException("Queue is Empty"); } else { - int max = queueArray[1]; // By defintion of our max-heap, value at queueArray[1] pos is the greatest + int max = queueArray[1]; // By defintion of our max-heap, value at queueArray[1] pos is + // the greatest // Swap max and last element int temp = queueArray[1]; @@ -175,4 +173,3 @@ class PriorityQueue { return nItems; } } - diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/BalancedBrackets.java b/src/main/java/com/thealgorithms/datastructures/stacks/BalancedBrackets.java index 2e2b572c..d80502d8 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/BalancedBrackets.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/BalancedBrackets.java @@ -28,16 +28,13 @@ class BalancedBrackets { */ public static boolean isPaired(char leftBracket, char rightBracket) { char[][] pairedBrackets = { - { '(', ')' }, - { '[', ']' }, - { '{', '}' }, - { '<', '>' }, + {'(', ')'}, + {'[', ']'}, + {'{', '}'}, + {'<', '>'}, }; for (char[] pairedBracket : pairedBrackets) { - if ( - pairedBracket[0] == leftBracket && - pairedBracket[1] == rightBracket - ) { + if (pairedBracket[0] == leftBracket && pairedBracket[1] == rightBracket) { return true; } } @@ -58,24 +55,21 @@ class BalancedBrackets { 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 */ + 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(); diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/CalculateMaxOfMin.java b/src/main/java/com/thealgorithms/datastructures/stacks/CalculateMaxOfMin.java index 7a76c62e..df7279bb 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/CalculateMaxOfMin.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/CalculateMaxOfMin.java @@ -1,8 +1,12 @@ -/** Author : Siddhant Swarup Mallick +/** + * Author : Siddhant Swarup Mallick * Github : https://github.com/siddhant2002 */ -/** Program description - Given an integer array. The task is to find the maximum of the minimum of the array */ +/** + * Program description - Given an integer array. The task is to find the maximum of the minimum of + * the array + */ package com.thealgorithms.datastructures.stacks; import java.util.*; diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/DecimalToAnyUsingStack.java b/src/main/java/com/thealgorithms/datastructures/stacks/DecimalToAnyUsingStack.java index 28302793..a0d36413 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/DecimalToAnyUsingStack.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/DecimalToAnyUsingStack.java @@ -24,12 +24,7 @@ public class DecimalToAnyUsingStack { 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 - ) - ); + String.format("Invalid input -> number:%d,radius:%d", number, radix)); } char[] tables = { '0', diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/DuplicateBrackets.java b/src/main/java/com/thealgorithms/datastructures/stacks/DuplicateBrackets.java index d47f5b19..fb976360 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/DuplicateBrackets.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/DuplicateBrackets.java @@ -1,7 +1,8 @@ package com.thealgorithms.datastructures.stacks; // 1. You are given a string exp representing an expression. -// 2. Assume that the expression is balanced i.e. the opening and closing brackets match with each other. +// 2. Assume that the expression is balanced i.e. the opening and closing brackets match with each +// other. // 3. But, some of the pair of brackets maybe extra/needless. // 4. You are required to print true if you detect extra brackets and false otherwise. // e.g.' diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/InfixToPostfix.java b/src/main/java/com/thealgorithms/datastructures/stacks/InfixToPostfix.java index 9df7330d..b0092233 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/InfixToPostfix.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/InfixToPostfix.java @@ -10,8 +10,7 @@ public class InfixToPostfix { assert "34+5*6-".equals(infix2PostFix("(3+4)*5-6")); } - public static String infix2PostFix(String infixExpression) - throws Exception { + public static String infix2PostFix(String infixExpression) throws Exception { if (!BalancedBrackets.isBalanced(infixExpression)) { throw new Exception("invalid expression"); } @@ -28,10 +27,7 @@ public class InfixToPostfix { } stack.pop(); } else { - while ( - !stack.isEmpty() && - precedence(element) <= precedence(stack.peek()) - ) { + while (!stack.isEmpty() && precedence(element) <= precedence(stack.peek())) { output.append(stack.pop()); } stack.push(element); @@ -45,16 +41,16 @@ public class InfixToPostfix { private static int precedence(char operator) { switch (operator) { - case '+': - case '-': - return 0; - case '*': - case '/': - return 1; - case '^': - return 2; - default: - return -1; + case '+': + case '-': + return 0; + case '*': + case '/': + return 1; + case '^': + return 2; + default: + return -1; } } } diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/LargestRectangle.java b/src/main/java/com/thealgorithms/datastructures/stacks/LargestRectangle.java index 9cc4f0f7..f076d5d6 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/LargestRectangle.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/LargestRectangle.java @@ -19,7 +19,7 @@ public class LargestRectangle { maxArea = Math.max(maxArea, tmp[1] * (i - tmp[0])); start = tmp[0]; } - st.push(new int[] { start, heights[i] }); + st.push(new int[] {start, heights[i]}); } while (!st.isEmpty()) { int[] tmp = st.pop(); @@ -29,8 +29,7 @@ public class LargestRectangle { } public static void main(String[] args) { - assert largestRectanglehistogram(new int[] { 2, 1, 5, 6, 2, 3 }) - .equals("10"); - assert largestRectanglehistogram(new int[] { 2, 4 }).equals("4"); + assert largestRectanglehistogram(new int[] {2, 1, 5, 6, 2, 3}).equals("10"); + assert largestRectanglehistogram(new int[] {2, 4}).equals("4"); } } diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/MaximumMinimumWindow.java b/src/main/java/com/thealgorithms/datastructures/stacks/MaximumMinimumWindow.java index 53a50279..88228000 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/MaximumMinimumWindow.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/MaximumMinimumWindow.java @@ -97,8 +97,8 @@ public class MaximumMinimumWindow { } public static void main(String[] args) { - int[] arr = new int[] { 10, 20, 30, 50, 10, 70, 30 }; - int[] target = new int[] { 70, 30, 20, 10, 10, 10, 10 }; + int[] arr = new int[] {10, 20, 30, 50, 10, 70, 30}; + int[] target = new int[] {70, 30, 20, 10, 10, 10, 10}; int[] res = calculateMaxOfMin(arr, arr.length); assert Arrays.equals(target, res); } diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/NextGraterElement.java b/src/main/java/com/thealgorithms/datastructures/stacks/NextGraterElement.java index 2497158a..294e436c 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/NextGraterElement.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/NextGraterElement.java @@ -37,7 +37,8 @@ import java.util.Stack; popped elements. d. Finally, push the next in the stack. - 3. If elements are left in stack after completing while loop then their Next Grater element is -1. + 3. If elements are left in stack after completing while loop then their Next Grater element is + -1. */ public class NextGraterElement { @@ -61,7 +62,7 @@ public class NextGraterElement { } public static void main(String[] args) { - int[] input = { 2, 7, 3, 5, 4, 6, 8 }; + int[] input = {2, 7, 3, 5, 4, 6, 8}; int[] result = findNextGreaterElements(input); System.out.println(Arrays.toString(result)); } diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/NextSmallerElement.java b/src/main/java/com/thealgorithms/datastructures/stacks/NextSmallerElement.java index 6073d481..b25e5346 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/NextSmallerElement.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/NextSmallerElement.java @@ -4,10 +4,10 @@ import java.util.Arrays; import java.util.Stack; /* - Given an array "input" you need to print the first smaller element for each element to the left side of an array. - For a given element x of an array, the Next Smaller element of that element is the - first smaller element to the left side of it. If no such element is present print -1. - + Given an array "input" you need to print the first smaller element for each element to the left + side of an array. For a given element x of an array, the Next Smaller element of that element is + the first smaller element to the left side of it. If no such element is present print -1. + Example input = { 2, 7, 3, 5, 4, 6, 8 }; At i = 0 @@ -24,17 +24,17 @@ import java.util.Stack; Next smaller element between (0 , 4) is 4 At i = 6 Next smaller element between (0 , 5) is 6 - + result : [-1, 2, 2, 3, 3, 4, 6] - + 1) Create a new empty stack st - + 2) Iterate over array "input" , where "i" goes from 0 to input.length -1. - a) We are looking for value just smaller than `input[i]`. So keep popping from "stack" + a) We are looking for value just smaller than `input[i]`. So keep popping from "stack" till elements in "stack.peek() >= input[i]" or stack becomes empty. - b) If the stack is non-empty, then the top element is our previous element. Else the previous element does not exist. - c) push input[i] in stack. - 3) If elements are left then their answer is -1 + b) If the stack is non-empty, then the top element is our previous element. Else the + previous element does not exist. c) push input[i] in stack. 3) If elements are left then their + answer is -1 */ public class NextSmallerElement { @@ -61,7 +61,7 @@ public class NextSmallerElement { } public static void main(String[] args) { - int[] input = { 2, 7, 3, 5, 4, 6, 8 }; + int[] input = {2, 7, 3, 5, 4, 6, 8}; int[] result = findNextSmallerElements(input); System.out.println(Arrays.toString(result)); } diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/NodeStack.java b/src/main/java/com/thealgorithms/datastructures/stacks/NodeStack.java index b4ab7860..ffdfc962 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/NodeStack.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/NodeStack.java @@ -50,7 +50,8 @@ public class NodeStack { /** * Constructors for the NodeStack. */ - public NodeStack() {} + public NodeStack() { + } private NodeStack(Item item) { this.data = item; diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/PostfixToInfix.java b/src/main/java/com/thealgorithms/datastructures/stacks/PostfixToInfix.java index 868aa778..0d67a793 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/PostfixToInfix.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/PostfixToInfix.java @@ -20,12 +20,12 @@ public class PostfixToInfix { public static boolean isOperator(char token) { switch (token) { - case '+': - case '-': - case '/': - case '*': - case '^': - return true; + case '+': + case '-': + case '/': + case '*': + case '^': + return true; } return false; @@ -42,7 +42,8 @@ public class PostfixToInfix { int operandCount = 0; int operatorCount = 0; - /* Traverse the postfix string to check if --> Number of operands = Number of operators + 1 */ + /* Traverse the postfix string to check if --> Number of operands = Number of operators + 1 + */ for (int i = 0; i < postfix.length(); i++) { char token = postfix.charAt(i); @@ -59,8 +60,8 @@ public class PostfixToInfix { /* Operand count is set to 2 because:- * - * 1) the previous set of operands & operators combined have become a single valid expression, - * which could be considered/assigned as a single operand. + * 1) the previous set of operands & operators combined have become a single valid + * expression, which could be considered/assigned as a single operand. * * 2) the operand in the current iteration. */ @@ -123,7 +124,6 @@ public class PostfixToInfix { assert getPostfixToInfix("AB+CD+*").equals("((A+B)*(C+D))"); assert getPostfixToInfix("AB+C+D+").equals("(((A+B)+C)+D)"); assert getPostfixToInfix("ABCDE^*/-").equals("(A-(B/(C*(D^E))))"); - assert getPostfixToInfix("AB+CD^/E*FGH+-^") - .equals("((((A+B)/(C^D))*E)^(F-(G+H)))"); + assert getPostfixToInfix("AB+CD^/E*FGH+-^").equals("((((A+B)/(C^D))*E)^(F-(G+H)))"); } } diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/ReverseStack.java b/src/main/java/com/thealgorithms/datastructures/stacks/ReverseStack.java index 1dd9fe11..f269d08b 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/ReverseStack.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/ReverseStack.java @@ -12,9 +12,7 @@ public class ReverseStack { public static void main(String[] args) { Scanner sc = new Scanner(System.in); - System.out.println( - "Enter the number of elements you wish to insert in the stack" - ); + System.out.println("Enter the number of elements you wish to insert in the stack"); int n = sc.nextInt(); int i; Stack stack = new Stack(); @@ -36,28 +34,29 @@ public class ReverseStack { return; } - //Store the topmost element + // Store the topmost element int element = stack.peek(); - //Remove the topmost element + // Remove the topmost element stack.pop(); - //Reverse the stack for the leftover elements + // Reverse the stack for the leftover elements reverseStack(stack); - //Insert the topmost element to the bottom of the stack + // Insert the topmost element to the bottom of the stack insertAtBottom(stack, element); } private static void insertAtBottom(Stack stack, int element) { if (stack.isEmpty()) { - //When stack is empty, insert the element so it will be present at the bottom of the stack + // When stack is empty, insert the element so it will be present at the bottom of the + // stack stack.push(element); return; } int ele = stack.peek(); - /*Keep popping elements till stack becomes empty. Push the elements once the topmost element has - moved to the bottom of the stack. + /*Keep popping elements till stack becomes empty. Push the elements once the topmost element + has moved to the bottom of the stack. */ stack.pop(); insertAtBottom(stack, element); diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/StackOfLinkedList.java b/src/main/java/com/thealgorithms/datastructures/stacks/StackOfLinkedList.java index 8f8931d1..0463018f 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/StackOfLinkedList.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/StackOfLinkedList.java @@ -23,9 +23,7 @@ class StackOfLinkedList { 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()); } } @@ -120,9 +118,7 @@ class LinkedListStack { builder.append(cur.data).append("->"); cur = cur.next; } - return builder - .replace(builder.length() - 2, builder.length(), "") - .toString(); + return builder.replace(builder.length() - 2, builder.length(), "").toString(); } /** diff --git a/src/main/java/com/thealgorithms/datastructures/trees/AVLSimple.java b/src/main/java/com/thealgorithms/datastructures/trees/AVLSimple.java index 85c44707..1032daa2 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/AVLSimple.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/AVLSimple.java @@ -3,23 +3,23 @@ package com.thealgorithms.datastructures.trees; /* * Avl is algo that balance itself while adding new alues to tree * by rotating branches of binary tree and make itself Binary seaarch tree -* there are four cases which has to tackle -* rotating - left right ,left left,right right,right left +* there are four cases which has to tackle +* rotating - left right ,left left,right right,right left Test Case: AVLTree tree=new AVLTree(); - tree.insert(20); - tree.insert(25); - tree.insert(30); - tree.insert(10); - tree.insert(5); - tree.insert(15); - tree.insert(27); - tree.insert(19); - tree.insert(16); - - tree.display(); + tree.insert(20); + tree.insert(25); + tree.insert(30); + tree.insert(10); + tree.insert(5); + tree.insert(15); + tree.insert(27); + tree.insert(19); + tree.insert(16); + + tree.display(); @@ -59,16 +59,16 @@ public class AVLSimple { } node.height = Math.max(height(node.left), height(node.right)) + 1; int bf = bf(node); - //LL case + // LL case if (bf > 1 && item < node.left.data) return rightRotate(node); - //RR case + // RR case if (bf < -1 && item > node.right.data) return leftRotate(node); - //RL case + // RL case if (bf < -1 && item < node.right.data) { node.right = rightRotate(node.right); return leftRotate(node); } - //LR case + // LR case if (bf > 1 && item > node.left.data) { node.left = leftRotate(node.left); return rightRotate(node); @@ -84,11 +84,15 @@ public class AVLSimple { private void display(Node node) { String str = ""; - if (node.left != null) str += node.left.data + "=>"; else str += - "END=>"; + if (node.left != null) + str += node.left.data + "=>"; + else + str += "END=>"; str += node.data + ""; - if (node.right != null) str += "<=" + node.right.data; else str += - "<=END"; + if (node.right != null) + str += "<=" + node.right.data; + else + str += "<=END"; System.out.println(str); if (node.left != null) display(node.left); if (node.right != null) display(node.right); diff --git a/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursiveGeneric.java b/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursiveGeneric.java index f7fecdb3..b70fcb28 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursiveGeneric.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursiveGeneric.java @@ -39,17 +39,20 @@ public class BSTRecursiveGeneric> { integerTree.add(5); integerTree.add(10); integerTree.add(9); - assert !integerTree.find(4) : "4 is not yet present in BST"; - assert integerTree.find(10) : "10 should be present in BST"; + assert !integerTree.find(4) + : "4 is not yet present in BST"; + assert integerTree.find(10) + : "10 should be present in BST"; integerTree.remove(9); - assert !integerTree.find(9) : "9 was just deleted from BST"; + assert !integerTree.find(9) + : "9 was just deleted from BST"; integerTree.remove(1); - assert !integerTree.find( - 1 - ) : "Since 1 was not present so find deleting would do no change"; + assert !integerTree.find(1) + : "Since 1 was not present so find deleting would do no change"; integerTree.add(20); integerTree.add(70); - assert integerTree.find(70) : "70 was inserted but not found"; + assert integerTree.find(70) + : "70 was inserted but not found"; /* Will print in following order 5 10 20 70 @@ -63,17 +66,20 @@ public class BSTRecursiveGeneric> { stringTree.add("banana"); stringTree.add("pineapple"); stringTree.add("date"); - assert !stringTree.find("girl") : "girl is not yet present in BST"; - assert stringTree.find("pineapple") : "10 should be present in BST"; + assert !stringTree.find("girl") + : "girl is not yet present in BST"; + assert stringTree.find("pineapple") + : "10 should be present in BST"; stringTree.remove("date"); - assert !stringTree.find("date") : "date was just deleted from BST"; + assert !stringTree.find("date") + : "date was just deleted from BST"; stringTree.remove("boy"); - assert !stringTree.find( - "boy" - ) : "Since boy was not present so deleting would do no change"; + assert !stringTree.find("boy") + : "Since boy was not present so deleting would do no change"; stringTree.add("india"); stringTree.add("hills"); - assert stringTree.find("hills") : "hills was inserted but not found"; + assert stringTree.find("hills") + : "hills was inserted but not found"; /* Will print in following order banana hills india pineapple diff --git a/src/main/java/com/thealgorithms/datastructures/trees/BinaryTree.java b/src/main/java/com/thealgorithms/datastructures/trees/BinaryTree.java index fc0db9b8..d86130df 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/BinaryTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/BinaryTree.java @@ -143,7 +143,8 @@ public class BinaryTree { 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 + } // 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 { @@ -179,7 +180,8 @@ public class BinaryTree { else { successor.parent = temp.parent; - // This if/else assigns the new node to be either the left or right child of the 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 { diff --git a/src/main/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBST.java b/src/main/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBST.java index 13246944..19fbb6a8 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBST.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBST.java @@ -24,8 +24,6 @@ public class CheckBinaryTreeIsValidBST { } return ( - isBSTUtil(node.left, min, node.data - 1) && - isBSTUtil(node.right, node.data + 1, max) - ); + isBSTUtil(node.left, min, node.data - 1) && isBSTUtil(node.right, node.data + 1, max)); } } diff --git a/src/main/java/com/thealgorithms/datastructures/trees/CheckIfBinaryTreeBalanced.java b/src/main/java/com/thealgorithms/datastructures/trees/CheckIfBinaryTreeBalanced.java index e953a37d..c4d6ff94 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/CheckIfBinaryTreeBalanced.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/CheckIfBinaryTreeBalanced.java @@ -80,11 +80,7 @@ public class CheckIfBinaryTreeBalanced { * @param depth The current depth of the node * @param isBalanced The array of length 1 keeping track of our balance */ - private int isBalancedRecursive( - BTNode node, - int depth, - boolean[] isBalanced - ) { + private int isBalancedRecursive(BTNode node, int depth, boolean[] isBalanced) { // If the node is null, we should not explore it and the height is 0 // If the tree is already not balanced, might as well stop because we // can't make it balanced now! @@ -94,11 +90,7 @@ public class CheckIfBinaryTreeBalanced { // Visit the left and right children, incrementing their depths by 1 int leftHeight = isBalancedRecursive(node.left, depth + 1, isBalanced); - int rightHeight = isBalancedRecursive( - node.right, - depth + 1, - isBalanced - ); + int rightHeight = isBalancedRecursive(node.right, depth + 1, isBalanced); // If the height of either of the left or right subtrees differ by more // than 1, we cannot be balanced @@ -174,10 +166,7 @@ public class CheckIfBinaryTreeBalanced { // The height of the subtree containing this node is the // max of the left and right subtree heighs plus 1 - subtreeHeights.put( - node, - Math.max(rightHeight, leftHeight) + 1 - ); + subtreeHeights.put(node, Math.max(rightHeight, leftHeight) + 1); // We've now visited this node, so we pop it from the stack nodeStack.pop(); diff --git a/src/main/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetric.java b/src/main/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetric.java index 0df93cef..bb592bd4 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetric.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetric.java @@ -48,10 +48,12 @@ public class CheckTreeIsSymmetric { return false; } - return isSymmetric(leftSubtreeRoot.right, rightSubtreRoot.left) && isSymmetric(leftSubtreeRoot.left, rightSubtreRoot.right); + return isSymmetric(leftSubtreeRoot.right, rightSubtreRoot.left) + && isSymmetric(leftSubtreeRoot.left, rightSubtreRoot.right); } private static boolean isInvalidSubtree(Node leftSubtreeRoot, Node rightSubtreeRoot) { - return leftSubtreeRoot == null || rightSubtreeRoot == null || leftSubtreeRoot.data != rightSubtreeRoot.data; + return leftSubtreeRoot == null || rightSubtreeRoot == null + || leftSubtreeRoot.data != rightSubtreeRoot.data; } } diff --git a/src/main/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorder.java b/src/main/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorder.java index 99b1fb4e..5c08a002 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorder.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorder.java @@ -1,7 +1,6 @@ package com.thealgorithms.datastructures.trees; import com.thealgorithms.datastructures.trees.BinaryTree.Node; - import java.util.HashMap; import java.util.Map; @@ -37,13 +36,8 @@ public class CreateBinaryTreeFromInorderPreorder { return createTreeOptimized(preorder, inorderMap, 0, 0, inorder.length); } - private static Node createTree( - final Integer[] preorder, - final Integer[] inorder, - final int preStart, - final int inStart, - final int size - ) { + private static Node createTree(final Integer[] preorder, final Integer[] inorder, + final int preStart, final int inStart, final int size) { if (size == 0) { return null; } @@ -55,32 +49,15 @@ public class CreateBinaryTreeFromInorderPreorder { } int leftNodesCount = i - inStart; int rightNodesCount = size - leftNodesCount - 1; - root.left = - createTree( - preorder, - inorder, - preStart + 1, - inStart, - leftNodesCount - ); - root.right = - createTree( - preorder, - inorder, - preStart + leftNodesCount + 1, - i + 1, - rightNodesCount - ); + root.left = createTree(preorder, inorder, preStart + 1, inStart, leftNodesCount); + root.right + = createTree(preorder, inorder, preStart + leftNodesCount + 1, i + 1, rightNodesCount); return root; } - private static Node createTreeOptimized( - final Integer[] preorder, - final Map inorderMap, - final int preStart, - final int inStart, - final int size - ) { + private static Node createTreeOptimized(final Integer[] preorder, + final Map inorderMap, final int preStart, final int inStart, + final int size) { if (size == 0) { return null; } @@ -89,22 +66,10 @@ public class CreateBinaryTreeFromInorderPreorder { int i = inorderMap.get(preorder[preStart]); int leftNodesCount = i - inStart; int rightNodesCount = size - leftNodesCount - 1; - root.left = - createTreeOptimized( - preorder, - inorderMap, - preStart + 1, - inStart, - leftNodesCount - ); - root.right = - createTreeOptimized( - preorder, - inorderMap, - preStart + leftNodesCount + 1, - i + 1, - rightNodesCount - ); + root.left + = createTreeOptimized(preorder, inorderMap, preStart + 1, inStart, leftNodesCount); + root.right = createTreeOptimized( + preorder, inorderMap, preStart + leftNodesCount + 1, i + 1, rightNodesCount); return root; } } diff --git a/src/main/java/com/thealgorithms/datastructures/trees/GenericTree.java b/src/main/java/com/thealgorithms/datastructures/trees/GenericTree.java index c22bdab0..d4bbf0c9 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/GenericTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/GenericTree.java @@ -35,9 +35,7 @@ public class GenericTree { if (node == null) { System.out.println("Enter root's data"); } else { - System.out.println( - "Enter data of parent of index " + node.data + " " + childindx - ); + System.out.println("Enter data of parent of index " + node.data + " " + childindx); } // input node = new Node(); diff --git a/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java b/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java index cd28f93c..f0f8fac8 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java @@ -34,15 +34,11 @@ public class KDTree { * @param points Array of initial points */ KDTree(Point[] points) { - if (points.length == 0) throw new IllegalArgumentException( - "Points array cannot be empty" - ); + if (points.length == 0) throw new IllegalArgumentException("Points array cannot be empty"); this.k = points[0].getDimension(); - for (Point point : points) if ( - point.getDimension() != k - ) throw new IllegalArgumentException( - "Points must have the same dimension" - ); + for (Point point : points) + if (point.getDimension() != k) + throw new IllegalArgumentException("Points must have the same dimension"); this.root = build(points, 0); } @@ -53,19 +49,13 @@ public class KDTree { * */ KDTree(int[][] pointsCoordinates) { - if (pointsCoordinates.length == 0) throw new IllegalArgumentException( - "Points array cannot be empty" - ); + if (pointsCoordinates.length == 0) + throw new IllegalArgumentException("Points array cannot be empty"); this.k = pointsCoordinates[0].length; - Point[] points = Arrays - .stream(pointsCoordinates) - .map(Point::new) - .toArray(Point[]::new); - for (Point point : points) if ( - point.getDimension() != k - ) throw new IllegalArgumentException( - "Points must have the same dimension" - ); + Point[] points = Arrays.stream(pointsCoordinates).map(Point::new).toArray(Point[] ::new); + for (Point point : points) + if (point.getDimension() != k) + throw new IllegalArgumentException("Points must have the same dimension"); this.root = build(points, 0); } @@ -125,11 +115,7 @@ public class KDTree { * * @return The distance between the two points */ - public static int comparableDistanceExceptAxis( - Point p1, - Point p2, - int axis - ) { + public static int comparableDistanceExceptAxis(Point p1, Point p2, int axis) { int distance = 0; for (int i = 0; i < p1.getDimension(); i++) { if (i == axis) continue; @@ -177,9 +163,10 @@ public class KDTree { * @return The nearest child Node */ public Node getNearChild(Point point) { - if ( - point.getCoordinate(axis) < this.point.getCoordinate(axis) - ) return left; else return right; + if (point.getCoordinate(axis) < this.point.getCoordinate(axis)) + return left; + else + return right; } /** @@ -190,9 +177,10 @@ public class KDTree { * @return The farthest child Node */ public Node getFarChild(Point point) { - if ( - point.getCoordinate(axis) < this.point.getCoordinate(axis) - ) return right; else return left; + if (point.getCoordinate(axis) < this.point.getCoordinate(axis)) + return right; + else + return left; } /** @@ -221,18 +209,11 @@ public class KDTree { if (points.length == 0) return null; int axis = depth % k; if (points.length == 1) return new Node(points[0], axis); - Arrays.sort( - points, - Comparator.comparingInt(o -> o.getCoordinate(axis)) - ); + Arrays.sort(points, Comparator.comparingInt(o -> o.getCoordinate(axis))); int median = points.length >> 1; Node node = new Node(points[median], axis); node.left = build(Arrays.copyOfRange(points, 0, median), depth + 1); - node.right = - build( - Arrays.copyOfRange(points, median + 1, points.length), - depth + 1 - ); + node.right = build(Arrays.copyOfRange(points, median + 1, points.length), depth + 1); return node; } @@ -243,9 +224,8 @@ public class KDTree { * */ public void insert(Point point) { - if (point.getDimension() != k) throw new IllegalArgumentException( - "Point has wrong dimension" - ); + if (point.getDimension() != k) + throw new IllegalArgumentException("Point has wrong dimension"); root = insert(root, point, 0); } @@ -261,9 +241,10 @@ public class KDTree { private Node insert(Node root, Point point, int depth) { int axis = depth % k; if (root == null) return new Node(point, axis); - if (point.getCoordinate(axis) < root.getAxisCoordinate()) root.left = - insert(root.left, point, depth + 1); else root.right = - insert(root.right, point, depth + 1); + if (point.getCoordinate(axis) < root.getAxisCoordinate()) + root.left = insert(root.left, point, depth + 1); + else + root.right = insert(root.right, point, depth + 1); return root; } @@ -276,9 +257,8 @@ public class KDTree { * @return The Node corresponding to the specified point */ public Optional search(Point point) { - if (point.getDimension() != k) throw new IllegalArgumentException( - "Point has wrong dimension" - ); + if (point.getDimension() != k) + throw new IllegalArgumentException("Point has wrong dimension"); return search(root, point); } @@ -323,9 +303,8 @@ public class KDTree { } else { Node left = findMin(root.left, axis); Node right = findMin(root.right, axis); - Node[] candidates = { left, root, right }; - return Arrays - .stream(candidates) + Node[] candidates = {left, root, right}; + return Arrays.stream(candidates) .filter(Objects::nonNull) .min(Comparator.comparingInt(a -> a.point.getCoordinate(axis))) .orElse(null); @@ -359,9 +338,8 @@ public class KDTree { } else { Node left = findMax(root.left, axis); Node right = findMax(root.right, axis); - Node[] candidates = { left, root, right }; - return Arrays - .stream(candidates) + Node[] candidates = {left, root, right}; + return Arrays.stream(candidates) .filter(Objects::nonNull) .max(Comparator.comparingInt(a -> a.point.getCoordinate(axis))) .orElse(null); @@ -374,8 +352,8 @@ public class KDTree { * @param point the point to delete * */ public void delete(Point point) { - Node node = search(point) - .orElseThrow(() -> new IllegalArgumentException("Point not found")); + Node node + = search(point).orElseThrow(() -> new IllegalArgumentException("Point not found")); root = delete(root, node); } @@ -398,12 +376,13 @@ public class KDTree { Node min = findMin(root.left, root.getAxis()); root.point = min.point; root.left = delete(root.left, min); - } else return null; + } else + return null; } - if ( - root.getAxisCoordinate() < node.point.getCoordinate(root.getAxis()) - ) root.left = delete(root.left, node); else root.right = - delete(root.right, node); + if (root.getAxisCoordinate() < node.point.getCoordinate(root.getAxis())) + root.left = delete(root.left, node); + else + root.right = delete(root.right, node); return root; } @@ -427,17 +406,12 @@ public class KDTree { if (root == null) return nearest; if (root.point.equals(point)) return root; int distance = Point.comparableDistance(root.point, point); - int distanceExceptAxis = Point.comparableDistanceExceptAxis( - root.point, - point, - root.getAxis() - ); - if (distance < Point.comparableDistance(nearest.point, point)) nearest = - root; + int distanceExceptAxis + = Point.comparableDistanceExceptAxis(root.point, point, root.getAxis()); + if (distance < Point.comparableDistance(nearest.point, point)) nearest = root; nearest = findNearest(root.getNearChild(point), point, nearest); - if ( - distanceExceptAxis < Point.comparableDistance(nearest.point, point) - ) nearest = findNearest(root.getFarChild(point), point, nearest); + if (distanceExceptAxis < Point.comparableDistance(nearest.point, point)) + nearest = findNearest(root.getFarChild(point), point, nearest); return nearest; } } diff --git a/src/main/java/com/thealgorithms/datastructures/trees/LCA.java b/src/main/java/com/thealgorithms/datastructures/trees/LCA.java index 1fe83e0c..d7bdb0af 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/LCA.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/LCA.java @@ -8,17 +8,17 @@ public class LCA { private static Scanner scanner = new Scanner(System.in); public static void main(String[] args) { - //The adjacency list representation of a tree: + // The adjacency list representation of a tree: ArrayList> adj = new ArrayList<>(); - //v is the number of vertices and e is the number of edges + // v is the number of vertices and e is the number of edges int v = scanner.nextInt(), e = v - 1; for (int i = 0; i < v; i++) { adj.add(new ArrayList()); } - //Storing the given tree as an adjacency list + // Storing the given tree as an adjacency list int to, from; for (int i = 0; i < e; i++) { to = scanner.nextInt(); @@ -28,19 +28,19 @@ public class LCA { adj.get(from).add(to); } - //parent[v1] gives parent of a vertex v1 + // parent[v1] gives parent of a vertex v1 int[] parent = new int[v]; - //depth[v1] gives depth of vertex v1 with respect to the root + // depth[v1] gives depth of vertex v1 with respect to the root int[] depth = new int[v]; - //Assuming the tree to be rooted at 0, hence calculating parent and depth of every vertex + // Assuming the tree to be rooted at 0, hence calculating parent and depth of every vertex dfs(adj, 0, -1, parent, depth); - //Inputting the two vertices whose LCA is to be calculated + // Inputting the two vertices whose LCA is to be calculated int v1 = scanner.nextInt(), v2 = scanner.nextInt(); - //Outputting the LCA + // Outputting the LCA System.out.println(getLCA(v1, v2, depth, parent)); } @@ -54,12 +54,7 @@ public class LCA { * @param depth An array to store depth of all vertices */ private static void dfs( - ArrayList> adj, - int s, - int p, - int[] parent, - int[] depth - ) { + ArrayList> adj, int s, int p, int[] parent, int[] depth) { for (int adjacent : adj.get(s)) { if (adjacent != p) { parent[adjacent] = s; diff --git a/src/main/java/com/thealgorithms/datastructures/trees/LazySegmentTree.java b/src/main/java/com/thealgorithms/datastructures/trees/LazySegmentTree.java index a98ec9dd..b5a9db9f 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/LazySegmentTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/LazySegmentTree.java @@ -24,7 +24,8 @@ public class LazySegmentTree { this.right = null; } - /** Update the value of this node with the given value diff. + /** + * Update the value of this node with the given value diff. * * @param diff The value to add to every index of this node range. */ @@ -33,7 +34,8 @@ public class LazySegmentTree { this.value += (this.end - this.start) * diff; } - /** Shift the lazy value of this node to its children. + /** + * Shift the lazy value of this node to its children. */ public void shift() { if (lazy == 0) return; @@ -44,7 +46,8 @@ public class LazySegmentTree { this.lazy = 0; } - /** Create a new node that is the sum of this node and the given node. + /** + * Create a new node that is the sum of this node and the given node. * * @param left The left Node of merging * @param right The right Node of merging @@ -53,11 +56,7 @@ public class LazySegmentTree { static Node merge(Node left, Node right) { if (left == null) return right; if (right == null) return left; - Node result = new Node( - left.start, - right.end, - left.value + right.value - ); + Node result = new Node(left.start, right.end, left.value + right.value); result.left = left; result.right = right; return result; @@ -78,7 +77,8 @@ public class LazySegmentTree { private final Node root; - /** Create a new LazySegmentTree with the given array. + /** + * Create a new LazySegmentTree with the given array. * * @param array The array to create the LazySegmentTree from. */ @@ -86,7 +86,8 @@ public class LazySegmentTree { this.root = buildTree(array, 0, array.length); } - /** Build a new LazySegmentTree from the given array in O(n) time. + /** + * Build a new LazySegmentTree from the given array in O(n) time. * * @param array The array to build the LazySegmentTree from. * @param start The start index of the current node. @@ -101,7 +102,8 @@ public class LazySegmentTree { return Node.merge(left, right); } - /** Update the value of given range with the given value diff in O(log n) time. + /** + * Update the value of given range with the given value diff in O(log n) time. * * @param left The left index of the range to update. * @param right The right index of the range to update. @@ -121,7 +123,8 @@ public class LazySegmentTree { curr.value = merge.value; } - /** Get Node of given range in O(log n) time. + /** + * Get Node of given range in O(log n) time. * * @param left The left index of the range to update. * @param right The right index of the range to update. @@ -131,10 +134,7 @@ public class LazySegmentTree { if (left <= curr.start && curr.end <= right) return curr; if (left >= curr.end || right <= curr.start) return null; curr.shift(); - return Node.merge( - getRange(left, right, curr.left), - getRange(left, right, curr.right) - ); + return Node.merge(getRange(left, right, curr.left), getRange(left, right, curr.right)); } public int getRange(int left, int right) { diff --git a/src/main/java/com/thealgorithms/datastructures/trees/RedBlackBST.java b/src/main/java/com/thealgorithms/datastructures/trees/RedBlackBST.java index 7103a9ea..fbb51701 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/RedBlackBST.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/RedBlackBST.java @@ -28,14 +28,8 @@ public class RedBlackBST { return; } printTree(node.left); - System.out.print( - ((node.color == R) ? " R " : " B ") + - "Key: " + - node.key + - " Parent: " + - node.p.key + - "\n" - ); + System.out.print(((node.color == R) ? " R " : " B ") + "Key: " + node.key + + " Parent: " + node.p.key + "\n"); printTree(node.right); } @@ -43,14 +37,8 @@ public class RedBlackBST { if (node == nil) { return; } - System.out.print( - ((node.color == R) ? " R " : " B ") + - "Key: " + - node.key + - " Parent: " + - node.p.key + - "\n" - ); + System.out.print(((node.color == R) ? " R " : " B ") + "Key: " + node.key + + " Parent: " + node.p.key + "\n"); printTreepre(node.left); printTreepre(node.right); } diff --git a/src/main/java/com/thealgorithms/datastructures/trees/SameTreesCheck.java b/src/main/java/com/thealgorithms/datastructures/trees/SameTreesCheck.java index 6a2258b5..aede2a23 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/SameTreesCheck.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/SameTreesCheck.java @@ -5,9 +5,8 @@ import java.util.Deque; /** * Given 2 binary trees. - * This code checks whether they are the same (structurally identical and have the same values) or not. - *

- * Example: + * This code checks whether they are the same (structurally identical and have the same values) or + * not.

Example: * 1. Binary trees: * 1 1 * / \ / \ diff --git a/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree.java b/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree.java index e24db38d..d7674f4a 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree.java @@ -26,21 +26,14 @@ public class SegmentTree { } int mid = start + (end - start) / 2; - this.seg_t[index] = - constructTree(arr, start, mid, index * 2 + 1) + - constructTree(arr, mid + 1, end, index * 2 + 2); + this.seg_t[index] = constructTree(arr, start, mid, index * 2 + 1) + + constructTree(arr, mid + 1, end, index * 2 + 2); return this.seg_t[index]; } /* A function which will update the value at a index i. This will be called by the update function internally*/ - private void updateTree( - int start, - int end, - int index, - int diff, - int seg_index - ) { + private void updateTree(int start, int end, int index, int diff, int seg_index) { if (index < start || index > end) { return; } @@ -64,14 +57,9 @@ public class SegmentTree { updateTree(0, n - 1, index, diff, 0); } - /* A function to get the sum of the elements from index l to index r. This will be called internally*/ - private int getSumTree( - int start, - int end, - int q_start, - int q_end, - int seg_index - ) { + /* A function to get the sum of the elements from index l to index r. This will be called + * internally*/ + private int getSumTree(int start, int end, int q_start, int q_end, int seg_index) { if (q_start <= start && q_end >= end) { return this.seg_t[seg_index]; } @@ -81,10 +69,8 @@ public class SegmentTree { } int mid = start + (end - start) / 2; - return ( - getSumTree(start, mid, q_start, q_end, seg_index * 2 + 1) + - getSumTree(mid + 1, end, q_start, q_end, seg_index * 2 + 2) - ); + return (getSumTree(start, mid, q_start, q_end, seg_index * 2 + 1) + + getSumTree(mid + 1, end, q_start, q_end, seg_index * 2 + 2)); } /* A function to query the sum of the subarray [start...end]*/ diff --git a/src/main/java/com/thealgorithms/datastructures/trees/TreeRandomNode.java b/src/main/java/com/thealgorithms/datastructures/trees/TreeRandomNode.java index 369eaf57..d9f5a6f0 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/TreeRandomNode.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/TreeRandomNode.java @@ -5,7 +5,8 @@ package com.thealgorithms.datastructures.trees; */ /* PROBLEM DESCRIPTION : - There is a Binary Search Tree given, and we are supposed to find a random node in the given binary tree. + There is a Binary Search Tree given, and we are supposed to find a random node in the given binary + tree. */ /* ALGORITHM : @@ -14,9 +15,9 @@ package com.thealgorithms.datastructures.trees; Step 3: Now use a method inOrder() that takes a node as input parameter to traverse through the binary tree in inorder fashion as also store the values in a ArrayList simultaneously. Step 4: Now define a method getRandom() that takes a node as input parameter, in this first call - the inOrder() method to store the values in the arraylist, then find the size of the binary tree and now just generate a random number between 0 to n-1. - Step 5: After generating the number display the value of the ArrayList at the generated index - Step 6: STOP + the inOrder() method to store the values in the arraylist, then find the size of the + binary tree and now just generate a random number between 0 to n-1. Step 5: After generating the + number display the value of the ArrayList at the generated index Step 6: STOP */ import java.util.ArrayList; @@ -65,7 +66,7 @@ public class TreeRandomNode { int n = list.size(); int min = 0; int max = n - 1; - //Generate random int value from 0 to n-1 + // Generate random int value from 0 to n-1 int b = (int) (Math.random() * (max - min + 1) + min); // displaying the value at the generated index int random = list.get(b); @@ -74,9 +75,10 @@ public class TreeRandomNode { } /* Explanation of the Approach : (a) Form the required binary tree - (b) Now use the inOrder() method to get the nodes in inOrder fashion and also store them in the given arraylist 'list' - (c) Using the getRandom() method generate a random number between 0 to n-1, then get the value at the generated random number - from the arraylist using get() method and finally display the result. + (b) Now use the inOrder() method to get the nodes in inOrder fashion and also store them in the + given arraylist 'list' (c) Using the getRandom() method generate a random number between 0 to n-1, + then get the value at the generated random number from the arraylist using get() method and + finally display the result. */ /* OUTPUT : First output : diff --git a/src/main/java/com/thealgorithms/datastructures/trees/TrieImp.java b/src/main/java/com/thealgorithms/datastructures/trees/TrieImp.java index 5829f920..79c66cb9 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/TrieImp.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/TrieImp.java @@ -83,57 +83,56 @@ public class TrieImp { public static void main(String[] args) { TrieImp obj = new TrieImp(); String word; - @SuppressWarnings("resource") - Scanner scan = new Scanner(System.in); + @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; + 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(); diff --git a/src/main/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversal.java b/src/main/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversal.java index 15fd348e..a42b4370 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversal.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversal.java @@ -23,7 +23,7 @@ in a tree from top to bottom and left to right, so for a tree : public class VerticalOrderTraversal { /*Function that receives a root Node and prints the tree - in Vertical Order.*/ + in Vertical Order.*/ public static ArrayList verticalTraversal(BinaryTree.Node root) { if (root == null) { return new ArrayList<>(); @@ -32,19 +32,19 @@ public class VerticalOrderTraversal { /*Queue to store the Nodes.*/ Queue queue = new LinkedList<>(); - /*Queue to store the index of particular vertical - column of a tree , with root at 0, Nodes on left - with negative index and Nodes on right with positive - index. */ + /*Queue to store the index of particular vertical + column of a tree , with root at 0, Nodes on left + with negative index and Nodes on right with positive + index. */ Queue index = new LinkedList<>(); - /*Map of Integer and ArrayList to store all the - elements in a particular index in a single arrayList - that will have a key equal to the index itself. */ + /*Map of Integer and ArrayList to store all the + elements in a particular index in a single arrayList + that will have a key equal to the index itself. */ Map> map = new HashMap<>(); /* min and max stores leftmost and right most index to - later print the tree in vertical fashion.*/ + later print the tree in vertical fashion.*/ int max = 0, min = 0; queue.offer(root); index.offer(0); @@ -52,38 +52,38 @@ public class VerticalOrderTraversal { while (!queue.isEmpty()) { if (queue.peek().left != null) { /*Adding the left Node if it is not null - and its index by subtracting 1 from it's - parent's index*/ + and its index by subtracting 1 from it's + parent's index*/ queue.offer(queue.peek().left); index.offer(index.peek() - 1); } if (queue.peek().right != null) { /*Adding the right Node if it is not null - and its index by adding 1 from it's - parent's index*/ + and its index by adding 1 from it's + parent's index*/ queue.offer(queue.peek().right); index.offer(index.peek() + 1); } /*If the map does not contains the index a new - ArrayList is created with the index as key.*/ + ArrayList is created with the index as key.*/ if (!map.containsKey(index.peek())) { ArrayList a = new ArrayList<>(); map.put(index.peek(), a); } /*For a index, corresponding Node data is added - to the respective ArrayList present at that - index. */ + to the respective ArrayList present at that + index. */ map.get(index.peek()).add(queue.peek().data); max = Math.max(max, index.peek()); min = Math.min(min, index.peek()); /*The Node and its index are removed - from their respective queues.*/ + from their respective queues.*/ index.poll(); queue.poll(); } /*Finally map data is printed here which has keys - from min to max. Each ArrayList represents a - vertical column that is added in ans ArrayList.*/ + from min to max. Each ArrayList represents a + vertical column that is added in ans ArrayList.*/ ArrayList ans = new ArrayList<>(); for (int i = min; i <= max; i++) { ans.addAll(map.get(i)); diff --git a/src/main/java/com/thealgorithms/datastructures/trees/ZigzagTraversal.java b/src/main/java/com/thealgorithms/datastructures/trees/ZigzagTraversal.java index 7aafcdf8..d5bfd68e 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/ZigzagTraversal.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/ZigzagTraversal.java @@ -17,7 +17,8 @@ import java.util.*; * This solution implements the breadth-first search (BFS) algorithm using a queue. * 1. The algorithm starts with a root node. This node is added to a queue. * 2. While the queue is not empty: - * - each time we enter the while-loop we get queue size. Queue size refers to the number of nodes at the current level. + * - each time we enter the while-loop we get queue size. Queue size refers to the number of nodes + * at the current level. * - we traverse all the level nodes in 2 ways: from left to right OR from right to left * (this state is stored on `prevLevelFromLeftToRight` variable) * - if the current node has children we add them to a queue diff --git a/src/main/java/com/thealgorithms/datastructures/trees/nearestRightKey.java b/src/main/java/com/thealgorithms/datastructures/trees/nearestRightKey.java index 773d3074..f0626c1d 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/nearestRightKey.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/nearestRightKey.java @@ -27,7 +27,7 @@ class Main { } public static int nearestRightKey(NRKTree root, int x0) { - //Check whether tree is empty + // Check whether tree is empty if (root == null) { return 0; } else { diff --git a/src/main/java/com/thealgorithms/devutils/entities/ProcessDetails.java b/src/main/java/com/thealgorithms/devutils/entities/ProcessDetails.java index 873e4636..388fb3fd 100644 --- a/src/main/java/com/thealgorithms/devutils/entities/ProcessDetails.java +++ b/src/main/java/com/thealgorithms/devutils/entities/ProcessDetails.java @@ -25,7 +25,6 @@ public class ProcessDetails { return burstTime; } - public int getWaitingTime() { return waitingTime; } diff --git a/src/main/java/com/thealgorithms/devutils/nodes/LargeTreeNode.java b/src/main/java/com/thealgorithms/devutils/nodes/LargeTreeNode.java index 7a60741d..bfd30f9f 100644 --- a/src/main/java/com/thealgorithms/devutils/nodes/LargeTreeNode.java +++ b/src/main/java/com/thealgorithms/devutils/nodes/LargeTreeNode.java @@ -54,10 +54,7 @@ public class LargeTreeNode extends TreeNode { * @see TreeNode#TreeNode(Object, Node) */ public LargeTreeNode( - E data, - LargeTreeNode parentNode, - Collection> childNodes - ) { + E data, LargeTreeNode parentNode, Collection> childNodes) { super(data, parentNode); this.childNodes = childNodes; } diff --git a/src/main/java/com/thealgorithms/devutils/nodes/Node.java b/src/main/java/com/thealgorithms/devutils/nodes/Node.java index e6be58f5..a1081783 100644 --- a/src/main/java/com/thealgorithms/devutils/nodes/Node.java +++ b/src/main/java/com/thealgorithms/devutils/nodes/Node.java @@ -20,7 +20,8 @@ public abstract class Node { /** * Empty constructor. */ - public Node() {} + public Node() { + } /** * Initializes the Nodes' data. diff --git a/src/main/java/com/thealgorithms/devutils/nodes/SimpleTreeNode.java b/src/main/java/com/thealgorithms/devutils/nodes/SimpleTreeNode.java index 7230db73..61f430bd 100644 --- a/src/main/java/com/thealgorithms/devutils/nodes/SimpleTreeNode.java +++ b/src/main/java/com/thealgorithms/devutils/nodes/SimpleTreeNode.java @@ -57,12 +57,8 @@ public class SimpleTreeNode extends TreeNode { * @param rightNode Value to which the nodes' right child reference will be * set. */ - public SimpleTreeNode( - E data, - SimpleTreeNode parentNode, - SimpleTreeNode leftNode, - SimpleTreeNode rightNode - ) { + public SimpleTreeNode(E data, SimpleTreeNode parentNode, SimpleTreeNode leftNode, + SimpleTreeNode rightNode) { super(data, parentNode); this.leftNode = leftNode; this.rightNode = rightNode; diff --git a/src/main/java/com/thealgorithms/divideandconquer/BinaryExponentiation.java b/src/main/java/com/thealgorithms/divideandconquer/BinaryExponentiation.java index 365eb48c..da45d5b9 100644 --- a/src/main/java/com/thealgorithms/divideandconquer/BinaryExponentiation.java +++ b/src/main/java/com/thealgorithms/divideandconquer/BinaryExponentiation.java @@ -5,7 +5,7 @@ package com.thealgorithms.divideandconquer; /* * Binary Exponentiation is a method to calculate a to the power of b. * It is used to calculate a^n in O(log n) time. - * + * * Reference: * https://iq.opengenus.org/binary-exponentiation/ */ diff --git a/src/main/java/com/thealgorithms/divideandconquer/ClosestPair.java b/src/main/java/com/thealgorithms/divideandconquer/ClosestPair.java index ad0c6867..aa453539 100644 --- a/src/main/java/com/thealgorithms/divideandconquer/ClosestPair.java +++ b/src/main/java/com/thealgorithms/divideandconquer/ClosestPair.java @@ -135,11 +135,7 @@ public final class ClosestPair { * @param first (IN Parameter) first point
* @param last (IN Parameter) last point
*/ - public void xQuickSort( - final Location[] a, - final int first, - final int last - ) { + 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 @@ -154,11 +150,7 @@ public final class ClosestPair { * @param first (IN Parameter) first point
* @param last (IN Parameter) last point
*/ - public void yQuickSort( - final Location[] a, - final int first, - final int last - ) { + 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 @@ -186,13 +178,7 @@ public final class ClosestPair { // divide-left array System.arraycopy(divideArray, 0, leftArray, 0, divideX); // divide-right array - System.arraycopy( - divideArray, - divideX, - rightArray, - 0, - indexNum - divideX - ); + System.arraycopy(divideArray, divideX, rightArray, 0, indexNum - divideX); double minLeftArea; // Minimum length of left array double minRightArea; // Minimum length of right array diff --git a/src/main/java/com/thealgorithms/divideandconquer/SkylineAlgorithm.java b/src/main/java/com/thealgorithms/divideandconquer/SkylineAlgorithm.java index f7ba384c..610b1b78 100644 --- a/src/main/java/com/thealgorithms/divideandconquer/SkylineAlgorithm.java +++ b/src/main/java/com/thealgorithms/divideandconquer/SkylineAlgorithm.java @@ -92,16 +92,10 @@ public class SkylineAlgorithm { * @param right the skyline of the right part of points * @return left the final skyline */ - public ArrayList produceFinalSkyLine( - ArrayList left, - ArrayList right - ) { + 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 - ) { + if (left.get(i).x == left.get(i + 1).x && left.get(i).y > left.get(i + 1).y) { left.remove(i); i--; } @@ -172,10 +166,7 @@ public class SkylineAlgorithm { */ 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 ((this.x < p1.x && this.y <= p1.y) || (this.x <= p1.x && this.y < p1.y)); } } diff --git a/src/main/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplication.java b/src/main/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplication.java index 7fe4fe18..4c25066a 100644 --- a/src/main/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplication.java +++ b/src/main/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplication.java @@ -4,12 +4,12 @@ package com.thealgorithms.divideandconquer; /* * Uses the divide and conquer approach to multiply two matrices. - * Time Complexity: O(n^2.8074) better than the O(n^3) of the standard matrix multiplication algorithm. - * Space Complexity: O(n^2) - * - * This Matrix multiplication can be performed only on square matrices + * Time Complexity: O(n^2.8074) better than the O(n^3) of the standard matrix multiplication + * algorithm. Space Complexity: O(n^2) + * + * This Matrix multiplication can be performed only on square matrices * where n is a power of 2. Order of both of the matrices are n × n. - * + * * Reference: * https://www.tutorialspoint.com/design_and_analysis_of_algorithms/design_and_analysis_of_algorithms_strassens_matrix_multiplication.htm#:~:text=Strassen's%20Matrix%20multiplication%20can%20be,matrices%20are%20n%20%C3%97%20n. * https://www.geeksforgeeks.org/strassens-matrix-multiplication/ @@ -139,5 +139,4 @@ public class StrassenMatrixMultiplication { } } } - } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/BoardPath.java b/src/main/java/com/thealgorithms/dynamicprogramming/BoardPath.java index 0f2a1428..7deb8144 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/BoardPath.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/BoardPath.java @@ -11,16 +11,16 @@ Test Case: here target is 10 int n=10; - startAlgo(); - System.out.println(bpR(0,n)); - System.out.println(endAlgo()+"ms"); - int[] strg=new int [n+1]; - startAlgo(); - System.out.println(bpRS(0,n,strg)); - System.out.println(endAlgo()+"ms"); - startAlgo(); - System.out.println(bpIS(0,n,strg)); - System.out.println(endAlgo()+"ms"); + startAlgo(); + System.out.println(bpR(0,n)); + System.out.println(endAlgo()+"ms"); + int[] strg=new int [n+1]; + startAlgo(); + System.out.println(bpRS(0,n,strg)); + System.out.println(endAlgo()+"ms"); + startAlgo(); + System.out.println(bpIS(0,n,strg)); + System.out.println(endAlgo()+"ms"); diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/BoundaryFill.java b/src/main/java/com/thealgorithms/dynamicprogramming/BoundaryFill.java index 514f9e4c..d09d2d9b 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/BoundaryFill.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/BoundaryFill.java @@ -13,11 +13,7 @@ public class BoundaryFill { * @param x_co_ordinate The x co-ordinate of which color is to be obtained * @param y_co_ordinate The y co-ordinate of which color is to be obtained */ - public static int getPixel( - int[][] image, - int x_co_ordinate, - int y_co_ordinate - ) { + public static int getPixel(int[][] image, int x_co_ordinate, int y_co_ordinate) { return image[x_co_ordinate][y_co_ordinate]; } @@ -29,11 +25,7 @@ public class BoundaryFill { * @param y_co_ordinate The y co-ordinate at which color is to be filled */ public static void putPixel( - int[][] image, - int x_co_ordinate, - int y_co_ordinate, - int new_color - ) { + int[][] image, int x_co_ordinate, int y_co_ordinate, int new_color) { image[x_co_ordinate][y_co_ordinate] = new_color; } @@ -47,75 +39,19 @@ public class BoundaryFill { * @param boundary_color The old color which is to be replaced in the image */ public static void boundaryFill( - int[][] image, - int x_co_ordinate, - int y_co_ordinate, - int new_color, - int boundary_color - ) { - if ( - x_co_ordinate >= 0 && - y_co_ordinate >= 0 && - getPixel(image, x_co_ordinate, y_co_ordinate) != new_color && - getPixel(image, x_co_ordinate, y_co_ordinate) != boundary_color - ) { + int[][] image, int x_co_ordinate, int y_co_ordinate, int new_color, int boundary_color) { + if (x_co_ordinate >= 0 && y_co_ordinate >= 0 + && getPixel(image, x_co_ordinate, y_co_ordinate) != new_color + && getPixel(image, x_co_ordinate, y_co_ordinate) != boundary_color) { putPixel(image, x_co_ordinate, y_co_ordinate, new_color); - boundaryFill( - image, - x_co_ordinate + 1, - y_co_ordinate, - new_color, - boundary_color - ); - boundaryFill( - image, - x_co_ordinate - 1, - y_co_ordinate, - new_color, - boundary_color - ); - boundaryFill( - image, - x_co_ordinate, - y_co_ordinate + 1, - new_color, - boundary_color - ); - boundaryFill( - image, - x_co_ordinate, - y_co_ordinate - 1, - new_color, - boundary_color - ); - boundaryFill( - image, - x_co_ordinate + 1, - y_co_ordinate - 1, - new_color, - boundary_color - ); - boundaryFill( - image, - x_co_ordinate - 1, - y_co_ordinate + 1, - new_color, - boundary_color - ); - boundaryFill( - image, - x_co_ordinate + 1, - y_co_ordinate + 1, - new_color, - boundary_color - ); - boundaryFill( - image, - x_co_ordinate - 1, - y_co_ordinate - 1, - new_color, - boundary_color - ); + boundaryFill(image, x_co_ordinate + 1, y_co_ordinate, new_color, boundary_color); + boundaryFill(image, x_co_ordinate - 1, y_co_ordinate, new_color, boundary_color); + boundaryFill(image, x_co_ordinate, y_co_ordinate + 1, new_color, boundary_color); + boundaryFill(image, x_co_ordinate, y_co_ordinate - 1, new_color, boundary_color); + boundaryFill(image, x_co_ordinate + 1, y_co_ordinate - 1, new_color, boundary_color); + boundaryFill(image, x_co_ordinate - 1, y_co_ordinate + 1, new_color, boundary_color); + boundaryFill(image, x_co_ordinate + 1, y_co_ordinate + 1, new_color, boundary_color); + boundaryFill(image, x_co_ordinate - 1, y_co_ordinate - 1, new_color, boundary_color); } } @@ -136,30 +72,30 @@ public class BoundaryFill { // Driver Program public static void main(String[] args) { - //Input 2D image matrix + // Input 2D image matrix int[][] image = { - { 0, 0, 0, 0, 0, 0, 0 }, - { 0, 3, 3, 3, 3, 0, 0 }, - { 0, 3, 0, 0, 3, 0, 0 }, - { 0, 3, 0, 0, 3, 3, 3 }, - { 0, 3, 3, 3, 0, 0, 3 }, - { 0, 0, 0, 3, 0, 0, 3 }, - { 0, 0, 0, 3, 3, 3, 3 }, + {0, 0, 0, 0, 0, 0, 0}, + {0, 3, 3, 3, 3, 0, 0}, + {0, 3, 0, 0, 3, 0, 0}, + {0, 3, 0, 0, 3, 3, 3}, + {0, 3, 3, 3, 0, 0, 3}, + {0, 0, 0, 3, 0, 0, 3}, + {0, 0, 0, 3, 3, 3, 3}, }; boundaryFill(image, 2, 2, 5, 3); /* Output ==> - * 0 0 0 0 0 0 0 - 0 3 3 3 3 0 0 - 0 3 5 5 3 0 0 - 0 3 5 5 3 3 3 - 0 3 3 3 5 5 3 - 0 0 0 3 5 5 3 + * 0 0 0 0 0 0 0 + 0 3 3 3 3 0 0 + 0 3 5 5 3 0 0 + 0 3 5 5 3 3 3 + 0 3 3 3 5 5 3 + 0 0 0 3 5 5 3 0 0 0 3 3 3 3 - * */ + * */ - //print 2D image matrix + // print 2D image matrix printImageArray(image); } } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsack.java b/src/main/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsack.java index c6f55560..5b17a101 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsack.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsack.java @@ -22,16 +22,15 @@ public class BruteForceKnapsack { // (1) nth item included // (2) not included else { - return Math.max(val[n - 1] + knapSack(W - wt[n - 1], wt, val, n - 1), - knapSack(W, wt, val, n - 1) - ); + return Math.max( + val[n - 1] + knapSack(W - wt[n - 1], wt, val, n - 1), knapSack(W, wt, val, n - 1)); } } // Driver code public static void main(String[] args) { - int[] val = new int[] { 60, 100, 120 }; - int[] wt = new int[] { 10, 20, 30 }; + int[] val = new int[] {60, 100, 120}; + int[] wt = new int[] {10, 20, 30}; int W = 50; int n = val.length; System.out.println(knapSack(W, wt, val, n)); diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java b/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java index 9744f3c0..5db7d39f 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java @@ -47,9 +47,7 @@ public class CatalanNumber { public static void main(String[] args) { Scanner sc = new Scanner(System.in); - System.out.println( - "Enter the number n to find nth Catalan number (n <= 50)" - ); + System.out.println("Enter the number n to find nth Catalan number (n <= 50)"); int n = sc.nextInt(); System.out.println(n + "th Catalan number is " + findNthCatalan(n)); diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/ClimbingStairs.java b/src/main/java/com/thealgorithms/dynamicprogramming/ClimbingStairs.java index 376a6532..58ba1351 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/ClimbingStairs.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/ClimbingStairs.java @@ -9,7 +9,7 @@ public class ClimbingStairs { public static int numberOfWays(int n) { - if(n == 1 || n == 0){ + if (n == 1 || n == 0) { return n; } int prev = 1; @@ -17,14 +17,13 @@ public class ClimbingStairs { int next; - for(int i = 2; i <= n; i++){ - next = curr+prev; + for (int i = 2; i <= n; i++) { + next = curr + prev; prev = curr; curr = next; } return curr; - } } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java b/src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java index d7bd476f..7d74e2a8 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java @@ -8,20 +8,12 @@ public class CoinChange { // Driver Program public static void main(String[] args) { int amount = 12; - int[] coins = { 2, 4, 5 }; + 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)); } /** @@ -67,10 +59,7 @@ public class CoinChange { for (int coin : coins) { if (coin <= i) { int sub_res = minimumCoins[i - coin]; - if ( - sub_res != Integer.MAX_VALUE && - sub_res + 1 < minimumCoins[i] - ) { + if (sub_res != Integer.MAX_VALUE && sub_res + 1 < minimumCoins[i]) { minimumCoins[i] = sub_res + 1; } } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/CountFriendsPairing.java b/src/main/java/com/thealgorithms/dynamicprogramming/CountFriendsPairing.java index 75189b61..e1872540 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/CountFriendsPairing.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/CountFriendsPairing.java @@ -1,8 +1,10 @@ -/** Author : Siddhant Swarup Mallick +/** + * Author : Siddhant Swarup Mallick * Github : https://github.com/siddhant2002 */ /** - * In mathematics, the Golomb sequence is a non-decreasing integer sequence where n-th term is equal to number of times n appears in the sequence. + * In mathematics, the Golomb sequence is a non-decreasing integer sequence where n-th term is equal + * to number of times n appears in the sequence. */ /** diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/DiceThrow.java b/src/main/java/com/thealgorithms/dynamicprogramming/DiceThrow.java index 5744e4f8..84f9cf6a 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/DiceThrow.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/DiceThrow.java @@ -15,11 +15,12 @@ Following is implementation of Dynamic Programming approach. */ // dice where every dice has 'm' faces class DP { - /* The main function that returns the number of ways to get sum 'x' with 'n' dice and 'm' with m faces. */ + /* The main function that returns the number of ways to get sum 'x' with 'n' dice and 'm' with m + * faces. */ public static long findWays(int m, int n, int x) { - /* Create a table to store the results of subproblems. - One extra row and column are used for simplicity - (Number of dice is directly used as row index and sum is directly used as column index). + /* Create a table to store the results of subproblems. + One extra row and column are used for simplicity + (Number of dice is directly used as row index and sum is directly used as column index). The entries in 0th row and 0th column are never used. */ long[][] table = new long[n + 1][x + 1]; @@ -28,7 +29,7 @@ class DP { table[1][j] = 1; } - /* Fill rest of the entries in table using recursive relation + /* Fill rest of the entries in table using recursive relation i: number of dice, j: sum */ for (int i = 2; i <= n; i++) { for (int j = 1; j <= x; j++) { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/DyanamicProgrammingKnapsack.java b/src/main/java/com/thealgorithms/dynamicprogramming/DyanamicProgrammingKnapsack.java index 3b501f66..042dff37 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/DyanamicProgrammingKnapsack.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/DyanamicProgrammingKnapsack.java @@ -27,8 +27,8 @@ public class DyanamicProgrammingKnapsack { // Driver code public static void main(String[] args) { - int[] val = new int[] { 60, 100, 120 }; - int[] wt = new int[] { 10, 20, 30 }; + int[] val = new int[] {60, 100, 120}; + int[] wt = new int[] {10, 20, 30}; int W = 50; int n = val.length; System.out.println(knapSack(W, wt, val, n)); diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/EditDistance.java b/src/main/java/com/thealgorithms/dynamicprogramming/EditDistance.java index 5141e12d..bba63729 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/EditDistance.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/EditDistance.java @@ -77,13 +77,7 @@ public class EditDistance { // 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 - ); + "The minimum Edit Distance between \"" + s1 + "\" and \"" + s2 + "\" is " + ans); input.close(); } @@ -108,8 +102,7 @@ public class EditDistance { return storage[m][n]; } if (s1.charAt(0) == s2.charAt(0)) { - storage[m][n] = - editDistance(s1.substring(1), s2.substring(1), storage); + storage[m][n] = editDistance(s1.substring(1), s2.substring(1), storage); } else { int op1 = editDistance(s1, s2.substring(1), storage); int op2 = editDistance(s1.substring(1), s2, storage); diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/EggDropping.java b/src/main/java/com/thealgorithms/dynamicprogramming/EggDropping.java index eee6ab78..ef1ff494 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/EggDropping.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/EggDropping.java @@ -25,9 +25,7 @@ public class EggDropping { 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]); + 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]) { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java b/src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java index 521bb2a9..5d250cd5 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java @@ -91,21 +91,22 @@ public class Fibonacci { res = next; } return res; -} - + } + /** - * We have only defined the nth Fibonacci number in terms of the two before it. Now, we will look at Binet's formula to calculate the nth Fibonacci number in constant time. - * The Fibonacci terms maintain a ratio called golden ratio denoted by Φ, the Greek character pronounced ‘phi'. - * First, let's look at how the golden ratio is calculated: Φ = ( 1 + √5 )/2 = 1.6180339887... - * Now, let's look at Binet's formula: Sn = Φⁿ–(– Φ⁻ⁿ)/√5 - * We first calculate the squareRootof5 and phi and store them in variables. Later, we apply Binet's formula to get the required term. - * Time Complexity will be O(1) - */ - + * We have only defined the nth Fibonacci number in terms of the two before it. Now, we will + * look at Binet's formula to calculate the nth Fibonacci number in constant time. The Fibonacci + * terms maintain a ratio called golden ratio denoted by Φ, the Greek character pronounced + * ‘phi'. First, let's look at how the golden ratio is calculated: Φ = ( 1 + √5 )/2 + * = 1.6180339887... Now, let's look at Binet's formula: Sn = Φⁿ–(– Φ⁻ⁿ)/√5 We first calculate + * the squareRootof5 and phi and store them in variables. Later, we apply Binet's formula to get + * the required term. Time Complexity will be O(1) + */ + public static int fibBinet(int n) { double squareRootOf5 = Math.sqrt(5); - double phi = (1 + squareRootOf5)/2; - int nthTerm = (int) ((Math.pow(phi, n) - Math.pow(-phi, -n))/squareRootOf5); + double phi = (1 + squareRootOf5) / 2; + int nthTerm = (int) ((Math.pow(phi, n) - Math.pow(-phi, -n)) / squareRootOf5); return nthTerm; } } \ No newline at end of file diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/FordFulkerson.java b/src/main/java/com/thealgorithms/dynamicprogramming/FordFulkerson.java index 1b9f1dee..63ec477c 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/FordFulkerson.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/FordFulkerson.java @@ -26,9 +26,7 @@ public class FordFulkerson { capacity[3][4] = 15; capacity[4][5] = 17; - System.out.println( - "Max capacity in networkFlow : " + networkFlow(0, 5) - ); + System.out.println("Max capacity in networkFlow : " + networkFlow(0, 5)); } private static int networkFlow(int source, int sink) { @@ -46,10 +44,7 @@ public class FordFulkerson { 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 - ) { + if (capacity[here][there] - flow[here][there] > 0 && parent.get(there) == -1) { q.add(there); parent.set(there, here); } @@ -63,11 +58,7 @@ public class FordFulkerson { 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 - ); + amount = Math.min(capacity[parent.get(p)][p] - flow[parent.get(p)][p], amount); sb.append(p + "-"); } sb.append(source); diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java b/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java index 0c15e2fe..51cd6e50 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java @@ -1,4 +1,5 @@ -/** Author : Siddhant Swarup Mallick +/** + * Author : Siddhant Swarup Mallick * Github : https://github.com/siddhant2002 */ diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java b/src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java index 13296b84..712a028e 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java @@ -5,8 +5,7 @@ package com.thealgorithms.dynamicprogramming; */ public class Knapsack { - private static int knapSack(int W, int[] wt, int[] val, int n) - throws IllegalArgumentException { + private static int knapSack(int W, int[] wt, int[] val, int n) throws IllegalArgumentException { if (wt == null || val == null) { throw new IllegalArgumentException(); } @@ -19,11 +18,7 @@ public class Knapsack { 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] - ); + 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]; } @@ -35,8 +30,8 @@ public class Knapsack { // 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[] val = new int[] {50, 100, 130}; + int[] wt = new int[] {10, 20, 40}; int W = 50; System.out.println(knapSack(W, wt, val, val.length)); } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackMemoization.java b/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackMemoization.java index bcf1909d..161a910b 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackMemoization.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackMemoization.java @@ -25,9 +25,8 @@ public class KnapsackMemoization { } // Returns the value of maximum profit using recursive approach - int solveKnapsackRecursive(int capacity, int[] weights, - int[] profits, int numOfItems, - int[][] dpTable) { + int solveKnapsackRecursive( + int capacity, int[] weights, int[] profits, int numOfItems, int[][] dpTable) { // Base condition if (numOfItems == 0 || capacity == 0) { return 0; @@ -39,11 +38,15 @@ public class KnapsackMemoization { if (weights[numOfItems - 1] > capacity) { // Store the value of function call stack in table - dpTable[numOfItems][capacity] = solveKnapsackRecursive(capacity, weights, profits, numOfItems - 1, dpTable); + dpTable[numOfItems][capacity] + = solveKnapsackRecursive(capacity, weights, profits, numOfItems - 1, dpTable); return dpTable[numOfItems][capacity]; } else { // Return value of table after storing - return dpTable[numOfItems][capacity] = Math.max((profits[numOfItems - 1] + solveKnapsackRecursive(capacity - weights[numOfItems - 1], weights, profits, numOfItems - 1, dpTable)), + return dpTable[numOfItems][capacity] + = Math.max((profits[numOfItems - 1] + + solveKnapsackRecursive(capacity - weights[numOfItems - 1], weights, + profits, numOfItems - 1, dpTable)), solveKnapsackRecursive(capacity, weights, profits, numOfItems - 1, dpTable)); } } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LevenshteinDistance.java b/src/main/java/com/thealgorithms/dynamicprogramming/LevenshteinDistance.java index f2a96187..23222bec 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/LevenshteinDistance.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/LevenshteinDistance.java @@ -32,12 +32,9 @@ public class LevenshteinDistance { if (str1.charAt(i - 1) == str2.charAt(j - 1)) { distanceMat[i][j] = distanceMat[i - 1][j - 1]; } else { - distanceMat[i][j] = - 1 + minimum( - distanceMat[i - 1][j], - distanceMat[i - 1][j - 1], - distanceMat[i][j - 1] - ); + distanceMat[i][j] = 1 + + minimum(distanceMat[i - 1][j], distanceMat[i - 1][j - 1], + distanceMat[i][j - 1]); } } } @@ -48,9 +45,7 @@ public class LevenshteinDistance { String str1 = ""; // enter your string here String str2 = ""; // enter your string here - System.out.print( - "Levenshtein distance between " + str1 + " and " + str2 + " is: " - ); + System.out.print("Levenshtein distance between " + str1 + " and " + str2 + " is: "); System.out.println(calculateLevenshteinDistance(str1, str2)); } } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestAlternatingSubsequence.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestAlternatingSubsequence.java index bfa75a90..5b508e03 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestAlternatingSubsequence.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestAlternatingSubsequence.java @@ -2,12 +2,13 @@ package com.thealgorithms.dynamicprogramming; /* - * Problem Statement: - + * Problem Statement: - * Find Longest Alternating Subsequence - * A sequence {x1, x2, .. xn} is alternating sequence if its elements satisfy one of the following relations : + * A sequence {x1, x2, .. xn} is alternating sequence if its elements satisfy one of the following + relations : - x1 < x2 > x3 < x4 > x5 < …. xn or + x1 < x2 > x3 < x4 > x5 < …. xn or x1 > x2 < x3 > x4 < x5 > …. xn */ public class LongestAlternatingSubsequence { @@ -16,16 +17,16 @@ public class LongestAlternatingSubsequence { static int AlternatingLength(int[] arr, int n) { /* - las[i][0] = Length of the longest - alternating subsequence ending at - index i and last element is - greater than its previous element + las[i][0] = Length of the longest + alternating subsequence ending at + index i and last element is + greater than its previous element - las[i][1] = Length of the longest - alternating subsequence ending at - index i and last element is - smaller than its previous - element + las[i][1] = Length of the longest + alternating subsequence ending at + index i and last element is + smaller than its previous + element */ int[][] las = new int[n][2]; // las = LongestAlternatingSubsequence @@ -61,12 +62,9 @@ public class LongestAlternatingSubsequence { } public static void main(String[] args) { - int[] arr = { 10, 22, 9, 33, 49, 50, 31, 60 }; + int[] arr = {10, 22, 9, 33, 49, 50, 31, 60}; int n = arr.length; - System.out.println( - "Length of Longest " + - "alternating subsequence is " + - AlternatingLength(arr, n) - ); + System.out.println("Length of Longest " + + "alternating subsequence is " + AlternatingLength(arr, n)); } } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestCommonSubsequence.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestCommonSubsequence.java index a2711a81..72fbc893 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestCommonSubsequence.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestCommonSubsequence.java @@ -37,11 +37,7 @@ class LongestCommonSubsequence { return lcsString(str1, str2, lcsMatrix); } - public static String lcsString( - String str1, - String str2, - int[][] 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) { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequence.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequence.java index 373077e8..e7a54f21 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequence.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequence.java @@ -56,8 +56,8 @@ public class LongestIncreasingSubsequence { } // 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) + // (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]; } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubsequence.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubsequence.java index d3d7c36b..68fd6edb 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubsequence.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubsequence.java @@ -31,32 +31,21 @@ public class LongestPalindromicSubsequence { 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) - ); + 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; + 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. + // 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 - ); + 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 { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestValidParentheses.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestValidParentheses.java index a2a5427e..f8de2d84 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestValidParentheses.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestValidParentheses.java @@ -31,10 +31,7 @@ public class LongestValidParentheses { 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); + res[i] = res[i - 1] + 2 + (index - 1 >= 0 ? res[index - 1] : 0); } } } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainMultiplication.java b/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainMultiplication.java index 7a321355..6dec5b41 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainMultiplication.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainMultiplication.java @@ -16,9 +16,7 @@ public class MatrixChainMultiplication { public static void main(String[] args) { int count = 1; while (true) { - String[] mSize = input( - "input size of matrix A(" + count + ") ( ex. 10 20 ) : " - ); + String[] mSize = input("input size of matrix A(" + count + ") ( ex. 10 20 ) : "); int col = Integer.parseInt(mSize[0]); if (col == 0) { break; @@ -30,12 +28,7 @@ public class MatrixChainMultiplication { count++; } for (Matrix m : mArray) { - System.out.format( - "A(%d) = %2d x %2d%n", - m.count(), - m.col(), - m.row() - ); + System.out.format("A(%d) = %2d x %2d%n", m.count(), m.col(), m.row()); } size = mArray.size(); diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainRecursiveTopDownMemoisation.java b/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainRecursiveTopDownMemoisation.java index 0bcff767..b1bf3152 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainRecursiveTopDownMemoisation.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainRecursiveTopDownMemoisation.java @@ -28,10 +28,8 @@ public class MatrixChainRecursiveTopDownMemoisation { return m[i][j]; } else { for (int k = i; k < j; k++) { - int q = - Lookup_Chain(m, p, i, k) + - Lookup_Chain(m, p, k + 1, j) + - (p[i - 1] * p[k] * p[j]); + int q = Lookup_Chain(m, p, i, k) + Lookup_Chain(m, p, k + 1, j) + + (p[i - 1] * p[k] * p[j]); if (q < m[i][j]) { m[i][j] = q; } @@ -40,12 +38,10 @@ public class MatrixChainRecursiveTopDownMemoisation { return m[i][j]; } - // in this code we are taking the example of 4 matrixes whose orders are 1x2,2x3,3x4,4x5 respectively - // output should be Minimum number of multiplications is 38 + // in this code we are taking the example of 4 matrixes whose orders are 1x2,2x3,3x4,4x5 + // respectively output should be Minimum number of multiplications is 38 public static void main(String[] args) { - int[] arr = { 1, 2, 3, 4, 5 }; - System.out.println( - "Minimum number of multiplications is " + Memoized_Matrix_Chain(arr) - ); + int[] arr = {1, 2, 3, 4, 5}; + System.out.println("Minimum number of multiplications is " + Memoized_Matrix_Chain(arr)); } } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/MinimumPathSum.java b/src/main/java/com/thealgorithms/dynamicprogramming/MinimumPathSum.java index 22e77c04..cd1f25a4 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/MinimumPathSum.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/MinimumPathSum.java @@ -28,22 +28,22 @@ For more information see https://www.geeksforgeeks.org/maximum-path-sum-matrix/ public class MinimumPathSum { public void testRegular() { - int[][] grid = { { 1, 3, 1 }, { 1, 5, 1 }, { 4, 2, 1 } }; + int[][] grid = {{1, 3, 1}, {1, 5, 1}, {4, 2, 1}}; System.out.println(minimumPathSum(grid)); } public void testLessColumns() { - int[][] grid = { { 1, 2 }, { 5, 6 }, { 1, 1 } }; + int[][] grid = {{1, 2}, {5, 6}, {1, 1}}; System.out.println(minimumPathSum(grid)); } public void testLessRows() { - int[][] grid = { { 2, 3, 3 }, { 7, 2, 1 } }; + int[][] grid = {{2, 3, 3}, {7, 2, 1}}; System.out.println(minimumPathSum(grid)); } public void testOneRowOneColumn() { - int[][] grid = { { 2 } }; + int[][] grid = {{2}}; System.out.println(minimumPathSum(grid)); } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/MinimumSumPartition.java b/src/main/java/com/thealgorithms/dynamicprogramming/MinimumSumPartition.java index 78676c00..c15c0186 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/MinimumSumPartition.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/MinimumSumPartition.java @@ -82,8 +82,8 @@ public class MinimumSumPartition { * 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; + 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/src/main/java/com/thealgorithms/dynamicprogramming/NewManShanksPrime.java b/src/main/java/com/thealgorithms/dynamicprogramming/NewManShanksPrime.java index d41135b1..5aa0bf02 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/NewManShanksPrime.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/NewManShanksPrime.java @@ -1,4 +1,5 @@ -/** Author : Siddhant Swarup Mallick +/** + * Author : Siddhant Swarup Mallick * Github : https://github.com/siddhant2002 */ diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java b/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java index 071880af..52ffaf19 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java @@ -22,9 +22,11 @@ public class OptimalJobScheduling { * @param numberProcesses ,refers to the number of precedent processes(N) * @param numberMachines ,refers to the number of different machines in our disposal(M) * @param Run , N*M matrix refers to the cost of running each process to each machine - * @param Transfer ,M*M symmetric matrix refers to the transportation delay for each pair of machines + * @param Transfer ,M*M symmetric matrix refers to the transportation delay for each pair of + * machines */ - public OptimalJobScheduling(int numberProcesses, int numberMachines, int[][] Run, int[][] Transfer) { + public OptimalJobScheduling( + int numberProcesses, int numberMachines, int[][] Run, int[][] Transfer) { this.numberProcesses = numberProcesses; this.numberMachines = numberMachines; this.Run = Run; @@ -35,7 +37,7 @@ public class OptimalJobScheduling { /** * Function which computes the cost of process scheduling to a number of VMs. */ - public void execute(){ + public void execute() { this.calculateCost(); this.showResults(); } @@ -43,11 +45,11 @@ public class OptimalJobScheduling { /** * Function which computes the cost of running each Process to each and every Machine */ - private void calculateCost(){ + private void calculateCost() { - for (int i=0; i < numberProcesses; i++){ //for each Process + for (int i = 0; i < numberProcesses; i++) { // for each Process - for (int j=0; j < numberMachines; j++) { //for each Machine + for (int j = 0; j < numberMachines; j++) { // for each Machine Cost[i][j] = runningCost(i, j); } @@ -55,10 +57,12 @@ public class OptimalJobScheduling { } /** - * Function which returns the minimum cost of running a certain Process to a certain Machine.In order for the Machine to execute the Process ,he requires the output - * of the previously executed Process, which may have been executed to the same Machine or some other.If the previous Process has been executed to another Machine,we - * have to transfer her result, which means extra cost for transferring the data from one Machine to another(if the previous Process has been executed to the same - * Machine, there is no transport cost). + * Function which returns the minimum cost of running a certain Process to a certain Machine.In + * order for the Machine to execute the Process ,he requires the output of the previously + * executed Process, which may have been executed to the same Machine or some other.If the + * previous Process has been executed to another Machine,we have to transfer her result, which + * means extra cost for transferring the data from one Machine to another(if the previous + * Process has been executed to the same Machine, there is no transport cost). * * @param process ,refers to the Process * @param machine ,refers to the Machine @@ -66,32 +70,38 @@ public class OptimalJobScheduling { */ private int runningCost(int process, int machine) { - if (process==0) //refers to the first process,which does not require for a previous one to have been executed + if (process == 0) // refers to the first process,which does not require for a previous one + // to have been executed return Run[process][machine]; else { - int[] runningCosts = new int[numberMachines]; //stores the costs of executing our Process depending on the Machine the previous one was executed + int[] runningCosts + = new int[numberMachines]; // stores the costs of executing our Process depending on + // the Machine the previous one was executed - for (int k=0; k < numberMachines; k++) //computes the cost of executing the previous process to each and every Machine - runningCosts[k] = Cost[process-1][k] + Transfer[k][machine] + Run[process][machine]; //transferring the result to our Machine and executing the Process to our Machine + for (int k = 0; k < numberMachines; k++) // computes the cost of executing the previous + // process to each and every Machine + runningCosts[k] = Cost[process - 1][k] + Transfer[k][machine] + + Run[process][machine]; // transferring the result to our Machine and executing + // the Process to our Machine - return findMin(runningCosts); //returns the minimum running cost + return findMin(runningCosts); // returns the minimum running cost } } /** * Function used in order to return the minimum Cost. - * @param cost ,an Array of size M which refers to the costs of executing a Process to each Machine + * @param cost ,an Array of size M which refers to the costs of executing a Process to each + * Machine * @return the minimum cost */ private int findMin(int[] cost) { - int min=0; + int min = 0; - for (int i=1;i - * @param b Co-ordinates of point a - * @param c Co-ordinates of point a - * @return { -1, 0, +1 } if a -→ b -→ c is a { clockwise, collinear; counterclockwise } turn. - */ - public static int orientation(Point a, Point b, Point c) { - int val = (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x); - if (val == 0) { - return 0; - } - return (val > 0) ? +1 : -1; - } - - /** - * @param p2 Co-ordinate of point to compare to. - * This function will compare the points and will return a positive integer it the - * point is greater than the argument point and a negative integer if the point is - * less than the argument point. - */ - public int compareTo(Point p2) { - if (this.y < p2.y) return -1; - if (this.y > p2.y) return +1; - if (this.x < p2.x) return -1; - if (this.x > p2.x) return +1; + /** + * Finds the orientation of ordered triplet. + * + * @param a Co-ordinates of point a + * @param b Co-ordinates of point a + * @param c Co-ordinates of point a + * @return { -1, 0, +1 } if a -→ b -→ c is a { clockwise, collinear; counterclockwise } + * turn. + */ + public static int orientation(Point a, Point b, Point c) { + int val = (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x); + if (val == 0) { return 0; } + return (val > 0) ? +1 : -1; + } - /** - * A helper function that will let us sort points by their polar order - * This function will compare the angle between 2 polar Co-ordinates - * - * @return the comparator - */ - public Comparator polarOrder() { - return new PolarOrder(); - } + /** + * @param p2 Co-ordinate of point to compare to. + * This function will compare the points and will return a positive integer it the + * point is greater than the argument point and a negative integer if the point is + * less than the argument point. + */ + public int compareTo(Point p2) { + if (this.y < p2.y) return -1; + if (this.y > p2.y) return +1; + if (this.x < p2.x) return -1; + if (this.x > p2.x) return +1; + return 0; + } - private class PolarOrder implements Comparator { - public int compare(Point p1, Point p2) { - int dx1 = p1.x - x; - int dy1 = p1.y - y; - int dx2 = p2.x - x; - int dy2 = p2.y - y; + /** + * A helper function that will let us sort points by their polar order + * This function will compare the angle between 2 polar Co-ordinates + * + * @return the comparator + */ + public Comparator polarOrder() { + return new PolarOrder(); + } - if (dy1 >= 0 && dy2 < 0) return -1; // q1 above; q2 below - else if (dy2 >= 0 && dy1 < 0) return +1; // q1 below; q2 above - else if (dy1 == 0 && dy2 == 0) { // 3-collinear and horizontal - if (dx1 >= 0 && dx2 < 0) return -1; - else if (dx2 >= 0 && dx1 < 0) return +1; - else return 0; - } else return -orientation(Point.this, p1, p2); // both above or below - } - } + private class PolarOrder implements Comparator { + public int compare(Point p1, Point p2) { + int dx1 = p1.x - x; + int dy1 = p1.y - y; + int dx2 = p2.x - x; + int dy2 = p2.y - y; - /** - * Override of the toString method, necessary to compute the difference - * between the expected result and the derived result - * - * @return a string representation of any given 2D point in the format (x, y) - */ - @Override - public String toString() { - return "(" + x + ", " + y + ")"; + if (dy1 >= 0 && dy2 < 0) + return -1; // q1 above; q2 below + else if (dy2 >= 0 && dy1 < 0) + return +1; // q1 below; q2 above + else if (dy1 == 0 && dy2 == 0) { // 3-collinear and horizontal + if (dx1 >= 0 && dx2 < 0) + return -1; + else if (dx2 >= 0 && dx1 < 0) + return +1; + else + return 0; + } else + return -orientation(Point.this, p1, p2); // both above or below } } + + /** + * Override of the toString method, necessary to compute the difference + * between the expected result and the derived result + * + * @return a string representation of any given 2D point in the format (x, y) + */ + @Override + public String toString() { + return "(" + x + ", " + y + ")"; + } + } } diff --git a/src/main/java/com/thealgorithms/io/BufferedReader.java b/src/main/java/com/thealgorithms/io/BufferedReader.java index 1012ce79..8bd96cc9 100644 --- a/src/main/java/com/thealgorithms/io/BufferedReader.java +++ b/src/main/java/com/thealgorithms/io/BufferedReader.java @@ -13,181 +13,175 @@ import java.io.InputStream; */ public class BufferedReader { - private static final int DEFAULT_BUFFER_SIZE = 5; + private static final int DEFAULT_BUFFER_SIZE = 5; - /** - * Maximum number of bytes the buffer can hold. - * Value is changed when encountered Eof to not - * cause overflow read of 0 bytes - */ + /** + * Maximum number of bytes the buffer can hold. + * Value is changed when encountered Eof to not + * cause overflow read of 0 bytes + */ - private int bufferSize; - private final byte[] buffer; + private int bufferSize; + private final byte[] buffer; - /** - * posRead -> indicates the next byte to read - */ - private int posRead = 0, bufferPos = 0; + /** + * posRead -> indicates the next byte to read + */ + private int posRead = 0, bufferPos = 0; - private boolean foundEof = false; + private boolean foundEof = false; - private InputStream input; + private InputStream input; - public BufferedReader(byte[] input) throws IOException { - this(new ByteArrayInputStream(input)); - } - - public BufferedReader(InputStream input) throws IOException { - this(input, DEFAULT_BUFFER_SIZE); - } - - public BufferedReader(InputStream input, int bufferSize) throws IOException { - this.input = input; - if (input.available() == -1) - throw new IOException("Empty or already closed stream provided"); - - this.bufferSize = bufferSize; - buffer = new byte[bufferSize]; - } - - /** - * Reads a single byte from the stream - */ - public int read() throws IOException { - if (needsRefill()) { - if (foundEof) - return -1; - // the buffer is empty, or the buffer has - // been completely read and needs to be refilled - refill(); + public BufferedReader(byte[] input) throws IOException { + this(new ByteArrayInputStream(input)); } - return buffer[posRead++] & 0xff; // read and un-sign it - } - /** - * Number of bytes not yet been read - */ - - public int available() throws IOException { - int available = input.available(); - if (needsRefill()) - // since the block is already empty, - // we have no responsibility yet - return available; - return bufferPos - posRead + available; - } - - /** - * Returns the next character - */ - - public int peek() throws IOException { - return peek(1); - } - - /** - * Peeks and returns a value located at next {n} - */ - - public int peek(int n) throws IOException { - int available = available(); - if (n >= available) - throw new IOException("Out of range, available %d, but trying with %d" - .formatted(available, n)); - pushRefreshData(); - - if (n >= bufferSize) - throw new IllegalAccessError("Cannot peek %s, maximum upto %s (Buffer Limit)" - .formatted(n, bufferSize)); - return buffer[n]; - } - - /** - * Removes the already read bytes from the buffer - * in-order to make space for new bytes to be filled up. - *

- * This may also do the job to read first time data (whole buffer is empty) - */ - - private void pushRefreshData() throws IOException { - for (int i = posRead, j = 0; i < bufferSize; i++, j++) - buffer[j] = buffer[i]; - - bufferPos -= posRead; - posRead = 0; - - // fill out the spaces that we've - // emptied - justRefill(); - } - - /** - * Reads one complete block of size {bufferSize} - * if found eof, the total length of array will - * be that of what's available - * - * @return a completed block - */ - public byte[] readBlock() throws IOException { - pushRefreshData(); - - byte[] cloned = new byte[bufferSize]; - // arraycopy() function is better than clone() - if (bufferPos >= 0) - System.arraycopy(buffer, - 0, - cloned, - 0, - // important to note that, bufferSize does not stay constant - // once the class is defined. See justRefill() function - bufferSize); - // we assume that already a chunk - // has been read - refill(); - return cloned; - } - - private boolean needsRefill() { - return bufferPos == 0 || posRead == bufferSize; - } - - private void refill() throws IOException { - posRead = 0; - bufferPos = 0; - justRefill(); - } - - private void justRefill() throws IOException { - assertStreamOpen(); - - // try to fill in the maximum we can until - // we reach EOF - while (bufferPos < bufferSize) { - int read = input.read(); - if (read == -1) { - // reached end-of-file, no more data left - // to be read - foundEof = true; - // rewrite the BUFFER_SIZE, to know that we've reached - // EOF when requested refill - bufferSize = bufferPos; - } - buffer[bufferPos++] = (byte) read; + public BufferedReader(InputStream input) throws IOException { + this(input, DEFAULT_BUFFER_SIZE); } - } - private void assertStreamOpen() { - if (input == null) - throw new IllegalStateException("Input Stream already closed!"); - } + public BufferedReader(InputStream input, int bufferSize) throws IOException { + this.input = input; + if (input.available() == -1) + throw new IOException("Empty or already closed stream provided"); - public void close() throws IOException { - if (input != null) { - try { - input.close(); - } finally { - input = null; - } + this.bufferSize = bufferSize; + buffer = new byte[bufferSize]; + } + + /** + * Reads a single byte from the stream + */ + public int read() throws IOException { + if (needsRefill()) { + if (foundEof) return -1; + // the buffer is empty, or the buffer has + // been completely read and needs to be refilled + refill(); + } + return buffer[posRead++] & 0xff; // read and un-sign it + } + + /** + * Number of bytes not yet been read + */ + + public int available() throws IOException { + int available = input.available(); + if (needsRefill()) + // since the block is already empty, + // we have no responsibility yet + return available; + return bufferPos - posRead + available; + } + + /** + * Returns the next character + */ + + public int peek() throws IOException { + return peek(1); + } + + /** + * Peeks and returns a value located at next {n} + */ + + public int peek(int n) throws IOException { + int available = available(); + if (n >= available) + throw new IOException( + "Out of range, available %d, but trying with %d".formatted(available, n)); + pushRefreshData(); + + if (n >= bufferSize) + throw new IllegalAccessError( + "Cannot peek %s, maximum upto %s (Buffer Limit)".formatted(n, bufferSize)); + return buffer[n]; + } + + /** + * Removes the already read bytes from the buffer + * in-order to make space for new bytes to be filled up. + *

+ * This may also do the job to read first time data (whole buffer is empty) + */ + + private void pushRefreshData() throws IOException { + for (int i = posRead, j = 0; i < bufferSize; i++, j++) buffer[j] = buffer[i]; + + bufferPos -= posRead; + posRead = 0; + + // fill out the spaces that we've + // emptied + justRefill(); + } + + /** + * Reads one complete block of size {bufferSize} + * if found eof, the total length of array will + * be that of what's available + * + * @return a completed block + */ + public byte[] readBlock() throws IOException { + pushRefreshData(); + + byte[] cloned = new byte[bufferSize]; + // arraycopy() function is better than clone() + if (bufferPos >= 0) + System.arraycopy(buffer, 0, cloned, 0, + // important to note that, bufferSize does not stay constant + // once the class is defined. See justRefill() function + bufferSize); + // we assume that already a chunk + // has been read + refill(); + return cloned; + } + + private boolean needsRefill() { + return bufferPos == 0 || posRead == bufferSize; + } + + private void refill() throws IOException { + posRead = 0; + bufferPos = 0; + justRefill(); + } + + private void justRefill() throws IOException { + assertStreamOpen(); + + // try to fill in the maximum we can until + // we reach EOF + while (bufferPos < bufferSize) { + int read = input.read(); + if (read == -1) { + // reached end-of-file, no more data left + // to be read + foundEof = true; + // rewrite the BUFFER_SIZE, to know that we've reached + // EOF when requested refill + bufferSize = bufferPos; + } + buffer[bufferPos++] = (byte) read; + } + } + + private void assertStreamOpen() { + if (input == null) throw new IllegalStateException("Input Stream already closed!"); + } + + public void close() throws IOException { + if (input != null) { + try { + input.close(); + } finally { + input = null; + } + } } - } } diff --git a/src/main/java/com/thealgorithms/maths/ADTFraction.java b/src/main/java/com/thealgorithms/maths/ADTFraction.java index d0eaddfa..1ffd3d67 100644 --- a/src/main/java/com/thealgorithms/maths/ADTFraction.java +++ b/src/main/java/com/thealgorithms/maths/ADTFraction.java @@ -21,11 +21,8 @@ public record ADTFraction(int numerator, int denominator) { * @return A new {@code ADTFraction} containing the result of the operation */ public ADTFraction plus(ADTFraction fraction) { - var numerator = - this.denominator * - fraction.numerator + - this.numerator * - fraction.denominator; + var numerator + = this.denominator * fraction.numerator + this.numerator * fraction.denominator; var denominator = this.denominator * fraction.denominator; return new ADTFraction(numerator, denominator); } @@ -64,7 +61,8 @@ public record ADTFraction(int numerator, int denominator) { /** * Calculates the result of the fraction. * - * @return The numerical result of the division between {@code numerator} and {@code denominator} + * @return The numerical result of the division between {@code numerator} and {@code + * denominator} */ public float value() { return (float) this.numerator / this.denominator; diff --git a/src/main/java/com/thealgorithms/maths/AbsoluteMin.java b/src/main/java/com/thealgorithms/maths/AbsoluteMin.java index d5b27848..a8796ae4 100644 --- a/src/main/java/com/thealgorithms/maths/AbsoluteMin.java +++ b/src/main/java/com/thealgorithms/maths/AbsoluteMin.java @@ -15,12 +15,9 @@ public class AbsoluteMin { throw new IllegalArgumentException("Numbers array cannot be empty"); } - var absMinWrapper = new Object() { - int value = numbers[0]; - }; + var absMinWrapper = new Object() { int value = numbers[0]; }; - Arrays - .stream(numbers) + Arrays.stream(numbers) .skip(1) .filter(number -> Math.abs(number) < Math.abs(absMinWrapper.value)) .forEach(number -> absMinWrapper.value = number); diff --git a/src/main/java/com/thealgorithms/maths/AliquotSum.java b/src/main/java/com/thealgorithms/maths/AliquotSum.java index 6eb18f26..b9c7d381 100644 --- a/src/main/java/com/thealgorithms/maths/AliquotSum.java +++ b/src/main/java/com/thealgorithms/maths/AliquotSum.java @@ -18,28 +18,24 @@ public class AliquotSum { * @return aliquot sum of given {@code number} */ public static int getAliquotValue(int number) { - var sumWrapper = new Object() { - int value = 0; - }; + var sumWrapper = new Object() { int value = 0; }; - IntStream - .iterate(1, i -> ++i) + IntStream.iterate(1, i -> ++i) .limit(number / 2) .filter(i -> number % i == 0) .forEach(i -> sumWrapper.value += i); return sumWrapper.value; } - - /** + + /** * Function to calculate the aliquot sum of an integer number * * @param n a positive integer * @return aliquot sum of given {@code number} */ public static int getAliquotSum(int n) { - if (n <= 0) - return -1; + if (n <= 0) return -1; int sum = 1; double root = Math.sqrt(n); /* @@ -56,9 +52,9 @@ public class AliquotSum { sum += i + n / i; } } - // if n is a perfect square then its root was added twice in above loop, so subtracting root from sum - if (root == (int) root) - sum -= root; + // if n is a perfect square then its root was added twice in above loop, so subtracting root + // from sum + if (root == (int) root) sum -= root; return sum; } } diff --git a/src/main/java/com/thealgorithms/maths/AmicableNumber.java b/src/main/java/com/thealgorithms/maths/AmicableNumber.java index 3efea0e1..f5247083 100644 --- a/src/main/java/com/thealgorithms/maths/AmicableNumber.java +++ b/src/main/java/com/thealgorithms/maths/AmicableNumber.java @@ -21,9 +21,8 @@ public class AmicableNumber { 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 */ - + /* Res -> Int Range of 1 till 3000there are 3Amicable_numbers These are 1: = ( 220,284) + 2: = ( 1184,1210) 3: = ( 2620,2924) So it worked */ } /** @@ -32,8 +31,9 @@ public class AmicableNumber { * @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 + /* 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; @@ -42,22 +42,14 @@ public class AmicableNumber { for (int j = i + 1; j <= stopValue; j++) { if (isAmicableNumber(i, j)) { countofRes++; - res.append( - "" + countofRes + ": = ( " + i + "," + j + ")" + "\t" - ); + res.append("" + countofRes + ": = ( " + i + "," + j + ")" + + "\t"); } } } - res.insert( - 0, - "Int Range of " + - startValue + - " till " + - stopValue + - " there are " + - countofRes + - " Amicable_numbers.These are \n " - ); + res.insert(0, + "Int Range of " + startValue + " till " + stopValue + " there are " + countofRes + + " Amicable_numbers.These are \n "); System.out.println(res); } @@ -69,12 +61,8 @@ public class AmicableNumber { * otherwise false */ static boolean isAmicableNumber(int numberOne, int numberTwo) { - return ( - ( - recursiveCalcOfDividerSum(numberOne, numberOne) == numberTwo && - numberOne == recursiveCalcOfDividerSum(numberTwo, numberTwo) - ) - ); + return ((recursiveCalcOfDividerSum(numberOne, numberOne) == numberTwo + && numberOne == recursiveCalcOfDividerSum(numberTwo, numberTwo))); } /** diff --git a/src/main/java/com/thealgorithms/maths/Area.java b/src/main/java/com/thealgorithms/maths/Area.java index 262669fe..b4bae5ae 100644 --- a/src/main/java/com/thealgorithms/maths/Area.java +++ b/src/main/java/com/thealgorithms/maths/Area.java @@ -135,7 +135,8 @@ public class Area { * @param height height of trapezium * @return area of given trapezium */ - public static double surfaceAreaTrapezium(final double base1, final double base2, final double height) { + public static double surfaceAreaTrapezium( + final double base1, final double base2, final double height) { if (base1 <= 0) { throw new IllegalArgumentException(POSITIVE_BASE + 1); } diff --git a/src/main/java/com/thealgorithms/maths/AutomorphicNumber.java b/src/main/java/com/thealgorithms/maths/AutomorphicNumber.java index 3ea898cc..55c4864f 100644 --- a/src/main/java/com/thealgorithms/maths/AutomorphicNumber.java +++ b/src/main/java/com/thealgorithms/maths/AutomorphicNumber.java @@ -20,15 +20,15 @@ public class AutomorphicNumber { * {@code false} */ public static boolean isAutomorphic(long n) { - if (n < 0) - return false; + if (n < 0) return false; long square = n * n; // Calculating square of the number long t = n, numberOfdigits = 0; while (t > 0) { numberOfdigits++; // Calculating number of digits in n t /= 10; } - long lastDigits = square % (long) Math.pow(10, numberOfdigits); // Extracting last Digits of square + long lastDigits + = square % (long) Math.pow(10, numberOfdigits); // Extracting last Digits of square return n == lastDigits; } @@ -40,8 +40,7 @@ public class AutomorphicNumber { * {@code false} */ public static boolean isAutomorphic2(long n) { - if (n < 0) - return false; + if (n < 0) return false; long square = n * n; // Calculating square of the number return String.valueOf(square).endsWith(String.valueOf(n)); } @@ -55,8 +54,7 @@ public class AutomorphicNumber { */ public static boolean isAutomorphic3(String s) { BigInteger n = new BigInteger(s); - if (n.signum() == -1) - return false; //if number is negative, return false + if (n.signum() == -1) return false; // if number is negative, return false BigInteger square = n.multiply(n); // Calculating square of the number return String.valueOf(square).endsWith(String.valueOf(n)); } diff --git a/src/main/java/com/thealgorithms/maths/BinomialCoefficient.java b/src/main/java/com/thealgorithms/maths/BinomialCoefficient.java index 18f0d12b..5e7271a6 100644 --- a/src/main/java/com/thealgorithms/maths/BinomialCoefficient.java +++ b/src/main/java/com/thealgorithms/maths/BinomialCoefficient.java @@ -17,13 +17,11 @@ public class BinomialCoefficient { * * @param totalObjects Total number of objects * @param numberOfObjects Number of objects to be chosen from total_objects - * @return number of ways in which no_of_objects objects can be chosen from total_objects objects + * @return number of ways in which no_of_objects objects can be chosen from total_objects + * objects */ - public static int binomialCoefficient( - int totalObjects, - int numberOfObjects - ) { + public static int binomialCoefficient(int totalObjects, int numberOfObjects) { // Base Case if (numberOfObjects > totalObjects) { return 0; @@ -35,9 +33,7 @@ public class BinomialCoefficient { } // Recursive Call - return ( - binomialCoefficient(totalObjects - 1, numberOfObjects - 1) + - binomialCoefficient(totalObjects - 1, numberOfObjects) - ); + return (binomialCoefficient(totalObjects - 1, numberOfObjects - 1) + + binomialCoefficient(totalObjects - 1, numberOfObjects)); } } diff --git a/src/main/java/com/thealgorithms/maths/CircularConvolutionFFT.java b/src/main/java/com/thealgorithms/maths/CircularConvolutionFFT.java index 693fbbe9..b66499b3 100644 --- a/src/main/java/com/thealgorithms/maths/CircularConvolutionFFT.java +++ b/src/main/java/com/thealgorithms/maths/CircularConvolutionFFT.java @@ -39,14 +39,14 @@ public class CircularConvolutionFFT { * @return The convolved signal. */ public static ArrayList fftCircularConvolution( - ArrayList a, - ArrayList b - ) { - int convolvedSize = Math.max(a.size(), b.size()); // The two signals must have the same size equal to the bigger one + ArrayList a, ArrayList b) { + int convolvedSize = Math.max( + a.size(), b.size()); // The two signals must have the same size equal to the bigger one padding(a, convolvedSize); // Zero padding the smaller signal padding(b, convolvedSize); - /* Find the FFTs of both signal. Here we use the Bluestein algorithm because we want the FFT to have the same length with the signal and not bigger */ + /* Find the FFTs of both signal. Here we use the Bluestein algorithm because we want the FFT + * to have the same length with the signal and not bigger */ FFTBluestein.fftBluestein(a, false); FFTBluestein.fftBluestein(b, false); ArrayList convolved = new ArrayList<>(); diff --git a/src/main/java/com/thealgorithms/maths/Convolution.java b/src/main/java/com/thealgorithms/maths/Convolution.java index 8a89d31a..cafb36f7 100644 --- a/src/main/java/com/thealgorithms/maths/Convolution.java +++ b/src/main/java/com/thealgorithms/maths/Convolution.java @@ -27,8 +27,9 @@ public class Convolution { C[i] = Σ (A[k]*B[i-k]) k=0 - It's obvious that: 0 <= k <= A.length , 0 <= i <= A.length + B.length - 2 and 0 <= i-k <= B.length - 1 - From the last inequality we get that: i - B.length + 1 <= k <= i and thus we get the conditions below. + It's obvious that: 0 <= k <= A.length , 0 <= i <= A.length + B.length - 2 and 0 <= i-k <= + B.length - 1 From the last inequality we get that: i - B.length + 1 <= k <= i and thus we get + the conditions below. */ for (int i = 0; i < convolved.length; i++) { convolved[i] = 0; diff --git a/src/main/java/com/thealgorithms/maths/ConvolutionFFT.java b/src/main/java/com/thealgorithms/maths/ConvolutionFFT.java index c5f48815..cacde4b8 100644 --- a/src/main/java/com/thealgorithms/maths/ConvolutionFFT.java +++ b/src/main/java/com/thealgorithms/maths/ConvolutionFFT.java @@ -43,14 +43,13 @@ public class ConvolutionFFT { * @return The convolved signal. */ public static ArrayList convolutionFFT( - ArrayList a, - ArrayList b - ) { + ArrayList a, ArrayList b) { int convolvedSize = a.size() + b.size() - 1; // The size of the convolved signal padding(a, convolvedSize); // Zero padding both signals padding(b, convolvedSize); - /* Find the FFTs of both signals (Note that the size of the FFTs will be bigger than the convolvedSize because of the extra zero padding in FFT algorithm) */ + /* Find the FFTs of both signals (Note that the size of the FFTs will be bigger than the + * convolvedSize because of the extra zero padding in FFT algorithm) */ FFT.fft(a, false); FFT.fft(b, false); ArrayList convolved = new ArrayList<>(); @@ -59,7 +58,9 @@ public class ConvolutionFFT { convolved.add(a.get(i).multiply(b.get(i))); // FFT(a)*FFT(b) } FFT.fft(convolved, true); // IFFT - convolved.subList(convolvedSize, convolved.size()).clear(); // Remove the remaining zeros after the convolvedSize. These extra zeros came from + convolved.subList(convolvedSize, convolved.size()) + .clear(); // Remove the remaining zeros after the convolvedSize. These extra zeros came + // from // paddingPowerOfTwo() method inside the fft() method. return convolved; diff --git a/src/main/java/com/thealgorithms/maths/DeterminantOfMatrix.java b/src/main/java/com/thealgorithms/maths/DeterminantOfMatrix.java index 388bf396..c1ef3fc0 100644 --- a/src/main/java/com/thealgorithms/maths/DeterminantOfMatrix.java +++ b/src/main/java/com/thealgorithms/maths/DeterminantOfMatrix.java @@ -37,10 +37,10 @@ public class DeterminantOfMatrix { return det; } - //Driver Method + // Driver Method public static void main(String[] args) { Scanner in = new Scanner(System.in); - //Input Matrix + // Input Matrix System.out.println("Enter matrix size (Square matrix only)"); int n = in.nextInt(); System.out.println("Enter matrix"); diff --git a/src/main/java/com/thealgorithms/maths/DigitalRoot.java b/src/main/java/com/thealgorithms/maths/DigitalRoot.java index 6a3541f3..78066f40 100644 --- a/src/main/java/com/thealgorithms/maths/DigitalRoot.java +++ b/src/main/java/com/thealgorithms/maths/DigitalRoot.java @@ -1,7 +1,9 @@ -/** Author : Suraj Kumar Modi +/** + * Author : Suraj Kumar Modi * https://github.com/skmodi649 */ -/** You are given a number n. You need to find the digital root of n. +/** + * You are given a number n. You need to find the digital root of n. * DigitalRoot of a number is the recursive sum of its digits until we get a single digit number. * * Test Case 1: @@ -19,7 +21,8 @@ * sum of digit of 45 is 9 which is a single * digit number. */ -/** Algorithm : +/** + * Algorithm : * Step 1 : Define a method digitalRoot(int n) * Step 2 : Define another method single(int n) * Step 3 : digitalRoot(int n) method takes output of single(int n) as input @@ -32,14 +35,16 @@ * return n; * else * return (n%10) + (n/10) - * Step 5 : In main method simply take n as input and then call digitalRoot(int n) function and print the result + * Step 5 : In main method simply take n as input and then call digitalRoot(int n) function and + * print the result */ package com.thealgorithms.maths; class DigitalRoot { public static int digitalRoot(int n) { - if (single(n) <= 9) { // If n is already single digit than simply call single method and return the value + if (single(n) <= 9) { // If n is already single digit than simply call single method and + // return the value return single(n); } else { return digitalRoot(single(n)); @@ -55,7 +60,6 @@ class DigitalRoot { } } // n / 10 is the number obtainded after removing the digit one by one // Sum of digits is stored in the Stack memory and then finally returned - } /** * Time Complexity : O((Number of Digits)^2) Auxiliary Space Complexity : diff --git a/src/main/java/com/thealgorithms/maths/DistanceFormula.java b/src/main/java/com/thealgorithms/maths/DistanceFormula.java index 89f9b429..9a2654db 100644 --- a/src/main/java/com/thealgorithms/maths/DistanceFormula.java +++ b/src/main/java/com/thealgorithms/maths/DistanceFormula.java @@ -2,23 +2,13 @@ package com.thealgorithms.maths; public class DistanceFormula { - public static double euclideanDistance( - double x1, - double y1, - double x2, - double y2 - ) { + public static double euclideanDistance(double x1, double y1, double x2, double y2) { double dX = Math.pow(x2 - x1, 2); double dY = Math.pow(y2 - x1, 2); return Math.sqrt(dX + dY); } - public static double manhattanDistance( - double x1, - double y1, - double x2, - double y2 - ) { + public static double manhattanDistance(double x1, double y1, double x2, double y2) { return Math.abs(x1 - x2) + Math.abs(y1 - y2); } diff --git a/src/main/java/com/thealgorithms/maths/DudeneyNumber.java b/src/main/java/com/thealgorithms/maths/DudeneyNumber.java index ab9fb70b..72c2065e 100644 --- a/src/main/java/com/thealgorithms/maths/DudeneyNumber.java +++ b/src/main/java/com/thealgorithms/maths/DudeneyNumber.java @@ -10,7 +10,7 @@ import java.io.*; public class DudeneyNumber { - //returns True if the number is a Dudeney number and False if it is not a Dudeney number. + // returns True if the number is a Dudeney number and False if it is not a Dudeney number. public static boolean isDudeney(int n) { // Calculating Cube Root int cube_root = (int) (Math.round((Math.pow(n, 1.0 / 3.0)))); @@ -19,7 +19,7 @@ public class DudeneyNumber { return false; } int sum_of_digits = 0; // Stores the sums of the digit of the entered number - int temp = n; //A temporary variable to store the entered number + int temp = n; // A temporary variable to store the entered number // Loop to calculate sum of the digits. while (temp > 0) { // Extracting Last digit of the number @@ -32,7 +32,7 @@ public class DudeneyNumber { temp /= 10; } - //If the cube root of the number is not equal to the sum of its digits we return false. + // If the cube root of the number is not equal to the sum of its digits we return false. return cube_root == sum_of_digits; } } diff --git a/src/main/java/com/thealgorithms/maths/EulerMethod.java b/src/main/java/com/thealgorithms/maths/EulerMethod.java index eca40076..a5c5cf8d 100644 --- a/src/main/java/com/thealgorithms/maths/EulerMethod.java +++ b/src/main/java/com/thealgorithms/maths/EulerMethod.java @@ -37,15 +37,8 @@ public class EulerMethod { // example from https://www.geeksforgeeks.org/euler-method-solving-differential-equation/ System.out.println("\n\nexample 3:"); - BiFunction exampleEquation3 = (x, y) -> - x + y + x * y; - ArrayList points3 = eulerFull( - 0, - 0.1, - 0.025, - 1, - exampleEquation3 - ); + BiFunction exampleEquation3 = (x, y) -> x + y + x * y; + ArrayList points3 = eulerFull(0, 0.1, 0.025, 1, exampleEquation3); assert points3.get(points3.size() - 1)[1] == 1.1116729841674804; points3.forEach(point -> System.out.printf("x: %1$f; y: %2$f%n", point[0], point[1])); } @@ -60,16 +53,10 @@ public class EulerMethod { * @param differentialEquation The differential equation to be solved. * @return The next y-value. */ - public static double eulerStep( - double xCurrent, - double stepSize, - double yCurrent, - BiFunction differentialEquation - ) { + public static double eulerStep(double xCurrent, double stepSize, double yCurrent, + BiFunction differentialEquation) { if (stepSize <= 0) { - throw new IllegalArgumentException( - "stepSize should be greater than zero" - ); + throw new IllegalArgumentException("stepSize should be greater than zero"); } return yCurrent + stepSize * differentialEquation.apply(xCurrent, yCurrent); } @@ -86,36 +73,26 @@ public class EulerMethod { * @return The points constituting the solution of the differential * equation. */ - public static ArrayList eulerFull( - double xStart, - double xEnd, - double stepSize, - double yStart, - BiFunction differentialEquation - ) { + public static ArrayList eulerFull(double xStart, double xEnd, double stepSize, + double yStart, BiFunction differentialEquation) { if (xStart >= xEnd) { - throw new IllegalArgumentException( - "xEnd should be greater than xStart" - ); + throw new IllegalArgumentException("xEnd should be greater than xStart"); } if (stepSize <= 0) { - throw new IllegalArgumentException( - "stepSize should be greater than zero" - ); + throw new IllegalArgumentException("stepSize should be greater than zero"); } ArrayList points = new ArrayList(); - double[] firstPoint = { xStart, yStart }; + double[] firstPoint = {xStart, yStart}; points.add(firstPoint); double yCurrent = yStart; double xCurrent = xStart; while (xCurrent < xEnd) { // Euler method for next step - yCurrent = - eulerStep(xCurrent, stepSize, yCurrent, differentialEquation); + yCurrent = eulerStep(xCurrent, stepSize, yCurrent, differentialEquation); xCurrent += stepSize; - double[] point = { xCurrent, yCurrent }; + double[] point = {xCurrent, yCurrent}; points.add(point); } diff --git a/src/main/java/com/thealgorithms/maths/FFT.java b/src/main/java/com/thealgorithms/maths/FFT.java index 998d0668..f50bec52 100644 --- a/src/main/java/com/thealgorithms/maths/FFT.java +++ b/src/main/java/com/thealgorithms/maths/FFT.java @@ -180,10 +180,7 @@ public class FFT { * @param inverse True if you want to find the inverse FFT. * @return */ - public static ArrayList fft( - ArrayList x, - boolean inverse - ) { + public static ArrayList fft(ArrayList x, boolean inverse) { /* Pad the signal with zeros if necessary */ paddingPowerOfTwo(x); int N = x.size(); @@ -220,11 +217,7 @@ public class FFT { } /* Swap the values of the signal with bit-reversal method */ - public static ArrayList fftBitReversal( - int N, - int log2N, - ArrayList x - ) { + public static ArrayList fftBitReversal(int N, int log2N, ArrayList x) { int reverse; for (int i = 0; i < N; i++) { reverse = reverseBits(i, log2N); @@ -236,11 +229,7 @@ public class FFT { } /* Divide by N if we want the inverse FFT */ - public static ArrayList inverseFFT( - int N, - boolean inverse, - ArrayList x - ) { + public static ArrayList inverseFFT(int N, boolean inverse, ArrayList x) { if (inverse) { for (int i = 0; i < x.size(); i++) { Complex z = x.get(i); diff --git a/src/main/java/com/thealgorithms/maths/FFTBluestein.java b/src/main/java/com/thealgorithms/maths/FFTBluestein.java index ffd42bd5..cd698b62 100644 --- a/src/main/java/com/thealgorithms/maths/FFTBluestein.java +++ b/src/main/java/com/thealgorithms/maths/FFTBluestein.java @@ -30,7 +30,8 @@ public class FFTBluestein { ArrayList an = new ArrayList<>(); ArrayList bn = new ArrayList<>(); - /* Initialization of the b(n) sequence (see Wikipedia's article above for the symbols used)*/ + /* Initialization of the b(n) sequence (see Wikipedia's article above for the symbols + * used)*/ for (int i = 0; i < bnSize; i++) { bn.add(new FFT.Complex()); } @@ -38,26 +39,16 @@ public class FFTBluestein { for (int i = 0; i < N; i++) { double angle = (i - N + 1) * (i - N + 1) * Math.PI / N * direction; bn.set(i, new FFT.Complex(Math.cos(angle), Math.sin(angle))); - bn.set( - bnSize - i - 1, - new FFT.Complex(Math.cos(angle), Math.sin(angle)) - ); + bn.set(bnSize - i - 1, new FFT.Complex(Math.cos(angle), Math.sin(angle))); } /* Initialization of the a(n) sequence */ for (int i = 0; i < N; i++) { double angle = -i * i * Math.PI / N * direction; - an.add( - x - .get(i) - .multiply(new FFT.Complex(Math.cos(angle), Math.sin(angle))) - ); + an.add(x.get(i).multiply(new FFT.Complex(Math.cos(angle), Math.sin(angle)))); } - ArrayList convolution = ConvolutionFFT.convolutionFFT( - an, - bn - ); + ArrayList convolution = ConvolutionFFT.convolutionFFT(an, bn); /* The final multiplication of the convolution with the b*(k) factor */ for (int i = 0; i < N; i++) { diff --git a/src/main/java/com/thealgorithms/maths/Factorial.java b/src/main/java/com/thealgorithms/maths/Factorial.java index 4c31e69d..90fcde54 100644 --- a/src/main/java/com/thealgorithms/maths/Factorial.java +++ b/src/main/java/com/thealgorithms/maths/Factorial.java @@ -21,7 +21,8 @@ public class Factorial { throw new IllegalArgumentException("number is negative"); } long factorial = 1; - for (int i = 1; i <= n; factorial *= i, ++i); + for (int i = 1; i <= n; factorial *= i, ++i) + ; return factorial; } } diff --git a/src/main/java/com/thealgorithms/maths/FastInverseSqrt.java b/src/main/java/com/thealgorithms/maths/FastInverseSqrt.java index 1e30374e..88633747 100644 --- a/src/main/java/com/thealgorithms/maths/FastInverseSqrt.java +++ b/src/main/java/com/thealgorithms/maths/FastInverseSqrt.java @@ -1,4 +1,5 @@ -/** Author : Siddhant Swarup Mallick +/** + * Author : Siddhant Swarup Mallick * Github : https://github.com/siddhant2002 */ @@ -22,7 +23,8 @@ public class FastInverseSqrt { /** * Returns the inverse square root of the given number upto 6 - 8 decimal places. - * calculates the inverse square root of the given number and returns true if calculated answer matches with given answer else returns false + * calculates the inverse square root of the given number and returns true if calculated answer + * matches with given answer else returns false */ public static boolean inverseSqrt(double number) { @@ -39,17 +41,16 @@ public class FastInverseSqrt { } /** * Returns the inverse square root of the given number upto 14 - 16 decimal places. - * calculates the inverse square root of the given number and returns true if calculated answer matches with given answer else returns false + * calculates the inverse square root of the given number and returns true if calculated answer + * matches with given answer else returns false */ } /** * OUTPUT : * Input - number = 4522 - * Output: it calculates the inverse squareroot of a number and returns true with it matches the given answer else returns false. - * 1st approach Time Complexity : O(1) - * Auxiliary Space Complexity : O(1) - * Input - number = 4522 - * Output: it calculates the inverse squareroot of a number and returns true with it matches the given answer else returns false. - * 2nd approach Time Complexity : O(1) + * Output: it calculates the inverse squareroot of a number and returns true with it matches the + * given answer else returns false. 1st approach Time Complexity : O(1) Auxiliary Space Complexity : + * O(1) Input - number = 4522 Output: it calculates the inverse squareroot of a number and returns + * true with it matches the given answer else returns false. 2nd approach Time Complexity : O(1) * Auxiliary Space Complexity : O(1) */ diff --git a/src/main/java/com/thealgorithms/maths/FibonacciJavaStreams.java b/src/main/java/com/thealgorithms/maths/FibonacciJavaStreams.java index b6a39adf..72e89f09 100644 --- a/src/main/java/com/thealgorithms/maths/FibonacciJavaStreams.java +++ b/src/main/java/com/thealgorithms/maths/FibonacciJavaStreams.java @@ -25,31 +25,24 @@ public class FibonacciJavaStreams { return Optional.of(BigDecimal.ONE); } - final List results = Stream - .iterate( - index, - x -> x.compareTo(BigDecimal.ZERO) > 0, - x -> x.subtract(BigDecimal.ONE) - ) - .reduce( - List.of(), - (list, current) -> - list.isEmpty() || list.size() < 2 - ? List.of(BigDecimal.ZERO, BigDecimal.ONE) - : List.of(list.get(1), list.get(0).add(list.get(1))), - (list1, list2) -> list1 - ); + final List results + = Stream + .iterate( + index, x -> x.compareTo(BigDecimal.ZERO) > 0, x -> x.subtract(BigDecimal.ONE)) + .reduce(List.of(), + (list, current) + -> list.isEmpty() || list.size() < 2 + ? List.of(BigDecimal.ZERO, BigDecimal.ONE) + : List.of(list.get(1), list.get(0).add(list.get(1))), + (list1, list2) -> list1); - return results.isEmpty() - ? Optional.empty() - : Optional.of(results.get(results.size() - 1)); + return results.isEmpty() ? Optional.empty() : Optional.of(results.get(results.size() - 1)); } public static void assertThat(final Object actual, final Object expected) { if (!Objects.equals(actual, expected)) { throw new AssertionError( - String.format("expected=%s but was actual=%s", expected, actual) - ); + String.format("expected=%s but was actual=%s", expected, actual)); } } @@ -91,39 +84,28 @@ public class FibonacciJavaStreams { { final Optional result = calculate(new BigDecimal(30)); assertThat(result.isPresent(), true); - result.ifPresent(value -> assertThat(value, new BigDecimal(832040)) - ); + result.ifPresent(value -> assertThat(value, new BigDecimal(832040))); } { final Optional result = calculate(new BigDecimal(40)); assertThat(result.isPresent(), true); - result.ifPresent(value -> - assertThat(value, new BigDecimal(102334155)) - ); + result.ifPresent(value -> assertThat(value, new BigDecimal(102334155))); } { final Optional result = calculate(new BigDecimal(50)); assertThat(result.isPresent(), true); - result.ifPresent(value -> - assertThat(value, new BigDecimal(12586269025L)) - ); + result.ifPresent(value -> assertThat(value, new BigDecimal(12586269025L))); } { final Optional result = calculate(new BigDecimal(100)); assertThat(result.isPresent(), true); - result.ifPresent(value -> - assertThat(value, new BigDecimal("354224848179261915075")) - ); + result.ifPresent(value -> assertThat(value, new BigDecimal("354224848179261915075"))); } { final Optional result = calculate(new BigDecimal(200)); assertThat(result.isPresent(), true); - result.ifPresent(value -> - assertThat( - value, - new BigDecimal("280571172992510140037611932413038677189525") - ) - ); + result.ifPresent(value + -> assertThat(value, new BigDecimal("280571172992510140037611932413038677189525"))); } } } diff --git a/src/main/java/com/thealgorithms/maths/FindMaxRecursion.java b/src/main/java/com/thealgorithms/maths/FindMaxRecursion.java index 837cd321..c38da196 100644 --- a/src/main/java/com/thealgorithms/maths/FindMaxRecursion.java +++ b/src/main/java/com/thealgorithms/maths/FindMaxRecursion.java @@ -17,10 +17,8 @@ public class FindMaxRecursion { 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(); + assert max(array, array.length) == Arrays.stream(array).max().getAsInt(); + assert max(array, 0, array.length - 1) == Arrays.stream(array).max().getAsInt(); } /** @@ -52,8 +50,6 @@ public class FindMaxRecursion { * @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]); + return len == 1 ? array[0] : Math.max(max(array, len - 1), array[len - 1]); } } diff --git a/src/main/java/com/thealgorithms/maths/FindMinRecursion.java b/src/main/java/com/thealgorithms/maths/FindMinRecursion.java index aeee582d..66400d23 100644 --- a/src/main/java/com/thealgorithms/maths/FindMinRecursion.java +++ b/src/main/java/com/thealgorithms/maths/FindMinRecursion.java @@ -20,10 +20,8 @@ public class FindMinRecursion { 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(); + assert min(array, 0, array.length - 1) == Arrays.stream(array).min().getAsInt(); + assert min(array, array.length) == Arrays.stream(array).min().getAsInt(); } /** @@ -55,8 +53,6 @@ public class FindMinRecursion { * @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]); + return len == 1 ? array[0] : Math.min(min(array, len - 1), array[len - 1]); } } diff --git a/src/main/java/com/thealgorithms/maths/FrizzyNumber.java b/src/main/java/com/thealgorithms/maths/FrizzyNumber.java index 48d4fb3b..3b1ff5fd 100644 --- a/src/main/java/com/thealgorithms/maths/FrizzyNumber.java +++ b/src/main/java/com/thealgorithms/maths/FrizzyNumber.java @@ -1,10 +1,10 @@ -/** Author : Siddhant Swarup Mallick +/** + * Author : Siddhant Swarup Mallick * Github : https://github.com/siddhant2002 */ /** Program description - To find the FrizzyNumber*/ - package com.thealgorithms.maths; public class FrizzyNumber { @@ -16,7 +16,7 @@ public class FrizzyNumber { * Ascending order of sums of powers of 3 = * 3^0 = 1, 3^1 = 3, 3^1 + 3^0 = 4, 3^2 + 3^0 = 9 * Ans = 9 - * + * * @param base The base whose n-th sum of powers is required * @param n Index from ascending order of sum of powers of base * @return n-th sum of powers of base @@ -24,8 +24,7 @@ public class FrizzyNumber { public static double getNthFrizzy(int base, int n) { double final1 = 0.0; int i = 0; - do - { + do { final1 += Math.pow(base, i++) * (n % 2); } while ((n /= 2) > 0); return final1; diff --git a/src/main/java/com/thealgorithms/maths/GCD.java b/src/main/java/com/thealgorithms/maths/GCD.java index 96a2b47d..3a69fcab 100644 --- a/src/main/java/com/thealgorithms/maths/GCD.java +++ b/src/main/java/com/thealgorithms/maths/GCD.java @@ -48,14 +48,10 @@ public class GCD { } public static void main(String[] args) { - int[] myIntArray = { 4, 16, 32 }; + 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 + System.out.printf("gcd(40,24)=%d gcd(24,40)=%d%n", gcd(40, 24), gcd(24, 40)); // => 8 } } diff --git a/src/main/java/com/thealgorithms/maths/Gaussian.java b/src/main/java/com/thealgorithms/maths/Gaussian.java index 9bb7c035..fd0f86d8 100644 --- a/src/main/java/com/thealgorithms/maths/Gaussian.java +++ b/src/main/java/com/thealgorithms/maths/Gaussian.java @@ -4,10 +4,7 @@ import java.util.ArrayList; public class Gaussian { - public static ArrayList gaussian( - int mat_size, - ArrayList matrix - ) { + public static ArrayList gaussian(int mat_size, ArrayList matrix) { ArrayList answerArray = new ArrayList(); int i, j = 0; @@ -27,11 +24,7 @@ public class Gaussian { } // Perform Gaussian elimination - public static double[][] gaussianElimination( - int mat_size, - int i, - double[][] mat - ) { + public static double[][] gaussianElimination(int mat_size, int i, double[][] mat) { int step = 0; for (step = 0; step < mat_size - 1; step++) { for (i = step; i < mat_size - 1; i++) { @@ -46,11 +39,7 @@ public class Gaussian { } // calculate the x_1, x_2,... values of the gaussian and save it in an arraylist. - public static ArrayList valueOfGaussian( - int mat_size, - double[][] x, - double[][] mat - ) { + public static ArrayList valueOfGaussian(int mat_size, double[][] x, double[][] mat) { ArrayList answerArray = new ArrayList(); int i, j; diff --git a/src/main/java/com/thealgorithms/maths/GenericRoot.java b/src/main/java/com/thealgorithms/maths/GenericRoot.java index 04e07d14..1058da9e 100644 --- a/src/main/java/com/thealgorithms/maths/GenericRoot.java +++ b/src/main/java/com/thealgorithms/maths/GenericRoot.java @@ -1,7 +1,8 @@ package com.thealgorithms.maths; /* - * Algorithm explanation: https://technotip.com/6774/c-program-to-find-generic-root-of-a-number/#:~:text=Generic%20Root%3A%20of%20a%20number,get%20a%20single%2Ddigit%20output.&text=For%20Example%3A%20If%20user%20input,%2B%204%20%2B%205%20%3D%2015. + * Algorithm explanation: + * https://technotip.com/6774/c-program-to-find-generic-root-of-a-number/#:~:text=Generic%20Root%3A%20of%20a%20number,get%20a%20single%2Ddigit%20output.&text=For%20Example%3A%20If%20user%20input,%2B%204%20%2B%205%20%3D%2015. */ public class GenericRoot { diff --git a/src/main/java/com/thealgorithms/maths/HarshadNumber.java b/src/main/java/com/thealgorithms/maths/HarshadNumber.java index b30ada48..854e4d55 100644 --- a/src/main/java/com/thealgorithms/maths/HarshadNumber.java +++ b/src/main/java/com/thealgorithms/maths/HarshadNumber.java @@ -12,8 +12,7 @@ public class HarshadNumber { * {@code false} */ public static boolean isHarshad(long n) { - if (n <= 0) - return false; + if (n <= 0) return false; long t = n; int sumOfDigits = 0; @@ -34,8 +33,7 @@ public class HarshadNumber { */ public static boolean isHarshad(String s) { long n = Long.valueOf(s); - if (n <= 0) - return false; + if (n <= 0) return false; int sumOfDigits = 0; for (char ch : s.toCharArray()) { diff --git a/src/main/java/com/thealgorithms/maths/JosephusProblem.java b/src/main/java/com/thealgorithms/maths/JosephusProblem.java index 1e223f0f..b878eff2 100644 --- a/src/main/java/com/thealgorithms/maths/JosephusProblem.java +++ b/src/main/java/com/thealgorithms/maths/JosephusProblem.java @@ -1,15 +1,21 @@ package com.thealgorithms.maths; -/** There are n friends that are playing a game. The friends are sitting in a circle and are numbered from 1 to n in clockwise order. More formally, moving clockwise from the ith friend brings you to the (i+1)th friend for 1 <= i < n, and moving clockwise from the nth friend brings you to the 1st friend. +/** + * There are n friends that are playing a game. The friends are sitting in a circle and are + * numbered from 1 to n in clockwise order. More formally, moving clockwise from the ith friend + * brings you to the (i+1)th friend for 1 <= i < n, and moving clockwise from the nth friend brings + * you to the 1st friend. */ -/** The rules of the game are as follows: +/** + The rules of the game are as follows: 1.Start at the 1st friend. - 2.Count the next k friends in the clockwise direction including the friend you started at. The counting wraps around the circle and may count some friends more than once. - 3.The last friend you counted leaves the circle and loses the game. - 4.If there is still more than one friend in the circle, go back to step 2 starting from the friend immediately clockwise of the friend who just lost and repeat. - 5.Else, the last friend in the circle wins the game. + 2.Count the next k friends in the clockwise direction including the friend you started at. + The counting wraps around the circle and may count some friends more than once. 3.The last friend + you counted leaves the circle and loses the game. 4.If there is still more than one friend in the + circle, go back to step 2 starting from the friend immediately clockwise of the friend who just + lost and repeat. 5.Else, the last friend in the circle wins the game. @author Kunal */ diff --git a/src/main/java/com/thealgorithms/maths/JugglerSequence.java b/src/main/java/com/thealgorithms/maths/JugglerSequence.java index da18dd64..216098fc 100644 --- a/src/main/java/com/thealgorithms/maths/JugglerSequence.java +++ b/src/main/java/com/thealgorithms/maths/JugglerSequence.java @@ -35,10 +35,7 @@ public class JugglerSequence { if (n % 2 == 0) { temp = (int) Math.floor(Math.sqrt(n)); } else { - temp = - (int) Math.floor( - Math.sqrt(n) * Math.sqrt(n) * Math.sqrt(n) - ); + temp = (int) Math.floor(Math.sqrt(n) * Math.sqrt(n) * Math.sqrt(n)); } n = temp; seq.add(n + ""); diff --git a/src/main/java/com/thealgorithms/maths/KaprekarNumbers.java b/src/main/java/com/thealgorithms/maths/KaprekarNumbers.java index a932dc77..2db05939 100644 --- a/src/main/java/com/thealgorithms/maths/KaprekarNumbers.java +++ b/src/main/java/com/thealgorithms/maths/KaprekarNumbers.java @@ -6,12 +6,12 @@ import java.util.*; public class KaprekarNumbers { /* This program demonstrates if a given number is Kaprekar Number or not. - Kaprekar Number: A Kaprekar number is an n-digit number which its square can be split into two parts where the right part has n - digits and sum of these parts is equal to the original number. */ + Kaprekar Number: A Kaprekar number is an n-digit number which its square can be split into + two parts where the right part has n digits and sum of these parts is equal to the original + number. */ // Provides a list of kaprekarNumber in a range - public static List kaprekarNumberInRange(long start, long end) - throws Exception { + public static List kaprekarNumberInRange(long start, long end) throws Exception { long n = end - start; if (n < 0) throw new Exception("Invalid range"); ArrayList list = new ArrayList<>(); @@ -34,32 +34,13 @@ public class KaprekarNumbers { BigInteger leftDigits1 = BigInteger.ZERO; BigInteger leftDigits2; if (numberSquared.toString().contains("0")) { - leftDigits1 = - new BigInteger( - numberSquared - .toString() - .substring(0, numberSquared.toString().indexOf("0")) - ); + leftDigits1 = new BigInteger( + numberSquared.toString().substring(0, numberSquared.toString().indexOf("0"))); } - leftDigits2 = - new BigInteger( - numberSquared - .toString() - .substring( - 0, - ( - numberSquared.toString().length() - - number.length() - ) - ) - ); - BigInteger rightDigits = new BigInteger( - numberSquared - .toString() - .substring( - numberSquared.toString().length() - number.length() - ) - ); + leftDigits2 = new BigInteger(numberSquared.toString().substring( + 0, (numberSquared.toString().length() - number.length()))); + BigInteger rightDigits = new BigInteger(numberSquared.toString().substring( + numberSquared.toString().length() - number.length())); String x = leftDigits1.add(rightDigits).toString(); String y = leftDigits2.add(rightDigits).toString(); return (number.equals(x)) || (number.equals(y)); diff --git a/src/main/java/com/thealgorithms/maths/KeithNumber.java b/src/main/java/com/thealgorithms/maths/KeithNumber.java index a96638b0..0ea68d50 100644 --- a/src/main/java/com/thealgorithms/maths/KeithNumber.java +++ b/src/main/java/com/thealgorithms/maths/KeithNumber.java @@ -4,42 +4,43 @@ import java.util.*; class KeithNumber { - //user-defined function that checks if the given number is Keith or not + // user-defined function that checks if the given number is Keith or not static boolean isKeith(int x) { - //List stores all the digits of the X + // List stores all the digits of the X ArrayList terms = new ArrayList(); - //n denotes the number of digits + // n denotes the number of digits int temp = x, n = 0; - //executes until the condition becomes false + // executes until the condition becomes false while (temp > 0) { - //determines the last digit of the number and add it to the List + // determines the last digit of the number and add it to the List terms.add(temp % 10); - //removes the last digit + // removes the last digit temp = temp / 10; - //increments the number of digits (n) by 1 + // increments the number of digits (n) by 1 n++; } - //reverse the List + // reverse the List Collections.reverse(terms); int next_term = 0, i = n; - //finds next term for the series - //loop executes until the condition returns true + // finds next term for the series + // loop executes until the condition returns true while (next_term < x) { next_term = 0; - //next term is the sum of previous n terms (it depends on number of digits the number has) + // next term is the sum of previous n terms (it depends on number of digits the number + // has) for (int j = 1; j <= n; j++) { next_term = next_term + terms.get(i - j); } terms.add(next_term); i++; } - //when the control comes out of the while loop, there will be two conditions: - //either next_term will be equal to x or greater than x - //if equal, the given number is Keith, else not + // when the control comes out of the while loop, there will be two conditions: + // either next_term will be equal to x or greater than x + // if equal, the given number is Keith, else not return (next_term == x); } - //driver code + // driver code public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); diff --git a/src/main/java/com/thealgorithms/maths/KrishnamurthyNumber.java b/src/main/java/com/thealgorithms/maths/KrishnamurthyNumber.java index 57972cf8..eacc75c2 100644 --- a/src/main/java/com/thealgorithms/maths/KrishnamurthyNumber.java +++ b/src/main/java/com/thealgorithms/maths/KrishnamurthyNumber.java @@ -1,52 +1,48 @@ package com.thealgorithms.maths; /* This is a program to check if a number is a Krishnamurthy number or not. -A number is a Krishnamurthy number if the sum of the factorials of the digits of the number is equal to the number itself. -For example, 1, 2 and 145 are Krishnamurthy numbers. -Krishnamurthy number is also referred to as a Strong number. +A number is a Krishnamurthy number if the sum of the factorials of the digits of the number is equal +to the number itself. For example, 1, 2 and 145 are Krishnamurthy numbers. Krishnamurthy number is +also referred to as a Strong number. */ import java.io.*; public class KrishnamurthyNumber { - //returns True if the number is a Krishnamurthy number and False if it is not. + // returns True if the number is a Krishnamurthy number and False if it is not. public static boolean isKMurthy(int n) { - //initialising the variable s that will store the sum of the factorials of the digits to 0 + // initialising the variable s that will store the sum of the factorials of the digits to 0 int s = 0; - //storing the number n in a temporary variable tmp + // storing the number n in a temporary variable tmp int tmp = n; - //Krishnamurthy numbers are positive + // Krishnamurthy numbers are positive if (n <= 0) { return false; - } //checking if the number is a Krishnamurthy number + } // checking if the number is a Krishnamurthy number else { while (n != 0) { - //initialising the variable fact that will store the factorials of the digits + // initialising the variable fact that will store the factorials of the digits int fact = 1; - //computing factorial of each digit + // computing factorial of each digit for (int i = 1; i <= n % 10; i++) { fact = fact * i; } - //computing the sum of the factorials + // computing the sum of the factorials s = s + fact; - //discarding the digit for which factorial has been calculated + // discarding the digit for which factorial has been calculated n = n / 10; } - //evaluating if sum of the factorials of the digits equals the number itself + // evaluating if sum of the factorials of the digits equals the number itself return tmp == s; } } public static void main(String[] args) throws IOException { - BufferedReader br = new BufferedReader( - new InputStreamReader(System.in) - ); - System.out.println( - "Enter a number to check if it is a Krishnamurthy number: " - ); + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + System.out.println("Enter a number to check if it is a Krishnamurthy number: "); int n = Integer.parseInt(br.readLine()); if (isKMurthy(n)) { System.out.println(n + " is a Krishnamurthy number."); diff --git a/src/main/java/com/thealgorithms/maths/LeastCommonMultiple.java b/src/main/java/com/thealgorithms/maths/LeastCommonMultiple.java index 6d365746..5c904c2d 100644 --- a/src/main/java/com/thealgorithms/maths/LeastCommonMultiple.java +++ b/src/main/java/com/thealgorithms/maths/LeastCommonMultiple.java @@ -20,9 +20,7 @@ public class LeastCommonMultiple { int num1 = input.nextInt(); System.out.println("Please enter second number >> "); int num2 = input.nextInt(); - System.out.println( - "The least common multiple of two numbers is >> " + lcm(num1, num2) - ); + System.out.println("The least common multiple of two numbers is >> " + lcm(num1, num2)); } /* diff --git a/src/main/java/com/thealgorithms/maths/LeonardoNumber.java b/src/main/java/com/thealgorithms/maths/LeonardoNumber.java index 7b9620a4..1ca5c8bd 100644 --- a/src/main/java/com/thealgorithms/maths/LeonardoNumber.java +++ b/src/main/java/com/thealgorithms/maths/LeonardoNumber.java @@ -1,8 +1,8 @@ package com.thealgorithms.maths; - /** - * https://en.wikipedia.org/wiki/Leonardo_number - */ +/** + * https://en.wikipedia.org/wiki/Leonardo_number + */ public class LeonardoNumber { /** diff --git a/src/main/java/com/thealgorithms/maths/LinearDiophantineEquationsSolver.java b/src/main/java/com/thealgorithms/maths/LinearDiophantineEquationsSolver.java index d6788ea1..54cda155 100644 --- a/src/main/java/com/thealgorithms/maths/LinearDiophantineEquationsSolver.java +++ b/src/main/java/com/thealgorithms/maths/LinearDiophantineEquationsSolver.java @@ -28,38 +28,26 @@ public final class LinearDiophantineEquationsSolver { } private static GcdSolutionWrapper gcd( - final int a, - final int b, - final GcdSolutionWrapper previous - ) { + final int a, final int b, final GcdSolutionWrapper previous) { if (b == 0) { return new GcdSolutionWrapper(a, new Solution(1, 0)); } // stub wrapper becomes the `previous` of the next recursive call final var stubWrapper = new GcdSolutionWrapper(0, new Solution(0, 0)); - final var next = /* recursive call */gcd(b, a % b, stubWrapper); + final var next = /* recursive call */ gcd(b, a % b, stubWrapper); previous.getSolution().setX(next.getSolution().getY()); - previous - .getSolution() - .setY( - next.getSolution().getX() - - (a / b) * - (next.getSolution().getY()) - ); + previous.getSolution().setY( + next.getSolution().getX() - (a / b) * (next.getSolution().getY())); previous.setGcd(next.getGcd()); return new GcdSolutionWrapper(next.getGcd(), previous.getSolution()); } public static final class Solution { - public static final Solution NO_SOLUTION = new Solution( - Integer.MAX_VALUE, - Integer.MAX_VALUE - ); - public static final Solution INFINITE_SOLUTIONS = new Solution( - Integer.MIN_VALUE, - Integer.MIN_VALUE - ); + public static final Solution NO_SOLUTION + = new Solution(Integer.MAX_VALUE, Integer.MAX_VALUE); + public static final Solution INFINITE_SOLUTIONS + = new Solution(Integer.MIN_VALUE, Integer.MIN_VALUE); private int x; private int y; @@ -103,11 +91,14 @@ public final class LinearDiophantineEquationsSolver { @Override public String toString() { - return "Solution[" + "x=" + x + ", " + "y=" + y + ']'; + return "Solution[" + + "x=" + x + ", " + + "y=" + y + ']'; } } - public record Equation(int a, int b, int c) {} + public record Equation(int a, int b, int c) { + } public static final class GcdSolutionWrapper { @@ -128,10 +119,7 @@ public final class LinearDiophantineEquationsSolver { return false; } var that = (GcdSolutionWrapper) obj; - return ( - this.gcd == that.gcd && - Objects.equals(this.solution, that.solution) - ); + return (this.gcd == that.gcd && Objects.equals(this.solution, that.solution)); } public int getGcd() { @@ -157,15 +145,9 @@ public final class LinearDiophantineEquationsSolver { @Override public String toString() { - return ( - "GcdSolutionWrapper[" + - "gcd=" + - gcd + - ", " + - "solution=" + - solution + - ']' - ); + return ("GcdSolutionWrapper[" + + "gcd=" + gcd + ", " + + "solution=" + solution + ']'); } } } diff --git a/src/main/java/com/thealgorithms/maths/LiouvilleLambdaFunction.java b/src/main/java/com/thealgorithms/maths/LiouvilleLambdaFunction.java index c8e753e4..89acbf6a 100644 --- a/src/main/java/com/thealgorithms/maths/LiouvilleLambdaFunction.java +++ b/src/main/java/com/thealgorithms/maths/LiouvilleLambdaFunction.java @@ -24,13 +24,11 @@ public class LiouvilleLambdaFunction { */ static int liouvilleLambda(int number) { if (number <= 0) { - //throw exception when number is less than or is zero - throw new IllegalArgumentException( - "Number must be greater than zero." - ); + // throw exception when number is less than or is zero + throw new IllegalArgumentException("Number must be greater than zero."); } - //return 1 if size of prime factor list is even, -1 otherwise + // return 1 if size of prime factor list is even, -1 otherwise return PrimeFactorization.pfactors(number).size() % 2 == 0 ? 1 : -1; } } diff --git a/src/main/java/com/thealgorithms/maths/LongDivision.java b/src/main/java/com/thealgorithms/maths/LongDivision.java index 2578fe2e..b1c7b190 100644 --- a/src/main/java/com/thealgorithms/maths/LongDivision.java +++ b/src/main/java/com/thealgorithms/maths/LongDivision.java @@ -1,17 +1,19 @@ -// Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator. +// Given two integers dividend and divisor, divide two integers without using multiplication, +// division, and mod operator. // -// The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8, -// and -2.7335 would be truncated to -2. -// My method used Long Division, here is the source "https://en.wikipedia.org/wiki/Long_division" +// The integer division should truncate toward zero, which means losing its fractional part. +// For example, 8.345 would be truncated to 8, and -2.7335 would be truncated to -2. My +// method used Long Division, here is the source +// "https://en.wikipedia.org/wiki/Long_division" package com.thealgorithms.maths; public class LongDivision { -public static int divide(int dividend, int divisor) { + public static int divide(int dividend, int divisor) { long new_dividend_1 = dividend; long new_divisor_1 = divisor; - if(divisor == 0){ + if (divisor == 0) { return 0; } if (dividend < 0) { @@ -32,7 +34,6 @@ public static int divide(int dividend, int divisor) { String remainder = ""; - for (int i = 0; i < dividend_string.length(); i++) { String part_v1 = remainder + "" + dividend_string.substring(last_index, i + 1); long part_1 = Long.parseLong(part_v1); @@ -57,7 +58,7 @@ public static int divide(int dividend, int divisor) { } if (!(part_1 == 0)) { remainder = String.valueOf(part_1); - }else{ + } else { remainder = ""; } @@ -76,6 +77,5 @@ public static int divide(int dividend, int divisor) { } catch (NumberFormatException e) { return 2147483647; } - } } diff --git a/src/main/java/com/thealgorithms/maths/LucasSeries.java b/src/main/java/com/thealgorithms/maths/LucasSeries.java index 59c9a9f3..ebeb2715 100644 --- a/src/main/java/com/thealgorithms/maths/LucasSeries.java +++ b/src/main/java/com/thealgorithms/maths/LucasSeries.java @@ -13,9 +13,7 @@ public class LucasSeries { * @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); + return n == 1 ? 2 : n == 2 ? 1 : lucasSeries(n - 1) + lucasSeries(n - 2); } /** diff --git a/src/main/java/com/thealgorithms/maths/MagicSquare.java b/src/main/java/com/thealgorithms/maths/MagicSquare.java index 1f968305..e48efabe 100644 --- a/src/main/java/com/thealgorithms/maths/MagicSquare.java +++ b/src/main/java/com/thealgorithms/maths/MagicSquare.java @@ -2,8 +2,9 @@ package com.thealgorithms.maths; import java.util.*; -/*A magic square of order n is an arrangement of distinct n^2 integers,in a square, such that the n numbers in all -rows, all columns, and both diagonals sum to the same constant. A magic square contains the integers from 1 to n^2.*/ +/*A magic square of order n is an arrangement of distinct n^2 integers,in a square, such that the n +numbers in all rows, all columns, and both diagonals sum to the same constant. A magic square +contains the integers from 1 to n^2.*/ public class MagicSquare { public static void main(String[] args) { @@ -22,10 +23,7 @@ public class MagicSquare { magic_square[row_num][col_num] = 1; for (int i = 2; i <= num * num; i++) { - if ( - magic_square[(row_num - 1 + num) % num][(col_num + 1) % num] == - 0 - ) { + if (magic_square[(row_num - 1 + num) % num][(col_num + 1) % num] == 0) { row_num = (row_num - 1 + num) % num; col_num = (col_num + 1) % num; } else { diff --git a/src/main/java/com/thealgorithms/maths/MatrixUtil.java b/src/main/java/com/thealgorithms/maths/MatrixUtil.java index 4f5e048a..6fc5252f 100644 --- a/src/main/java/com/thealgorithms/maths/MatrixUtil.java +++ b/src/main/java/com/thealgorithms/maths/MatrixUtil.java @@ -18,33 +18,18 @@ public class MatrixUtil { } public static boolean hasEqualSizes( - final BigDecimal[][] matrix1, - final BigDecimal[][] matrix2 - ) { - return ( - isValid(matrix1) && - isValid(matrix2) && - matrix1.length == matrix2.length && - matrix1[0].length == matrix2[0].length - ); + final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) { + return (isValid(matrix1) && isValid(matrix2) && matrix1.length == matrix2.length + && matrix1[0].length == matrix2[0].length); } - public static boolean canMultiply( - final BigDecimal[][] matrix1, - final BigDecimal[][] matrix2 - ) { - return ( - isValid(matrix1) && - isValid(matrix2) && - matrix1[0].length == matrix2.length - ); + public static boolean canMultiply(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) { + return (isValid(matrix1) && isValid(matrix2) && matrix1[0].length == matrix2.length); } - public static Optional operate( - final BigDecimal[][] matrix1, + public static Optional operate(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2, - final BiFunction operation - ) { + final BiFunction operation) { if (!hasEqualSizes(matrix1, matrix2)) { return Optional.empty(); } @@ -54,43 +39,29 @@ public class MatrixUtil { final BigDecimal[][] result = new BigDecimal[rowSize][columnSize]; - IntStream - .range(0, rowSize) - .forEach(rowIndex -> - IntStream - .range(0, columnSize) - .forEach(columnIndex -> { - final BigDecimal value1 = - matrix1[rowIndex][columnIndex]; - final BigDecimal value2 = - matrix2[rowIndex][columnIndex]; + IntStream.range(0, rowSize) + .forEach(rowIndex -> IntStream.range(0, columnSize).forEach(columnIndex -> { + final BigDecimal value1 = matrix1[rowIndex][columnIndex]; + final BigDecimal value2 = matrix2[rowIndex][columnIndex]; - result[rowIndex][columnIndex] = - operation.apply(value1, value2); - }) - ); + result[rowIndex][columnIndex] = operation.apply(value1, value2); + })); return Optional.of(result); } public static Optional add( - final BigDecimal[][] matrix1, - final BigDecimal[][] matrix2 - ) { + final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) { return operate(matrix1, matrix2, BigDecimal::add); } public static Optional subtract( - final BigDecimal[][] matrix1, - final BigDecimal[][] matrix2 - ) { + final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) { return operate(matrix1, matrix2, BigDecimal::subtract); } public static Optional multiply( - final BigDecimal[][] matrix1, - final BigDecimal[][] matrix2 - ) { + final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) { if (!canMultiply(matrix1, matrix2)) { return Optional.empty(); } @@ -102,65 +73,49 @@ public class MatrixUtil { final BigDecimal[][] result = new BigDecimal[matrix1RowSize][matrix2ColumnSize]; - IntStream - .range(0, matrix1RowSize) - .forEach(rowIndex -> - IntStream - .range(0, matrix2ColumnSize) - .forEach(columnIndex -> - result[rowIndex][columnIndex] = - IntStream - .range(0, size) - .mapToObj(index -> { - final BigDecimal value1 = - matrix1[rowIndex][index]; - final BigDecimal value2 = - matrix2[index][columnIndex]; + IntStream.range(0, matrix1RowSize) + .forEach(rowIndex + -> IntStream.range(0, matrix2ColumnSize) + .forEach(columnIndex + -> result[rowIndex][columnIndex] + = IntStream.range(0, size) + .mapToObj(index -> { + final BigDecimal value1 = matrix1[rowIndex][index]; + final BigDecimal value2 = matrix2[index][columnIndex]; - return value1.multiply(value2); - }) - .reduce(BigDecimal.ZERO, BigDecimal::add) - ) - ); + return value1.multiply(value2); + }) + .reduce(BigDecimal.ZERO, BigDecimal::add))); return Optional.of(result); } - public static void assertThat( - final BigDecimal[][] actual, - final BigDecimal[][] expected - ) { + public static void assertThat(final BigDecimal[][] actual, final BigDecimal[][] expected) { if (!Objects.deepEquals(actual, expected)) { - throw new AssertionError( - String.format( - "expected=%s but was actual=%s", - Arrays.deepToString(expected), - Arrays.deepToString(actual) - ) - ); + throw new AssertionError(String.format("expected=%s but was actual=%s", + Arrays.deepToString(expected), Arrays.deepToString(actual))); } } public static void main(final String[] args) { { final BigDecimal[][] matrix1 = { - { new BigDecimal(3), new BigDecimal(2) }, - { new BigDecimal(0), new BigDecimal(1) }, + {new BigDecimal(3), new BigDecimal(2)}, + {new BigDecimal(0), new BigDecimal(1)}, }; final BigDecimal[][] matrix2 = { - { new BigDecimal(1), new BigDecimal(3) }, - { new BigDecimal(2), new BigDecimal(0) }, + {new BigDecimal(1), new BigDecimal(3)}, + {new BigDecimal(2), new BigDecimal(0)}, }; - final BigDecimal[][] actual = add(matrix1, matrix2) - .orElseThrow(() -> - new AssertionError("Could not compute matrix!") - ); + final BigDecimal[][] actual + = add(matrix1, matrix2) + .orElseThrow(() -> new AssertionError("Could not compute matrix!")); final BigDecimal[][] expected = { - { new BigDecimal(4), new BigDecimal(5) }, - { new BigDecimal(2), new BigDecimal(1) }, + {new BigDecimal(4), new BigDecimal(5)}, + {new BigDecimal(2), new BigDecimal(1)}, }; assertThat(actual, expected); @@ -168,23 +123,22 @@ public class MatrixUtil { { final BigDecimal[][] matrix1 = { - { new BigDecimal(1), new BigDecimal(4) }, - { new BigDecimal(5), new BigDecimal(6) }, + {new BigDecimal(1), new BigDecimal(4)}, + {new BigDecimal(5), new BigDecimal(6)}, }; final BigDecimal[][] matrix2 = { - { new BigDecimal(2), new BigDecimal(0) }, - { new BigDecimal(-2), new BigDecimal(-3) }, + {new BigDecimal(2), new BigDecimal(0)}, + {new BigDecimal(-2), new BigDecimal(-3)}, }; - final BigDecimal[][] actual = subtract(matrix1, matrix2) - .orElseThrow(() -> - new AssertionError("Could not compute matrix!") - ); + final BigDecimal[][] actual + = subtract(matrix1, matrix2) + .orElseThrow(() -> new AssertionError("Could not compute matrix!")); final BigDecimal[][] expected = { - { new BigDecimal(-1), new BigDecimal(4) }, - { new BigDecimal(7), new BigDecimal(9) }, + {new BigDecimal(-1), new BigDecimal(4)}, + {new BigDecimal(7), new BigDecimal(9)}, }; assertThat(actual, expected); @@ -192,26 +146,25 @@ public class MatrixUtil { { final BigDecimal[][] matrix1 = { - { new BigDecimal(1), new BigDecimal(2), new BigDecimal(3) }, - { new BigDecimal(4), new BigDecimal(5), new BigDecimal(6) }, - { new BigDecimal(7), new BigDecimal(8), new BigDecimal(9) }, + {new BigDecimal(1), new BigDecimal(2), new BigDecimal(3)}, + {new BigDecimal(4), new BigDecimal(5), new BigDecimal(6)}, + {new BigDecimal(7), new BigDecimal(8), new BigDecimal(9)}, }; final BigDecimal[][] matrix2 = { - { new BigDecimal(1), new BigDecimal(2) }, - { new BigDecimal(3), new BigDecimal(4) }, - { new BigDecimal(5), new BigDecimal(6) }, + {new BigDecimal(1), new BigDecimal(2)}, + {new BigDecimal(3), new BigDecimal(4)}, + {new BigDecimal(5), new BigDecimal(6)}, }; - final BigDecimal[][] actual = multiply(matrix1, matrix2) - .orElseThrow(() -> - new AssertionError("Could not compute matrix!") - ); + final BigDecimal[][] actual + = multiply(matrix1, matrix2) + .orElseThrow(() -> new AssertionError("Could not compute matrix!")); final BigDecimal[][] expected = { - { new BigDecimal(22), new BigDecimal(28) }, - { new BigDecimal(49), new BigDecimal(64) }, - { new BigDecimal(76), new BigDecimal(100) }, + {new BigDecimal(22), new BigDecimal(28)}, + {new BigDecimal(49), new BigDecimal(64)}, + {new BigDecimal(76), new BigDecimal(100)}, }; assertThat(actual, expected); diff --git a/src/main/java/com/thealgorithms/maths/Median.java b/src/main/java/com/thealgorithms/maths/Median.java index 44f94ad6..994b9b0c 100644 --- a/src/main/java/com/thealgorithms/maths/Median.java +++ b/src/main/java/com/thealgorithms/maths/Median.java @@ -15,8 +15,7 @@ public class Median { 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]; + return length % 2 == 0 ? (values[length / 2] + values[length / 2 - 1]) / 2.0 + : values[length / 2]; } } diff --git a/src/main/java/com/thealgorithms/maths/MobiusFunction.java b/src/main/java/com/thealgorithms/maths/MobiusFunction.java index 5ed83c7c..e9ead992 100644 --- a/src/main/java/com/thealgorithms/maths/MobiusFunction.java +++ b/src/main/java/com/thealgorithms/maths/MobiusFunction.java @@ -25,29 +25,27 @@ public class MobiusFunction { */ static int mobius(int number) { if (number <= 0) { - //throw exception when number is less than or is zero - throw new IllegalArgumentException( - "Number must be greater than zero." - ); + // throw exception when number is less than or is zero + throw new IllegalArgumentException("Number must be greater than zero."); } if (number == 1) { - //return 1 if number passed is less or is 1 + // return 1 if number passed is less or is 1 return 1; } int primeFactorCount = 0; for (int i = 1; i <= number; i++) { - //find prime factors of number + // find prime factors of number if (number % i == 0 && PrimeCheck.isPrime(i)) { - //check if number is divisible by square of prime factor + // check if number is divisible by square of prime factor if (number % (i * i) == 0) { - //if number is divisible by square of prime factor + // if number is divisible by square of prime factor return 0; } - /*increment primeFactorCount by 1 - if number is not divisible by square of found prime factor*/ + /*increment primeFactorCount by 1 + if number is not divisible by square of found prime factor*/ primeFactorCount++; } } diff --git a/src/main/java/com/thealgorithms/maths/Mode.java b/src/main/java/com/thealgorithms/maths/Mode.java index f90f7062..7333380b 100644 --- a/src/main/java/com/thealgorithms/maths/Mode.java +++ b/src/main/java/com/thealgorithms/maths/Mode.java @@ -16,19 +16,10 @@ 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 } - ); + 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}); } /* diff --git a/src/main/java/com/thealgorithms/maths/NonRepeatingElement.java b/src/main/java/com/thealgorithms/maths/NonRepeatingElement.java index e224c80f..e2847bcc 100644 --- a/src/main/java/com/thealgorithms/maths/NonRepeatingElement.java +++ b/src/main/java/com/thealgorithms/maths/NonRepeatingElement.java @@ -4,8 +4,8 @@ import java.util.Scanner; /* * Find the 2 elements which are non repeating in an array - * Reason to use bitwise operator: It makes our program faster as we are operating on bits and not on - * actual numbers. + * Reason to use bitwise operator: It makes our program faster as we are operating on bits and not + * on actual numbers. */ public class NonRepeatingElement { @@ -15,17 +15,14 @@ public class NonRepeatingElement { System.out.println("Enter the number of elements in the array"); int n = sc.nextInt(); if ((n & 1) == 1) { - //Not allowing odd number of elements as we are expecting 2 non repeating numbers + // Not allowing odd number of elements as we are expecting 2 non repeating numbers System.out.println("Array should contain even number of elements"); return; } int[] arr = new int[n]; System.out.println( - "Enter " + - n + - " elements in the array. NOTE: Only 2 elements should not repeat" - ); + "Enter " + n + " elements in the array. NOTE: Only 2 elements should not repeat"); for (i = 0; i < n; i++) { arr[i] = sc.nextInt(); } @@ -36,40 +33,38 @@ public class NonRepeatingElement { System.out.println("Unable to close scanner" + e); } - //Find XOR of the 2 non repeating elements + // Find XOR of the 2 non repeating elements for (i = 0; i < n; i++) { res ^= arr[i]; } - //Finding the rightmost set bit + // Finding the rightmost set bit res = res & (-res); int num1 = 0, num2 = 0; for (i = 0; i < n; i++) { - if ((res & arr[i]) > 0) { //Case 1 explained below + if ((res & arr[i]) > 0) { // Case 1 explained below num1 ^= arr[i]; } else { - num2 ^= arr[i]; //Case 2 explained below + num2 ^= arr[i]; // Case 2 explained below } } - System.out.println( - "The two non repeating elements are " + num1 + " and " + num2 - ); + System.out.println("The two non repeating elements are " + num1 + " and " + num2); } - /* + /* Explanation of the code: let us assume we have an array [1,2,1,2,3,4] - Property of XOR: num ^ num = 0. - If we XOR all the elemnets of the array we will be left with 3 ^ 4 as 1 ^ 1 and 2 ^ 2 would give 0. - Our task is to find num1 and num2 from the result of 3 ^ 4 = 7. - We need to find two's complement of 7 and find the rightmost set bit. i.e. (num & (-num)) - Two's complement of 7 is 001 and hence res = 1. - There can be 2 options when we Bitise AND this res with all the elements in our array + Property of XOR: num ^ num = 0. + If we XOR all the elemnets of the array we will be left with 3 ^ 4 as 1 ^ 1 and 2 ^ 2 would give + 0. Our task is to find num1 and num2 from the result of 3 ^ 4 = 7. We need to find two's + complement of 7 and find the rightmost set bit. i.e. (num & (-num)) Two's complement of 7 is 001 + and hence res = 1. There can be 2 options when we Bitise AND this res with all the elements in our + array 1. Result will come non zero number 2. Result will be 0. In the first case we will XOR our element with the first number (which is initially 0) In the second case we will XOR our element with the second number(which is initially 0) - This is how we will get non repeating elements with the help of bitwise operators. + This is how we will get non repeating elements with the help of bitwise operators. */ } diff --git a/src/main/java/com/thealgorithms/maths/NthUglyNumber.java b/src/main/java/com/thealgorithms/maths/NthUglyNumber.java index 6daeb267..d19b80ab 100644 --- a/src/main/java/com/thealgorithms/maths/NthUglyNumber.java +++ b/src/main/java/com/thealgorithms/maths/NthUglyNumber.java @@ -1,10 +1,9 @@ package com.thealgorithms.maths; -import java.util.HashMap; +import java.lang.IllegalArgumentException; import java.util.ArrayList; import java.util.Arrays; -import java.lang.IllegalArgumentException; - +import java.util.HashMap; /** * @brief class computing the n-th ugly number (when they are sorted) diff --git a/src/main/java/com/thealgorithms/maths/NumberOfDigits.java b/src/main/java/com/thealgorithms/maths/NumberOfDigits.java index 7c5c540b..665d8ef5 100644 --- a/src/main/java/com/thealgorithms/maths/NumberOfDigits.java +++ b/src/main/java/com/thealgorithms/maths/NumberOfDigits.java @@ -47,9 +47,7 @@ public class NumberOfDigits { * @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); + return number == 0 ? 1 : (int) Math.floor(Math.log10(Math.abs(number)) + 1); } /** diff --git a/src/main/java/com/thealgorithms/maths/ParseInteger.java b/src/main/java/com/thealgorithms/maths/ParseInteger.java index e2e9e52a..d0cf89b9 100644 --- a/src/main/java/com/thealgorithms/maths/ParseInteger.java +++ b/src/main/java/com/thealgorithms/maths/ParseInteger.java @@ -24,11 +24,7 @@ public class ParseInteger { 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 - ) { + 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); } diff --git a/src/main/java/com/thealgorithms/maths/PascalTriangle.java b/src/main/java/com/thealgorithms/maths/PascalTriangle.java index fb7468f2..beb9a1e4 100644 --- a/src/main/java/com/thealgorithms/maths/PascalTriangle.java +++ b/src/main/java/com/thealgorithms/maths/PascalTriangle.java @@ -3,18 +3,19 @@ package com.thealgorithms.maths; public class PascalTriangle { /** - *In mathematics, Pascal's triangle is a triangular array of the binomial coefficients that arises - * in probability theory, combinatorics, and algebra. In much of the Western world, it is named after - * the French mathematician Blaise Pascal, although other mathematicians studied it centuries before - * him in India, Persia, China, Germany, and Italy. + *In mathematics, Pascal's triangle is a triangular array of the binomial coefficients that + *arises in probability theory, combinatorics, and algebra. In much of the Western world, it is + *named after the French mathematician Blaise Pascal, although other mathematicians studied it + *centuries before him in India, Persia, China, Germany, and Italy. * - * The rows of Pascal's triangle are conventionally enumerated starting with row n=0 at the top (the 0th row). - * The entries in each row are numbered from the left beginning with k=0 and are usually staggered relative - * to the numbers in the adjacent rows. The triangle may be constructed in the following manner: - * In row 0 (the topmost row), there is a unique nonzero entry 1. Each entry of each subsequent row is - * constructed by adding the number above and to the left with the number above and to the right, treating - * blank entries as 0. For example, the initial number in the first (or any other) row is 1 (the sum of 0 and 1), - * whereas the numbers 1 and 3 in the third row are added to produce the number 4 in the fourth row. * + * The rows of Pascal's triangle are conventionally enumerated starting with row n=0 at the top + *(the 0th row). The entries in each row are numbered from the left beginning with k=0 and are + *usually staggered relative to the numbers in the adjacent rows. The triangle may be + *constructed in the following manner: In row 0 (the topmost row), there is a unique nonzero + *entry 1. Each entry of each subsequent row is constructed by adding the number above and to + *the left with the number above and to the right, treating blank entries as 0. For example, the + *initial number in the first (or any other) row is 1 (the sum of 0 and 1), whereas the numbers + *1 and 3 in the third row are added to produce the number 4 in the fourth row. * * *

* link:-https://en.wikipedia.org/wiki/Pascal%27s_triangle @@ -51,7 +52,8 @@ public class PascalTriangle { // First and last values in every row are 1 if (line == i || i == 0) arr[line][i] = 1; // The rest elements are sum of values just above and left of above - else arr[line][i] = arr[line - 1][i - 1] + arr[line - 1][i]; + else + arr[line][i] = arr[line - 1][i - 1] + arr[line - 1][i]; } } diff --git a/src/main/java/com/thealgorithms/maths/PerfectCube.java b/src/main/java/com/thealgorithms/maths/PerfectCube.java index 0fae7889..f9ed0558 100644 --- a/src/main/java/com/thealgorithms/maths/PerfectCube.java +++ b/src/main/java/com/thealgorithms/maths/PerfectCube.java @@ -17,7 +17,7 @@ public class PerfectCube { int a = (int) Math.pow(number, 1.0 / 3); return a * a * a == number; } - + /** * Check if a number is perfect cube or not by using Math.cbrt function * diff --git a/src/main/java/com/thealgorithms/maths/PerfectNumber.java b/src/main/java/com/thealgorithms/maths/PerfectNumber.java index 896b8cef..7d6a0451 100644 --- a/src/main/java/com/thealgorithms/maths/PerfectNumber.java +++ b/src/main/java/com/thealgorithms/maths/PerfectNumber.java @@ -17,8 +17,7 @@ public class PerfectNumber { * @return {@code true} if {@code number} is perfect number, otherwise false */ public static boolean isPerfectNumber(int number) { - if (number <= 0) - return false; + if (number <= 0) return false; int sum = 0; /* sum of its positive divisors */ for (int i = 1; i < number; ++i) { @@ -28,7 +27,7 @@ public class PerfectNumber { } return sum == number; } - + /** * Check if {@code n} is perfect number or not * @@ -36,11 +35,10 @@ public class PerfectNumber { * @return {@code true} if {@code number} is perfect number, otherwise false */ public static boolean isPerfectNumber2(int n) { - if (n <= 0) - return false; + if (n <= 0) return false; int sum = 1; double root = Math.sqrt(n); - + /* * We can get the factors after the root by dividing number by its factors * before the root. @@ -55,10 +53,10 @@ public class PerfectNumber { sum += i + n / i; } } - - // if n is a perfect square then its root was added twice in above loop, so subtracting root from sum - if (root == (int) root) - sum -= root; + + // if n is a perfect square then its root was added twice in above loop, so subtracting root + // from sum + if (root == (int) root) sum -= root; return sum == n; } diff --git a/src/main/java/com/thealgorithms/maths/Perimeter.java b/src/main/java/com/thealgorithms/maths/Perimeter.java index a941de19..15d032b0 100644 --- a/src/main/java/com/thealgorithms/maths/Perimeter.java +++ b/src/main/java/com/thealgorithms/maths/Perimeter.java @@ -5,8 +5,9 @@ public class Perimeter { /** * Calculate the Perimeter of regular polygon (equals sides) - * Examples of regular polygon are Equilateral Triangle, Square, Regular Pentagon, Regular Hexagon. - * + * Examples of regular polygon are Equilateral Triangle, Square, Regular Pentagon, Regular + * Hexagon. + * * @param n for number of sides. * @param side for length of each side. * @return Perimeter of given polygon @@ -17,15 +18,17 @@ public class Perimeter { /** * Calculate the Perimeter of irregular polygon (unequals sides) - * Examples of irregular polygon are scalent triangle, irregular quadrilateral, irregular Pentagon, irregular Hexagon. - * + * Examples of irregular polygon are scalent triangle, irregular quadrilateral, irregular + * Pentagon, irregular Hexagon. + * * @param side1 for length of side 1 * @param side2 for length of side 2 * @param side3 for length of side 3 * @param sides for length of remaining sides * @return Perimeter of given trapezoid. */ - public static float perimeterIrregularPolygon(float side1, float side2, float side3, float... sides) { + public static float perimeterIrregularPolygon( + float side1, float side2, float side3, float... sides) { float perimeter = side1 + side2 + side3; for (float side : sides) { perimeter += side; @@ -35,7 +38,7 @@ public class Perimeter { /** * Calculate the Perimeter of rectangle - * + * * @param length for length of rectangle * @param breadth for breadth of rectangle * @return Perimeter of given rectangle @@ -46,7 +49,7 @@ public class Perimeter { /** * Calculate the Perimeter or Circumference of circle. - * + * * @param r for radius of circle. * @return circumference of given circle. */ diff --git a/src/main/java/com/thealgorithms/maths/PiNilakantha.java b/src/main/java/com/thealgorithms/maths/PiNilakantha.java index c60b3b5b..d0024031 100644 --- a/src/main/java/com/thealgorithms/maths/PiNilakantha.java +++ b/src/main/java/com/thealgorithms/maths/PiNilakantha.java @@ -22,9 +22,7 @@ public class PiNilakantha { */ public static double calculatePi(int iterations) { if (iterations < 0 || iterations > 500) { - throw new IllegalArgumentException( - "Please input Integer Number between 0 and 500" - ); + throw new IllegalArgumentException("Please input Integer Number between 0 and 500"); } double pi = 3; @@ -32,15 +30,9 @@ public class PiNilakantha { for (int i = 0; i < iterations; i++) { if (i % 2 == 0) { - pi = - pi + - 4.0 / - (divCounter * (divCounter + 1) * (divCounter + 2)); + pi = pi + 4.0 / (divCounter * (divCounter + 1) * (divCounter + 2)); } else { - pi = - pi - - 4.0 / - (divCounter * (divCounter + 1) * (divCounter + 2)); + pi = pi - 4.0 / (divCounter * (divCounter + 1) * (divCounter + 2)); } divCounter += 2; diff --git a/src/main/java/com/thealgorithms/maths/PollardRho.java b/src/main/java/com/thealgorithms/maths/PollardRho.java index 59852c5a..8ce62336 100644 --- a/src/main/java/com/thealgorithms/maths/PollardRho.java +++ b/src/main/java/com/thealgorithms/maths/PollardRho.java @@ -3,12 +3,12 @@ package com.thealgorithms.maths; /* * Java program for pollard rho algorithm * The algorithm is used to factorize a number n = pq, - * where p is a non-trivial factor. + * where p is a non-trivial factor. * Pollard's rho algorithm is an algorithm for integer factorization - * and it takes as its inputs n, the integer to be factored; + * and it takes as its inputs n, the integer to be factored; * and g(x), a polynomial in x computed modulo n. * In the original algorithm, g(x) = ((x ^ 2) − 1) mod n, - * but nowadays it is more common to use g(x) = ((x ^ 2) + 1 ) mod n. + * but nowadays it is more common to use g(x) = ((x ^ 2) + 1 ) mod n. * The output is either a non-trivial factor of n, or failure. * It performs the following steps: * x ← 2 @@ -20,19 +20,20 @@ package com.thealgorithms.maths; * y ← g(g(y)) * d ← gcd(|x - y|, n) - * if d = n: + * if d = n: * return failure * else: * return d - * Here x and y corresponds to xi and xj in the previous section. + * Here x and y corresponds to xi and xj in the previous section. * Note that this algorithm may fail to find a nontrivial factor even when n is composite. - * In that case, the method can be tried again, using a starting value other than 2 or a different g(x) - * + * In that case, the method can be tried again, using a starting value other than 2 or a different + g(x) + * * Wikipedia: https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm - * + * * Author: Akshay Dubey (https://github.com/itsAkshayDubey) - * + * * */ public class PollardRho { @@ -40,7 +41,8 @@ public class PollardRho { * This method returns a polynomial in x computed modulo n * * @param base Integer base of the polynomial - * @param modulus Integer is value which is to be used to perform modulo operation over the polynomial + * @param modulus Integer is value which is to be used to perform modulo operation over the + * polynomial * @return Integer (((base * base) - 1) % modulus) */ static int g(int base, int modulus) { @@ -57,13 +59,13 @@ public class PollardRho { static int pollardRho(int number) { int x = 2, y = 2, d = 1; while (d == 1) { - //tortoise move + // tortoise move x = g(x, number); - //hare move + // hare move y = g(g(y, number), number); - //check GCD of |x-y| and number + // check GCD of |x-y| and number d = GCD.gcd(Math.abs(x - y), number); } if (d == number) { diff --git a/src/main/java/com/thealgorithms/maths/PrimeCheck.java b/src/main/java/com/thealgorithms/maths/PrimeCheck.java index 5eb757ac..2c9714f1 100644 --- a/src/main/java/com/thealgorithms/maths/PrimeCheck.java +++ b/src/main/java/com/thealgorithms/maths/PrimeCheck.java @@ -12,17 +12,13 @@ public class PrimeCheck { if (isPrime(n)) { System.out.println("algo1 verify that " + n + " is a prime number"); } else { - System.out.println( - "algo1 verify that " + n + " is not a prime number" - ); + System.out.println("algo1 verify that " + n + " is not a prime number"); } if (fermatPrimeChecking(n, 20)) { System.out.println("algo2 verify that " + n + " is a prime number"); } else { - System.out.println( - "algo2 verify that " + n + " is not a prime number" - ); + System.out.println("algo2 verify that " + n + " is not a prime number"); } scanner.close(); } diff --git a/src/main/java/com/thealgorithms/maths/PronicNumber.java b/src/main/java/com/thealgorithms/maths/PronicNumber.java index 15fae23a..312af21e 100644 --- a/src/main/java/com/thealgorithms/maths/PronicNumber.java +++ b/src/main/java/com/thealgorithms/maths/PronicNumber.java @@ -19,16 +19,17 @@ public class PronicNumber { * @return true if input number is a pronic number, false otherwise */ static boolean isPronic(int input_number) { - //Iterating from 0 to input_number + // Iterating from 0 to input_number for (int i = 0; i <= input_number; i++) { - //Checking if product of i and (i+1) is equals input_number + // Checking if product of i and (i+1) is equals input_number if (i * (i + 1) == input_number && i != input_number) { - //return true if product of i and (i+1) is equals input_number + // return true if product of i and (i+1) is equals input_number return true; } } - //return false if product of i and (i+1) for all values from 0 to input_number is not equals input_number + // return false if product of i and (i+1) for all values from 0 to input_number is not + // equals input_number return false; } } diff --git a/src/main/java/com/thealgorithms/maths/RomanNumeralUtil.java b/src/main/java/com/thealgorithms/maths/RomanNumeralUtil.java index ead630a7..f14415c3 100644 --- a/src/main/java/com/thealgorithms/maths/RomanNumeralUtil.java +++ b/src/main/java/com/thealgorithms/maths/RomanNumeralUtil.java @@ -12,7 +12,7 @@ public class RomanNumeralUtil { private static final int MIN_VALUE = 1; private static final int MAX_VALUE = 5999; - //1000-5999 + // 1000-5999 private static final String[] RN_M = { "", "M", @@ -21,7 +21,7 @@ public class RomanNumeralUtil { "MMMM", "MMMMM", }; - //100-900 + // 100-900 private static final String[] RN_C = { "", "C", @@ -34,7 +34,7 @@ public class RomanNumeralUtil { "DCCC", "CM", }; - //10-90 + // 10-90 private static final String[] RN_X = { "", "X", @@ -47,7 +47,7 @@ public class RomanNumeralUtil { "LXXX", "XC", }; - //1-9 + // 1-9 private static final String[] RN_I = { "", "I", @@ -64,19 +64,10 @@ public class RomanNumeralUtil { public static String generate(int number) { if (number < MIN_VALUE || number > MAX_VALUE) { throw new IllegalArgumentException( - String.format( - "The number must be in the range [%d, %d]", - MIN_VALUE, - MAX_VALUE - ) - ); + String.format("The number must be in the range [%d, %d]", MIN_VALUE, MAX_VALUE)); } - return ( - RN_M[number / 1000] + - RN_C[number % 1000 / 100] + - RN_X[number % 100 / 10] + - RN_I[number % 10] - ); + return (RN_M[number / 1000] + RN_C[number % 1000 / 100] + RN_X[number % 100 / 10] + + RN_I[number % 10]); } } diff --git a/src/main/java/com/thealgorithms/maths/SimpsonIntegration.java b/src/main/java/com/thealgorithms/maths/SimpsonIntegration.java index d9efb5e9..ef02c575 100644 --- a/src/main/java/com/thealgorithms/maths/SimpsonIntegration.java +++ b/src/main/java/com/thealgorithms/maths/SimpsonIntegration.java @@ -7,9 +7,9 @@ public class SimpsonIntegration { /* * Calculate definite integrals by using Composite Simpson's rule. * Wiki: https://en.wikipedia.org/wiki/Simpson%27s_rule#Composite_Simpson's_rule - * Given f a function and an even number N of intervals that divide the integration interval e.g. [a, b], - * we calculate the step h = (b-a)/N and create a table that contains all the x points of - * the real axis xi = x0 + i*h and the value f(xi) that corresponds to these xi. + * Given f a function and an even number N of intervals that divide the integration interval + * e.g. [a, b], we calculate the step h = (b-a)/N and create a table that contains all the x + * points of the real axis xi = x0 + i*h and the value f(xi) that corresponds to these xi. * * To evaluate the integral i use the formula below: * I = h/3 * {f(x0) + 4*f(x1) + 2*f(x2) + 4*f(x3) + ... + 2*f(xN-2) + 4*f(xN-1) + f(xN)} @@ -25,9 +25,7 @@ public class SimpsonIntegration { // Check so that N is even if (N % 2 != 0) { - System.out.println( - "N must be even number for Simpsons method. Aborted" - ); + System.out.println("N must be even number for Simpsons method. Aborted"); System.exit(1); } diff --git a/src/main/java/com/thealgorithms/maths/SquareFreeInteger.java b/src/main/java/com/thealgorithms/maths/SquareFreeInteger.java index b5f57a0d..c988bb70 100644 --- a/src/main/java/com/thealgorithms/maths/SquareFreeInteger.java +++ b/src/main/java/com/thealgorithms/maths/SquareFreeInteger.java @@ -1,7 +1,7 @@ package com.thealgorithms.maths; /* * Java program for Square free integer - * This class has a function which checks + * This class has a function which checks * if an integer has repeated prime factors * and will return false if the number has repeated prime factors. * true otherwise @@ -23,20 +23,21 @@ public class SquareFreeInteger { * true when number has non repeated prime factors * @throws IllegalArgumentException when number is negative or zero */ - public static boolean isSquareFreeInteger(int number) { - - if(number <= 0) { - //throw exception when number is less than or is zero - throw new IllegalArgumentException("Number must be greater than zero."); - } - - //Store prime factors of number which is passed as argument - //in a list - List primeFactorsList = PrimeFactorization.pfactors(number); - - //Create set from list of prime factors of integer number - //if size of list and set is equal then the argument passed to this method is square free - //if size of list and set is not equal then the argument passed to this method is not square free - return primeFactorsList.size() == new HashSet<>(primeFactorsList).size(); - } + public static boolean isSquareFreeInteger(int number) { + + if (number <= 0) { + // throw exception when number is less than or is zero + throw new IllegalArgumentException("Number must be greater than zero."); + } + + // Store prime factors of number which is passed as argument + // in a list + List primeFactorsList = PrimeFactorization.pfactors(number); + + // Create set from list of prime factors of integer number + // if size of list and set is equal then the argument passed to this method is square free + // if size of list and set is not equal then the argument passed to this method is not + // square free + return primeFactorsList.size() == new HashSet<>(primeFactorsList).size(); + } } diff --git a/src/main/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonMethod.java b/src/main/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonMethod.java index 1cfe8b63..98a9ac0c 100644 --- a/src/main/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonMethod.java +++ b/src/main/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonMethod.java @@ -19,11 +19,13 @@ import java.util.Scanner; public class SquareRootWithNewtonRaphsonMethod { public static double squareRoot(int n) { - double x = n; //initially taking a guess that x = n. - double root = 0.5 * (x + n / x); //applying Newton-Raphson Method. + double x = n; // initially taking a guess that x = n. + double root = 0.5 * (x + n / x); // applying Newton-Raphson Method. - while (Math.abs(root - x) > 0.0000001) { //root - x = error and error < 0.0000001, 0.0000001 is the precision value taken over here. - x = root; //decreasing the value of x to root, i.e. decreasing the guess. + while ( + Math.abs(root - x) > 0.0000001) { // root - x = error and error < 0.0000001, 0.0000001 + // is the precision value taken over here. + x = root; // decreasing the value of x to root, i.e. decreasing the guess. root = 0.5 * (x + n / x); } diff --git a/src/main/java/com/thealgorithms/maths/SumOfArithmeticSeries.java b/src/main/java/com/thealgorithms/maths/SumOfArithmeticSeries.java index 688756d0..69be4c3d 100644 --- a/src/main/java/com/thealgorithms/maths/SumOfArithmeticSeries.java +++ b/src/main/java/com/thealgorithms/maths/SumOfArithmeticSeries.java @@ -36,13 +36,7 @@ public class SumOfArithmeticSeries { * @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) - ); + private static double sumOfSeries(double firstTerm, double commonDiff, int numOfTerms) { + return (numOfTerms / 2.0 * (2 * firstTerm + (numOfTerms - 1) * commonDiff)); } } diff --git a/src/main/java/com/thealgorithms/maths/SumOfDigits.java b/src/main/java/com/thealgorithms/maths/SumOfDigits.java index 22d059d9..6ffc20ac 100644 --- a/src/main/java/com/thealgorithms/maths/SumOfDigits.java +++ b/src/main/java/com/thealgorithms/maths/SumOfDigits.java @@ -3,17 +3,13 @@ package com.thealgorithms.maths; public class SumOfDigits { public static void main(String[] args) { - assert sumOfDigits(-123) == 6 && - sumOfDigitsRecursion(-123) == 6 && - sumOfDigitsFast(-123) == 6; + 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; } /** @@ -42,9 +38,7 @@ public class SumOfDigits { public static int sumOfDigitsRecursion(int number) { number = number < 0 ? -number : number; /* calculate abs value */ - return number < 10 - ? number - : number % 10 + sumOfDigitsRecursion(number / 10); + return number < 10 ? number : number % 10 + sumOfDigitsRecursion(number / 10); } /** diff --git a/src/main/java/com/thealgorithms/maths/SumWithoutArithmeticOperators.java b/src/main/java/com/thealgorithms/maths/SumWithoutArithmeticOperators.java index f45ac4d3..8bc1afbe 100644 --- a/src/main/java/com/thealgorithms/maths/SumWithoutArithmeticOperators.java +++ b/src/main/java/com/thealgorithms/maths/SumWithoutArithmeticOperators.java @@ -3,18 +3,18 @@ package com.thealgorithms.maths; public class SumWithoutArithmeticOperators { /** - * Calculate the sum of two numbers a and b without using any arithmetic operators (+, -, *, /). - * All the integers associated are unsigned 32-bit integers - *https://stackoverflow.com/questions/365522/what-is-the-best-way-to-add-two-numbers-without-using-the-operator - *@param a - It is the first number - *@param b - It is the second number - *@return returns an integer which is the sum of the first and second number - */ + * Calculate the sum of two numbers a and b without using any arithmetic operators (+, -, *, /). + * All the integers associated are unsigned 32-bit integers + *https://stackoverflow.com/questions/365522/what-is-the-best-way-to-add-two-numbers-without-using-the-operator + *@param a - It is the first number + *@param b - It is the second number + *@return returns an integer which is the sum of the first and second number + */ - public int getSum(int a, int b){ - if(b==0) return a; - int sum = a^b; - int carry = (a&b)<<1; + public int getSum(int a, int b) { + if (b == 0) return a; + int sum = a ^ b; + int carry = (a & b) << 1; return getSum(sum, carry); } } diff --git a/src/main/java/com/thealgorithms/maths/TrinomialTriangle.java b/src/main/java/com/thealgorithms/maths/TrinomialTriangle.java index 1c19bea9..5bae51d5 100644 --- a/src/main/java/com/thealgorithms/maths/TrinomialTriangle.java +++ b/src/main/java/com/thealgorithms/maths/TrinomialTriangle.java @@ -19,10 +19,7 @@ public class TrinomialTriangle { } return ( - TrinomialValue(n - 1, k - 1) + - TrinomialValue(n - 1, k) + - TrinomialValue(n - 1, k + 1) - ); + TrinomialValue(n - 1, k - 1) + TrinomialValue(n - 1, k) + TrinomialValue(n - 1, k + 1)); } public static void printTrinomial(int n) { diff --git a/src/main/java/com/thealgorithms/maths/TwinPrime.java b/src/main/java/com/thealgorithms/maths/TwinPrime.java index ba4310ac..867a1d23 100644 --- a/src/main/java/com/thealgorithms/maths/TwinPrime.java +++ b/src/main/java/com/thealgorithms/maths/TwinPrime.java @@ -1,32 +1,31 @@ package com.thealgorithms.maths; /* * Java program to find 'twin prime' of a prime number - * Twin Prime: Twin prime of a number n is (n+2) + * Twin Prime: Twin prime of a number n is (n+2) * if and only if n & (n+2) are prime. * Wikipedia: https://en.wikipedia.org/wiki/Twin_prime - * + * * Author: Akshay Dubey (https://github.com/itsAkshayDubey) - * + * * */ public class TwinPrime { - - /** + + /** * This method returns twin prime of the integer value passed as argument * * @param input_number Integer value of which twin prime is to be found * @return (number + 2) if number and (number + 2) are prime, -1 otherwise */ - static int getTwinPrime(int inputNumber) { - - //if inputNumber and (inputNumber + 2) are both prime - //then return (inputNumber + 2) as a result - if(PrimeCheck.isPrime(inputNumber) && PrimeCheck.isPrime(inputNumber + 2) ) { - return inputNumber + 2; - } - //if any one from inputNumber and (inputNumber + 2) or if both of them are not prime - //then return -1 as a result - return -1; - } + static int getTwinPrime(int inputNumber) { + // if inputNumber and (inputNumber + 2) are both prime + // then return (inputNumber + 2) as a result + if (PrimeCheck.isPrime(inputNumber) && PrimeCheck.isPrime(inputNumber + 2)) { + return inputNumber + 2; + } + // if any one from inputNumber and (inputNumber + 2) or if both of them are not prime + // then return -1 as a result + return -1; + } } diff --git a/src/main/java/com/thealgorithms/maths/VampireNumber.java b/src/main/java/com/thealgorithms/maths/VampireNumber.java index fab745aa..d9aa4f20 100644 --- a/src/main/java/com/thealgorithms/maths/VampireNumber.java +++ b/src/main/java/com/thealgorithms/maths/VampireNumber.java @@ -31,33 +31,17 @@ public class VampireNumber { // System.out.println(i+ " "+ j); if (isVampireNumber(i, j, true)) { countofRes++; - res.append( - "" + - countofRes + - ": = ( " + - i + - "," + - j + - " = " + - i * - j + - ")" + - "\n" - ); + 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 + 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; diff --git a/src/main/java/com/thealgorithms/maths/VectorCrossProduct.java b/src/main/java/com/thealgorithms/maths/VectorCrossProduct.java index f9e903b9..8a1bb148 100644 --- a/src/main/java/com/thealgorithms/maths/VectorCrossProduct.java +++ b/src/main/java/com/thealgorithms/maths/VectorCrossProduct.java @@ -45,7 +45,7 @@ public class VectorCrossProduct { int y; int z; - //Default constructor, initialises all three Direction Ratios to 0 + // Default constructor, initialises all three Direction Ratios to 0 VectorCrossProduct() { x = 0; y = 0; @@ -110,15 +110,15 @@ public class VectorCrossProduct { } static void test() { - //Create two vectors + // Create two vectors VectorCrossProduct A = new VectorCrossProduct(1, -2, 3); VectorCrossProduct B = new VectorCrossProduct(2, 0, 3); - //Determine cross product + // Determine cross product VectorCrossProduct crossProd = A.crossProduct(B); crossProd.displayVector(); - //Determine dot product + // Determine dot product int dotProd = A.dotProduct(B); System.out.println("Dot Product of A and B: " + dotProd); } diff --git a/src/main/java/com/thealgorithms/matrixexponentiation/Fibonacci.java b/src/main/java/com/thealgorithms/matrixexponentiation/Fibonacci.java index 7a370d0f..78487660 100644 --- a/src/main/java/com/thealgorithms/matrixexponentiation/Fibonacci.java +++ b/src/main/java/com/thealgorithms/matrixexponentiation/Fibonacci.java @@ -10,10 +10,10 @@ import java.util.Scanner; public class Fibonacci { // Exponentiation matrix for Fibonacci sequence - private static final int[][] fibMatrix = { { 1, 1 }, { 1, 0 } }; - private static final int[][] identityMatrix = { { 1, 0 }, { 0, 1 } }; - //First 2 fibonacci numbers - private static final int[][] baseFibNumbers = { { 1 }, { 0 } }; + private static final int[][] fibMatrix = {{1, 1}, {1, 0}}; + private static final int[][] identityMatrix = {{1, 0}, {0, 1}}; + // First 2 fibonacci numbers + private static final int[][] baseFibNumbers = {{1}, {0}}; /** * Performs multiplication of 2 matrices @@ -22,11 +22,8 @@ public class Fibonacci { * @param matrix2 * @return The product of matrix1 and matrix2 */ - private static int[][] matrixMultiplication( - int[][] matrix1, - int[][] matrix2 - ) { - //Check if matrices passed can be multiplied + private static int[][] matrixMultiplication(int[][] matrix1, int[][] matrix2) { + // Check if matrices passed can be multiplied int rowsInMatrix1 = matrix1.length; int columnsInMatrix1 = matrix1[0].length; @@ -38,14 +35,10 @@ public class Fibonacci { for (int rowIndex = 0; rowIndex < rowsInMatrix1; rowIndex++) { for (int colIndex = 0; colIndex < columnsInMatrix2; colIndex++) { int matrixEntry = 0; - for ( - int intermediateIndex = 0; - intermediateIndex < columnsInMatrix1; - intermediateIndex++ - ) { - matrixEntry += - matrix1[rowIndex][intermediateIndex] * - matrix2[intermediateIndex][colIndex]; + for (int intermediateIndex = 0; intermediateIndex < columnsInMatrix1; + intermediateIndex++) { + matrixEntry += matrix1[rowIndex][intermediateIndex] + * matrix2[intermediateIndex][colIndex]; } product[rowIndex][colIndex] = matrixEntry; } @@ -65,17 +58,11 @@ public class Fibonacci { return Fibonacci.identityMatrix; } else { int[][] cachedResult = fib(n / 2); - int[][] matrixExpResult = matrixMultiplication( - cachedResult, - cachedResult - ); + int[][] matrixExpResult = matrixMultiplication(cachedResult, cachedResult); if (n % 2 == 0) { return matrixExpResult; } else { - return matrixMultiplication( - Fibonacci.fibMatrix, - matrixExpResult - ); + return matrixMultiplication(Fibonacci.fibMatrix, matrixExpResult); } } } diff --git a/src/main/java/com/thealgorithms/minimizinglateness/MinimizingLateness.java b/src/main/java/com/thealgorithms/minimizinglateness/MinimizingLateness.java index 495492ed..cfd4ccbd 100644 --- a/src/main/java/com/thealgorithms/minimizinglateness/MinimizingLateness.java +++ b/src/main/java/com/thealgorithms/minimizinglateness/MinimizingLateness.java @@ -23,9 +23,8 @@ public class MinimizingLateness { public static void main(String[] args) throws IOException { StringTokenizer token; - BufferedReader in = new BufferedReader( - new FileReader("MinimizingLateness/lateness_data.txt") - ); + BufferedReader in + = new BufferedReader(new FileReader("MinimizingLateness/lateness_data.txt")); String ch = in.readLine(); if (ch == null || ch.isEmpty()) { in.close(); @@ -38,13 +37,10 @@ public class MinimizingLateness { 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()) - ); + // 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); } diff --git a/src/main/java/com/thealgorithms/misc/ColorContrastRatio.java b/src/main/java/com/thealgorithms/misc/ColorContrastRatio.java index 7db1f636..b0da6cba 100644 --- a/src/main/java/com/thealgorithms/misc/ColorContrastRatio.java +++ b/src/main/java/com/thealgorithms/misc/ColorContrastRatio.java @@ -54,9 +54,7 @@ public class ColorContrastRatio { */ public double getColor(int color8Bit) { final double sRgb = getColorSRgb(color8Bit); - return (sRgb <= 0.03928) - ? sRgb / 12.92 - : Math.pow((sRgb + 0.055) / 1.055, 2.4); + return (sRgb <= 0.03928) ? sRgb / 12.92 : Math.pow((sRgb + 0.055) / 1.055, 2.4); } /** @@ -83,38 +81,27 @@ public class ColorContrastRatio { final Color black = Color.BLACK; final double blackLuminance = algImpl.getRelativeLuminance(black); - assert blackLuminance == - 0 : "Test 1 Failed - Incorrect relative luminance."; + assert blackLuminance == 0 : "Test 1 Failed - Incorrect relative luminance."; final Color white = Color.WHITE; final double whiteLuminance = algImpl.getRelativeLuminance(white); - assert whiteLuminance == - 1 : "Test 2 Failed - Incorrect relative luminance."; + assert whiteLuminance == 1 : "Test 2 Failed - Incorrect relative luminance."; final double highestColorRatio = algImpl.getContrastRatio(black, white); - assert highestColorRatio == - 21 : "Test 3 Failed - Incorrect contrast ratio."; + assert highestColorRatio == 21 : "Test 3 Failed - Incorrect contrast ratio."; final Color foreground = new Color(23, 103, 154); - final double foregroundLuminance = algImpl.getRelativeLuminance( - foreground - ); - assert foregroundLuminance == - 0.12215748057375966 : "Test 4 Failed - Incorrect relative luminance."; + final double foregroundLuminance = algImpl.getRelativeLuminance(foreground); + assert foregroundLuminance + == 0.12215748057375966 : "Test 4 Failed - Incorrect relative luminance."; final Color background = new Color(226, 229, 248); - final double backgroundLuminance = algImpl.getRelativeLuminance( - background - ); - assert backgroundLuminance == - 0.7898468477881603 : "Test 5 Failed - Incorrect relative luminance."; + final double backgroundLuminance = algImpl.getRelativeLuminance(background); + assert backgroundLuminance + == 0.7898468477881603 : "Test 5 Failed - Incorrect relative luminance."; - final double contrastRatio = algImpl.getContrastRatio( - foreground, - background - ); - assert contrastRatio == - 4.878363954846178 : "Test 6 Failed - Incorrect contrast ratio."; + final double contrastRatio = algImpl.getContrastRatio(foreground, background); + assert contrastRatio == 4.878363954846178 : "Test 6 Failed - Incorrect contrast ratio."; } public static void main(String[] args) { diff --git a/src/main/java/com/thealgorithms/misc/InverseOfMatrix.java b/src/main/java/com/thealgorithms/misc/InverseOfMatrix.java index 105612ae..0fb5b6f1 100644 --- a/src/main/java/com/thealgorithms/misc/InverseOfMatrix.java +++ b/src/main/java/com/thealgorithms/misc/InverseOfMatrix.java @@ -6,7 +6,8 @@ import java.util.Scanner; * Wikipedia link : https://en.wikipedia.org/wiki/Invertible_matrix * * Here we use gauss elimination method to find the inverse of a given matrix. - * To understand gauss elimination method to find inverse of a matrix: https://www.sangakoo.com/en/unit/inverse-matrix-method-of-gaussian-elimination + * To understand gauss elimination method to find inverse of a matrix: + * https://www.sangakoo.com/en/unit/inverse-matrix-method-of-gaussian-elimination * * We can also find the inverse of a matrix */ diff --git a/src/main/java/com/thealgorithms/misc/MedianOfRunningArray.java b/src/main/java/com/thealgorithms/misc/MedianOfRunningArray.java index d5572a94..84dff89e 100644 --- a/src/main/java/com/thealgorithms/misc/MedianOfRunningArray.java +++ b/src/main/java/com/thealgorithms/misc/MedianOfRunningArray.java @@ -44,7 +44,7 @@ public class MedianOfRunningArray { */ MedianOfRunningArray p = new MedianOfRunningArray(); - int[] arr = { 10, 7, 4, 9, 2, 3, 11, 17, 14 }; + 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() + " "); diff --git a/src/main/java/com/thealgorithms/misc/PalindromePrime.java b/src/main/java/com/thealgorithms/misc/PalindromePrime.java index ac6d2750..58de9383 100644 --- a/src/main/java/com/thealgorithms/misc/PalindromePrime.java +++ b/src/main/java/com/thealgorithms/misc/PalindromePrime.java @@ -6,9 +6,7 @@ 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" - ); + System.out.println("Enter the quantity of First Palindromic Primes you want"); int n = in.nextInt(); // Input of how many first palindromic prime we want functioning(n); // calling function - functioning in.close(); diff --git a/src/main/java/com/thealgorithms/misc/RangeInSortedArray.java b/src/main/java/com/thealgorithms/misc/RangeInSortedArray.java index c8526407..b9e6fbb7 100644 --- a/src/main/java/com/thealgorithms/misc/RangeInSortedArray.java +++ b/src/main/java/com/thealgorithms/misc/RangeInSortedArray.java @@ -6,39 +6,24 @@ public class RangeInSortedArray { public static void main(String[] args) { // Testcases - assert Arrays.equals( - sortedRange(new int[] { 1, 2, 3, 3, 3, 4, 5 }, 3), - new int[] { 2, 4 } - ); - assert Arrays.equals( - sortedRange(new int[] { 1, 2, 3, 3, 3, 4, 5 }, 4), - new int[] { 5, 5 } - ); - assert Arrays.equals( - sortedRange(new int[] { 0, 1, 2 }, 3), - new int[] { -1, -1 } - ); + assert Arrays.equals(sortedRange(new int[] {1, 2, 3, 3, 3, 4, 5}, 3), new int[] {2, 4}); + assert Arrays.equals(sortedRange(new int[] {1, 2, 3, 3, 3, 4, 5}, 4), new int[] {5, 5}); + assert Arrays.equals(sortedRange(new int[] {0, 1, 2}, 3), new int[] {-1, -1}); } // Get the 1st and last occurrence index of a number 'key' in a non-decreasing array 'nums' // Gives [-1, -1] in case element doesn't exist in array public static int[] sortedRange(int[] nums, int key) { - int[] range = new int[] { -1, -1 }; + int[] range = new int[] {-1, -1}; alteredBinSearchIter(nums, key, 0, nums.length - 1, range, true); alteredBinSearchIter(nums, key, 0, nums.length - 1, range, false); return range; } - // Recursive altered binary search which searches for leftmost as well as rightmost occurrence of - // 'key' + // Recursive altered binary search which searches for leftmost as well as rightmost occurrence + // of 'key' public static void alteredBinSearch( - int[] nums, - int key, - int left, - int right, - int[] range, - boolean goLeft - ) { + int[] nums, int key, int left, int right, int[] range, boolean goLeft) { if (left > right) { return; } @@ -64,16 +49,10 @@ public class RangeInSortedArray { } } - // Iterative altered binary search which searches for leftmost as well as rightmost occurrence of - // 'key' + // Iterative altered binary search which searches for leftmost as well as rightmost occurrence + // of 'key' public static void alteredBinSearchIter( - int[] nums, - int key, - int left, - int right, - int[] range, - boolean goLeft - ) { + int[] nums, int key, int left, int right, int[] range, boolean goLeft) { while (left <= right) { int mid = (left + right) / 2; if (nums[mid] > key) { diff --git a/src/main/java/com/thealgorithms/misc/Sort012D.java b/src/main/java/com/thealgorithms/misc/Sort012D.java index 18cb3cb0..1337e5ca 100644 --- a/src/main/java/com/thealgorithms/misc/Sort012D.java +++ b/src/main/java/com/thealgorithms/misc/Sort012D.java @@ -30,26 +30,24 @@ public class Sort012D { int temp; while (mid <= h) { switch (a[mid]) { - case 0: - { - temp = a[l]; - a[l] = a[mid]; - a[mid] = temp; - l++; - mid++; - break; - } - case 1: - mid++; - break; - case 2: - { - temp = a[mid]; - a[mid] = a[h]; - a[h] = temp; - h--; - break; - } + case 0: { + temp = a[l]; + a[l] = a[mid]; + a[mid] = temp; + l++; + mid++; + break; + } + case 1: + mid++; + break; + case 2: { + temp = a[mid]; + a[mid] = a[h]; + a[h] = temp; + h--; + break; + } } } System.out.println("the Sorted array is "); diff --git a/src/main/java/com/thealgorithms/misc/Sparcity.java b/src/main/java/com/thealgorithms/misc/Sparcity.java index 93264160..994f1919 100644 --- a/src/main/java/com/thealgorithms/misc/Sparcity.java +++ b/src/main/java/com/thealgorithms/misc/Sparcity.java @@ -3,8 +3,10 @@ package com.thealgorithms.misc; import java.util.*; /* - *A matrix is sparse if many of its coefficients are zero (In general if 2/3rd of matrix elements are 0, it is considered as sparse). - *The interest in sparsity arises because its exploitation can lead to enormous computational savings and because many large matrix problems that occur in practice are sparse. + *A matrix is sparse if many of its coefficients are zero (In general if 2/3rd of matrix elements + *are 0, it is considered as sparse). The interest in sparsity arises because its exploitation can + *lead to enormous computational savings and because many large matrix problems that occur in + *practice are sparse. * * @author Ojasva Jain */ @@ -19,7 +21,7 @@ class Sparcity { */ static double sparcity(double[][] mat) { int zero = 0; - //Traversing the matrix to count number of zeroes + // Traversing the matrix to count number of zeroes for (int i = 0; i < mat.length; i++) { for (int j = 0; j < mat[i].length; j++) { if (mat[i][j] == 0) { @@ -27,11 +29,11 @@ class Sparcity { } } } - //return sparcity + // return sparcity return ((double) zero / (mat.length * mat[1].length)); } - //Driver method + // Driver method public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter number of rows in matrix: "); diff --git a/src/main/java/com/thealgorithms/misc/ThreeSumProblem.java b/src/main/java/com/thealgorithms/misc/ThreeSumProblem.java index 5700b94a..fcd7a432 100644 --- a/src/main/java/com/thealgorithms/misc/ThreeSumProblem.java +++ b/src/main/java/com/thealgorithms/misc/ThreeSumProblem.java @@ -16,12 +16,8 @@ public class ThreeSumProblem { arr[i] = scan.nextInt(); } ThreeSumProblem th = new ThreeSumProblem(); - System.out.println( - "Brute Force Approach\n" + (th.BruteForce(arr, ts)) + "\n" - ); - System.out.println( - "Two Pointer Approach\n" + (th.TwoPointer(arr, ts)) + "\n" - ); + System.out.println("Brute Force Approach\n" + (th.BruteForce(arr, ts)) + "\n"); + System.out.println("Two Pointer Approach\n" + (th.TwoPointer(arr, ts)) + "\n"); System.out.println("Hashmap Approach\n" + (th.Hashmap(arr, ts))); } @@ -42,8 +38,7 @@ public class ThreeSumProblem { } } } - arr = - new ArrayList>(new LinkedHashSet>(arr)); + arr = new ArrayList>(new LinkedHashSet>(arr)); return arr; } diff --git a/src/main/java/com/thealgorithms/misc/WordBoggle.java b/src/main/java/com/thealgorithms/misc/WordBoggle.java index 1257c536..5513bdc5 100644 --- a/src/main/java/com/thealgorithms/misc/WordBoggle.java +++ b/src/main/java/com/thealgorithms/misc/WordBoggle.java @@ -27,54 +27,36 @@ public class WordBoggle { public static void main(String[] args) { // Testcase List ans = new ArrayList<>( - Arrays.asList( - "a", - "boggle", + Arrays.asList("a", "boggle", "this", "NOTRE_PEATED", "is", "simple", "board")); + assert (boggleBoard( + new char[][] { + {'t', 'h', 'i', 's', 'i', 's', 'a'}, + {'s', 'i', 'm', 'p', 'l', 'e', 'x'}, + {'b', 'x', 'x', 'x', 'x', 'e', 'b'}, + {'x', 'o', 'g', 'g', 'l', 'x', 'o'}, + {'x', 'x', 'x', 'D', 'T', 'r', 'a'}, + {'R', 'E', 'P', 'E', 'A', 'd', 'x'}, + {'x', 'x', 'x', 'x', 'x', 'x', 'x'}, + {'N', 'O', 'T', 'R', 'E', '_', 'P'}, + {'x', 'x', 'D', 'E', 'T', 'A', 'E'}, + }, + new String[] { "this", - "NOTRE_PEATED", "is", + "not", + "a", "simple", - "board" - ) - ); - assert ( - boggleBoard( - new char[][] { - { 't', 'h', 'i', 's', 'i', 's', 'a' }, - { 's', 'i', 'm', 'p', 'l', 'e', 'x' }, - { 'b', 'x', 'x', 'x', 'x', 'e', 'b' }, - { 'x', 'o', 'g', 'g', 'l', 'x', 'o' }, - { 'x', 'x', 'x', 'D', 'T', 'r', 'a' }, - { 'R', 'E', 'P', 'E', 'A', 'd', 'x' }, - { 'x', 'x', 'x', 'x', 'x', 'x', 'x' }, - { 'N', 'O', 'T', 'R', 'E', '_', 'P' }, - { 'x', 'x', 'D', 'E', 'T', 'A', 'E' }, - }, - new String[] { - "this", - "is", - "not", - "a", - "simple", - "test", - "boggle", - "board", - "REPEATED", - "NOTRE_PEATED", - } - ) - .equals(ans) - ); + "test", + "boggle", + "board", + "REPEATED", + "NOTRE_PEATED", + }) + .equals(ans)); } - public static void explore( - int i, - int j, - char[][] board, - TrieNode trieNode, - boolean[][] visited, - Set finalWords - ) { + public static void explore(int i, int j, char[][] board, TrieNode trieNode, boolean[][] visited, + Set finalWords) { if (visited[i][j]) { return; } @@ -91,14 +73,7 @@ public class WordBoggle { List neighbors = getNeighbors(i, j, board); for (Integer[] neighbor : neighbors) { - explore( - neighbor[0], - neighbor[1], - board, - trieNode, - visited, - finalWords - ); + explore(neighbor[0], neighbor[1], board, trieNode, visited, finalWords); } visited[i][j] = false; @@ -107,35 +82,35 @@ public class WordBoggle { public static List getNeighbors(int i, int j, char[][] board) { List neighbors = new ArrayList<>(); if (i > 0 && j > 0) { - neighbors.add(new Integer[] { i - 1, j - 1 }); + neighbors.add(new Integer[] {i - 1, j - 1}); } if (i > 0 && j < board[0].length - 1) { - neighbors.add(new Integer[] { i - 1, j + 1 }); + neighbors.add(new Integer[] {i - 1, j + 1}); } if (i < board.length - 1 && j < board[0].length - 1) { - neighbors.add(new Integer[] { i + 1, j + 1 }); + neighbors.add(new Integer[] {i + 1, j + 1}); } if (i < board.length - 1 && j > 0) { - neighbors.add(new Integer[] { i + 1, j - 1 }); + neighbors.add(new Integer[] {i + 1, j - 1}); } if (i > 0) { - neighbors.add(new Integer[] { i - 1, j }); + neighbors.add(new Integer[] {i - 1, j}); } if (i < board.length - 1) { - neighbors.add(new Integer[] { i + 1, j }); + neighbors.add(new Integer[] {i + 1, j}); } if (j > 0) { - neighbors.add(new Integer[] { i, j - 1 }); + neighbors.add(new Integer[] {i, j - 1}); } if (j < board[0].length - 1) { - neighbors.add(new Integer[] { i, j + 1 }); + neighbors.add(new Integer[] {i, j + 1}); } return neighbors; diff --git a/src/main/java/com/thealgorithms/others/BFPRT.java b/src/main/java/com/thealgorithms/others/BFPRT.java index f296fbda..29f47cd6 100644 --- a/src/main/java/com/thealgorithms/others/BFPRT.java +++ b/src/main/java/com/thealgorithms/others/BFPRT.java @@ -66,8 +66,7 @@ public class BFPRT { int offset = num % 5 == 0 ? 0 : 1; int[] mArr = new int[num / 5 + offset]; for (int i = 0; i < mArr.length; i++) { - mArr[i] = - getMedian(arr, begin + i * 5, Math.min(end, begin + i * 5 + 4)); + mArr[i] = getMedian(arr, begin + i * 5, Math.min(end, begin + i * 5 + 4)); } return bfprt(mArr, 0, mArr.length - 1, mArr.length / 2); } diff --git a/src/main/java/com/thealgorithms/others/BankersAlgorithm.java b/src/main/java/com/thealgorithms/others/BankersAlgorithm.java index 7e6ce9db..f6a28729 100644 --- a/src/main/java/com/thealgorithms/others/BankersAlgorithm.java +++ b/src/main/java/com/thealgorithms/others/BankersAlgorithm.java @@ -25,13 +25,8 @@ public class BankersAlgorithm { /** * This method finds the need of each process */ - static void calculateNeed( - int[][] needArray, - int[][] maxArray, - int[][] allocationArray, - int totalProcess, - int totalResources - ) { + static void calculateNeed(int[][] needArray, int[][] maxArray, int[][] allocationArray, + int totalProcess, int totalResources) { for (int i = 0; i < totalProcess; i++) { for (int j = 0; j < totalResources; j++) { needArray[i][j] = maxArray[i][j] - allocationArray[i][j]; @@ -54,23 +49,11 @@ public class BankersAlgorithm { * * @return boolean if the system is in safe state or not */ - static boolean checkSafeSystem( - int[] processes, - int[] availableArray, - int[][] maxArray, - int[][] allocationArray, - int totalProcess, - int totalResources - ) { + static boolean checkSafeSystem(int[] processes, int[] availableArray, int[][] maxArray, + int[][] allocationArray, int totalProcess, int totalResources) { int[][] needArray = new int[totalProcess][totalResources]; - calculateNeed( - needArray, - maxArray, - allocationArray, - totalProcess, - totalResources - ); + calculateNeed(needArray, maxArray, allocationArray, totalProcess, totalResources); boolean[] finishProcesses = new boolean[totalProcess]; @@ -113,16 +96,12 @@ public class BankersAlgorithm { // If we could not find a next process in safe sequence. if (!foundSafeSystem) { - System.out.print( - "The system is not in the safe state because lack of resources" - ); + System.out.print("The system is not in the safe state because lack of resources"); return false; } } - System.out.print( - "The system is in safe sequence and the sequence is as follows: " - ); + System.out.print("The system is in safe sequence and the sequence is as follows: "); for (int i = 0; i < totalProcess; i++) { System.out.print("P" + safeSequenceArray[i] + " "); } @@ -163,9 +142,7 @@ public class BankersAlgorithm { for (int i = 0; i < numberOfProcesses; i++) { System.out.println("For process " + i + ": "); for (int j = 0; j < numberOfResources; j++) { - System.out.println( - "Enter the maximum instances of resource " + j - ); + System.out.println("Enter the maximum instances of resource " + j); maxArray[i][j] = sc.nextInt(); } } @@ -181,20 +158,14 @@ public class BankersAlgorithm { } } - checkSafeSystem( - processes, - availableArray, - maxArray, - allocationArray, - numberOfProcesses, - numberOfResources - ); + checkSafeSystem(processes, availableArray, maxArray, allocationArray, numberOfProcesses, + numberOfResources); sc.close(); } } /* - Example: + Example: n = 5 m = 3 @@ -202,10 +173,10 @@ public class BankersAlgorithm { 0 1 2 0 1 2 0 1 2 0 0 1 0 7 5 3 3 3 2 - 1 2 0 0 3 2 2 + 1 2 0 0 3 2 2 2 3 0 2 9 0 2 3 2 1 1 2 2 2 4 0 0 2 4 3 3 - Result: The system is in safe sequence and the sequence is as follows: P1, P3, P4, P0, P2 + Result: The system is in safe sequence and the sequence is as follows: P1, P3, P4, P0, P2 */ diff --git a/src/main/java/com/thealgorithms/others/BoyerMoore.java b/src/main/java/com/thealgorithms/others/BoyerMoore.java index 2e4edbd9..f12e2cff 100644 --- a/src/main/java/com/thealgorithms/others/BoyerMoore.java +++ b/src/main/java/com/thealgorithms/others/BoyerMoore.java @@ -1,7 +1,8 @@ /* this Code is the illustration of Boyer moore's voting algorithm to find the majority element is an array that appears more than n/2 times in an array where "n" is the length of the array. -For more information on the algorithm refer https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm +For more information on the algorithm refer +https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm */ package com.thealgorithms.others; diff --git a/src/main/java/com/thealgorithms/others/CRC16.java b/src/main/java/com/thealgorithms/others/CRC16.java index 80dbbcb9..c5c3b1f3 100644 --- a/src/main/java/com/thealgorithms/others/CRC16.java +++ b/src/main/java/com/thealgorithms/others/CRC16.java @@ -1,7 +1,7 @@ package com.thealgorithms.others; /** - * Generates a crc16 checksum for a given string + * Generates a crc16 checksum for a given string */ public class CRC16 { @@ -9,21 +9,20 @@ public class CRC16 { System.out.println(crc16("Hello World!")); } - public static String crc16(String message) { - int crc = 0xFFFF; // initial value - int polynomial = 0x1021; // 0001 0000 0010 0001 (0, 5, 12) - byte[] bytes = message.getBytes(); + public static String crc16(String message) { + int crc = 0xFFFF; // initial value + int polynomial = 0x1021; // 0001 0000 0010 0001 (0, 5, 12) + byte[] bytes = message.getBytes(); - for (byte b : bytes) { - for (int i = 0; i < 8; i++) { - boolean bit = ((b >> (7 - i) & 1) == 1); - boolean c15 = ((crc >> 15 & 1) == 1); - crc <<= 1; - if (c15 ^ bit) - crc ^= polynomial; - } - } - crc &= 0xffff; - return Integer.toHexString(crc).toUpperCase(); - } + for (byte b : bytes) { + for (int i = 0; i < 8; i++) { + boolean bit = ((b >> (7 - i) & 1) == 1); + boolean c15 = ((crc >> 15 & 1) == 1); + crc <<= 1; + if (c15 ^ bit) crc ^= polynomial; + } + } + crc &= 0xffff; + return Integer.toHexString(crc).toUpperCase(); + } } diff --git a/src/main/java/com/thealgorithms/others/Conway.java b/src/main/java/com/thealgorithms/others/Conway.java index 7a034d96..b1d54e61 100644 --- a/src/main/java/com/thealgorithms/others/Conway.java +++ b/src/main/java/com/thealgorithms/others/Conway.java @@ -6,27 +6,24 @@ public class Conway { /* * This class will generate the conway sequence also known as the look and say sequence. - * To generate a member of the sequence from the previous member, read off the digits of the previous member, counting the number of digits in groups of the same digit. For example: - *1 is read off as "one 1" or 11. - *11 is read off as "two 1s" or 21. - *21 is read off as "one 2, one 1" or 1211. - *1211 is read off as "one 1, one 2, two 1s" or 111221. - *111221 is read off as "three 1s, two 2s, one 1" or 312211. - * https://en.wikipedia.org/wiki/Look-and-say_sequence + * To generate a member of the sequence from the previous member, read off the digits of the + *previous member, counting the number of digits in groups of the same digit. For example: 1 is + *read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, one 1" + *or 1211. 1211 is read off as "one 1, one 2, two 1s" or 111221. 111221 is read off as "three + *1s, two 2s, one 1" or 312211. https://en.wikipedia.org/wiki/Look-and-say_sequence * */ private static final StringBuilder builder = new StringBuilder(); protected static List generateList(String originalString, int maxIteration) { List numbers = new ArrayList<>(); - for(int i=0; i a : u.neighbours.entrySet()) { @@ -230,10 +222,7 @@ class Graph { */ public void printPath(String endName) { if (!graph.containsKey(endName)) { - System.err.printf( - "Graph doesn't contain end vertex \"%s\"%n", - endName - ); + System.err.printf("Graph doesn't contain end vertex \"%s\"%n", endName); return; } diff --git a/src/main/java/com/thealgorithms/others/FloydTriangle.java b/src/main/java/com/thealgorithms/others/FloydTriangle.java index a21ba479..d25ab303 100644 --- a/src/main/java/com/thealgorithms/others/FloydTriangle.java +++ b/src/main/java/com/thealgorithms/others/FloydTriangle.java @@ -6,9 +6,7 @@ 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: " - ); + 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++) { diff --git a/src/main/java/com/thealgorithms/others/HappyNumbersSeq.java b/src/main/java/com/thealgorithms/others/HappyNumbersSeq.java index 006b165a..88951765 100644 --- a/src/main/java/com/thealgorithms/others/HappyNumbersSeq.java +++ b/src/main/java/com/thealgorithms/others/HappyNumbersSeq.java @@ -7,9 +7,8 @@ import java.util.Set; public class HappyNumbersSeq { - private static final Set CYCLE_NUMS = new HashSet<>( - Arrays.asList(4, 16, 20, 37, 58, 145) - ); + private static final Set CYCLE_NUMS + = new HashSet<>(Arrays.asList(4, 16, 20, 37, 58, 145)); public static void main(String[] args) { Scanner in = new Scanner(System.in); diff --git a/src/main/java/com/thealgorithms/others/Huffman.java b/src/main/java/com/thealgorithms/others/Huffman.java index cf36ae22..a5af2bec 100644 --- a/src/main/java/com/thealgorithms/others/Huffman.java +++ b/src/main/java/com/thealgorithms/others/Huffman.java @@ -35,11 +35,7 @@ public class Huffman { // base case; if the left and right are null // then its a leaf node and we print // the code s generated by traversing the tree. - if ( - root.left == null && - root.right == null && - Character.isLetter(root.c) - ) { + if (root.left == null && root.right == null && Character.isLetter(root.c)) { // c is the character in the node System.out.println(root.c + ":" + s); @@ -60,15 +56,12 @@ public class Huffman { // number of characters. int n = 6; - char[] charArray = { 'a', 'b', 'c', 'd', 'e', 'f' }; - int[] charfreq = { 5, 9, 12, 13, 16, 45 }; + char[] charArray = {'a', 'b', 'c', 'd', 'e', 'f'}; + int[] charfreq = {5, 9, 12, 13, 16, 45}; // creating a priority queue q. // makes a min-priority queue(min-heap). - PriorityQueue q = new PriorityQueue( - n, - new MyComparator() - ); + PriorityQueue q = new PriorityQueue(n, new MyComparator()); for (int i = 0; i < n; i++) { // creating a Huffman node object diff --git a/src/main/java/com/thealgorithms/others/Implementing_auto_completing_features_using_trie.java b/src/main/java/com/thealgorithms/others/Implementing_auto_completing_features_using_trie.java index 3904691a..bb88c7e3 100644 --- a/src/main/java/com/thealgorithms/others/Implementing_auto_completing_features_using_trie.java +++ b/src/main/java/com/thealgorithms/others/Implementing_auto_completing_features_using_trie.java @@ -160,11 +160,11 @@ class Trieac { int comp = printAutoSuggestions(root, "hel"); if (comp == -1) { - System.out.println( - "No other strings found " + "with this prefix\n" - ); + System.out.println("No other strings found " + + "with this prefix\n"); } else if (comp == 0) { - System.out.println("No string found with" + " this prefix\n"); + System.out.println("No string found with" + + " this prefix\n"); } } } diff --git a/src/main/java/com/thealgorithms/others/InsertDeleteInArray.java b/src/main/java/com/thealgorithms/others/InsertDeleteInArray.java index 81697750..c90cfea1 100644 --- a/src/main/java/com/thealgorithms/others/InsertDeleteInArray.java +++ b/src/main/java/com/thealgorithms/others/InsertDeleteInArray.java @@ -18,9 +18,7 @@ public class InsertDeleteInArray { } // To insert a new element(we are creating a new array) - System.out.println( - "Enter the index at which the element should be inserted" - ); + 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(); diff --git a/src/main/java/com/thealgorithms/others/KochSnowflake.java b/src/main/java/com/thealgorithms/others/KochSnowflake.java index f82a8125..91070920 100644 --- a/src/main/java/com/thealgorithms/others/KochSnowflake.java +++ b/src/main/java/com/thealgorithms/others/KochSnowflake.java @@ -56,8 +56,7 @@ public class KochSnowflake { assert image.getRGB(0, 0) == new Color(255, 255, 255).getRGB(); // The snowflake is drawn in black and this is the position of the first vector - assert image.getRGB((int) offsetX, (int) offsetY) == - new Color(0, 0, 0).getRGB(); + assert image.getRGB((int) offsetX, (int) offsetY) == new Color(0, 0, 0).getRGB(); // Save image try { @@ -77,10 +76,7 @@ public class KochSnowflake { * @param steps The number of iterations. * @return The transformed vectors after the iteration-steps. */ - public static ArrayList Iterate( - ArrayList initialVectors, - int steps - ) { + public static ArrayList Iterate(ArrayList initialVectors, int steps) { ArrayList vectors = initialVectors; for (int i = 0; i < steps; i++) { vectors = IterationStep(vectors); @@ -98,18 +94,14 @@ public class KochSnowflake { */ public static BufferedImage GetKochSnowflake(int imageWidth, int steps) { if (imageWidth <= 0) { - throw new IllegalArgumentException( - "imageWidth should be greater than zero" - ); + throw new IllegalArgumentException("imageWidth should be greater than zero"); } double offsetX = imageWidth / 10.; double offsetY = imageWidth / 3.7; Vector2 vector1 = new Vector2(offsetX, offsetY); - Vector2 vector2 = new Vector2( - imageWidth / 2, - Math.sin(Math.PI / 3) * imageWidth * 0.8 + offsetY - ); + Vector2 vector2 + = new Vector2(imageWidth / 2, Math.sin(Math.PI / 3) * imageWidth * 0.8 + offsetY); Vector2 vector3 = new Vector2(imageWidth - offsetX, offsetY); ArrayList initialVectors = new ArrayList(); initialVectors.add(vector1); @@ -130,23 +122,15 @@ public class KochSnowflake { * applied. * @return The transformed vectors after the iteration-step. */ - private static ArrayList IterationStep( - ArrayList vectors - ) { + private static ArrayList IterationStep(ArrayList vectors) { ArrayList newVectors = new ArrayList(); for (int i = 0; i < vectors.size() - 1; i++) { Vector2 startVector = vectors.get(i); Vector2 endVector = vectors.get(i + 1); newVectors.add(startVector); - Vector2 differenceVector = endVector - .subtract(startVector) - .multiply(1. / 3); + Vector2 differenceVector = endVector.subtract(startVector).multiply(1. / 3); newVectors.add(startVector.add(differenceVector)); - newVectors.add( - startVector - .add(differenceVector) - .add(differenceVector.rotate(60)) - ); + newVectors.add(startVector.add(differenceVector).add(differenceVector.rotate(60))); newVectors.add(startVector.add(differenceVector.multiply(2))); } @@ -163,15 +147,9 @@ public class KochSnowflake { * @return The image of the rendered edges. */ private static BufferedImage GetImage( - ArrayList vectors, - int imageWidth, - int imageHeight - ) { - BufferedImage image = new BufferedImage( - imageWidth, - imageHeight, - BufferedImage.TYPE_INT_RGB - ); + ArrayList vectors, int imageWidth, int imageHeight) { + BufferedImage image + = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = image.createGraphics(); // Set the background white diff --git a/src/main/java/com/thealgorithms/others/LineSweep.java b/src/main/java/com/thealgorithms/others/LineSweep.java index f9db1f74..9aa0f6fa 100644 --- a/src/main/java/com/thealgorithms/others/LineSweep.java +++ b/src/main/java/com/thealgorithms/others/LineSweep.java @@ -13,31 +13,33 @@ import java.util.Comparator; */ public class LineSweep { - /** Find Maximum end point + /** + * Find Maximum end point * param = ranges : Array of range[start,end] * return Maximum Endpoint */ - public static int FindMaximumEndPoint (int[][]ranges){ - Arrays.sort(ranges, Comparator.comparingInt(a->a[1])); - return ranges[ranges.length-1][1]; - } + public static int FindMaximumEndPoint(int[][] ranges) { + Arrays.sort(ranges, Comparator.comparingInt(a -> a[1])); + return ranges[ranges.length - 1][1]; + } - /** Find if any ranges overlap + /** + * Find if any ranges overlap * param = ranges : Array of range[start,end] * return true if overlap exists false otherwise. */ public static boolean isOverlap(int[][] ranges) { int maximumEndPoint = FindMaximumEndPoint(ranges); - Arrays.sort(ranges, Comparator.comparingInt(a->a[0])); - int[] numberLine = new int[maximumEndPoint+2]; + Arrays.sort(ranges, Comparator.comparingInt(a -> a[0])); + int[] numberLine = new int[maximumEndPoint + 2]; for (int[] range : ranges) { int start = range[0]; int end = range[1]; numberLine[start] += 1; - numberLine[end+1] -= 1; + numberLine[end + 1] -= 1; } int current = 0; @@ -46,6 +48,6 @@ public class LineSweep { current += num; overlaps = Math.max(overlaps, current); } - return overlaps >1 ; + return overlaps > 1; } } diff --git a/src/main/java/com/thealgorithms/others/LinearCongruentialGenerator.java b/src/main/java/com/thealgorithms/others/LinearCongruentialGenerator.java index c96da433..f16946dc 100644 --- a/src/main/java/com/thealgorithms/others/LinearCongruentialGenerator.java +++ b/src/main/java/com/thealgorithms/others/LinearCongruentialGenerator.java @@ -21,11 +21,7 @@ public class LinearCongruentialGenerator { * @param modulo The maximum number that can be generated (exclusive). A * common value is 2^32. */ - public LinearCongruentialGenerator( - double multiplier, - double increment, - double modulo - ) { + public LinearCongruentialGenerator(double multiplier, double increment, double modulo) { this(System.currentTimeMillis(), multiplier, increment, modulo); } @@ -40,11 +36,7 @@ public class LinearCongruentialGenerator { * common value is 2^32. */ public LinearCongruentialGenerator( - double seed, - double multiplier, - double increment, - double modulo - ) { + double seed, double multiplier, double increment, double modulo) { this.previousValue = seed; this.a = multiplier; this.c = increment; @@ -66,11 +58,8 @@ public class LinearCongruentialGenerator { // 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) - ); + 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/src/main/java/com/thealgorithms/others/LowestBasePalindrome.java b/src/main/java/com/thealgorithms/others/LowestBasePalindrome.java index addf8255..9bc02535 100644 --- a/src/main/java/com/thealgorithms/others/LowestBasePalindrome.java +++ b/src/main/java/com/thealgorithms/others/LowestBasePalindrome.java @@ -27,7 +27,8 @@ final public class LowestBasePalindrome { * @param number the input number * @param base the given base * @exception IllegalArgumentException number is negative or base is less than 2 - * @return the list containing the digits of the input number in the given base, the most significant digit is at the end of the array + * @return the list containing the digits of the input number in the given base, the most + * significant digit is at the end of the array */ public static ArrayList computeDigitsInBase(int number, int base) { checkNumber(number); @@ -46,8 +47,8 @@ final public class LowestBasePalindrome { * @return true, if the input array is a palindrome, false otherwise */ public static boolean isPalindromic(ArrayList list) { - for (int pos = 0; pos < list.size()/2; ++pos) { - if(list.get(pos) != list.get(list.size()-1-pos)) { + for (int pos = 0; pos < list.size() / 2; ++pos) { + if (list.get(pos) != list.get(list.size() - 1 - pos)) { return false; } } @@ -59,7 +60,8 @@ final public class LowestBasePalindrome { * @param number the input number * @param base the given base * @exception IllegalArgumentException number is negative or base is less than 2 - * @return true, if the input number represented in the given base is a palindrome, false otherwise + * @return true, if the input number represented in the given base is a palindrome, false + * otherwise */ public static boolean isPalindromicInBase(int number, int base) { checkNumber(number); @@ -78,14 +80,15 @@ final public class LowestBasePalindrome { } /** - * @brief finds the smallest base for which the representation of the input number is a palindrome + * @brief finds the smallest base for which the representation of the input number is a + * palindrome * @param number the input number * @exception IllegalArgumentException number is negative * @return the smallest base for which the representation of the input number is a palindrome */ public static int lowestBasePalindrome(int number) { int base = 2; - while(!isPalindromicInBase(number, base)) { + while (!isPalindromicInBase(number, base)) { ++base; } return base; diff --git a/src/main/java/com/thealgorithms/others/Luhn.java b/src/main/java/com/thealgorithms/others/Luhn.java index 319955e7..269250ba 100644 --- a/src/main/java/com/thealgorithms/others/Luhn.java +++ b/src/main/java/com/thealgorithms/others/Luhn.java @@ -67,8 +67,9 @@ public class Luhn { public static void main(String[] args) { System.out.println("Luhn algorithm usage examples:"); - int[] validInput = { 4, 5, 6, 1, 2, 6, 1, 2, 1, 2, 3, 4, 5, 4, 6, 7 }; - int[] invalidInput = { 4, 5, 6, 1, 2, 6, 1, 2, 1, 2, 3, 4, 5, 4, 6, 4 }; //typo in last symbol + int[] validInput = {4, 5, 6, 1, 2, 6, 1, 2, 1, 2, 3, 4, 5, 4, 6, 7}; + int[] invalidInput = {4, 5, 6, 1, 2, 6, 1, 2, 1, 2, 3, 4, 5, 4, 6, 4}; // typo in last + // symbol checkAndPrint(validInput); checkAndPrint(invalidInput); @@ -83,9 +84,7 @@ public class Luhn { private static void checkAndPrint(int[] input) { String validationResult = Luhn.luhnCheck(input) ? "valid" : "not valid"; - System.out.println( - "Input " + Arrays.toString(input) + " is " + validationResult - ); + System.out.println("Input " + Arrays.toString(input) + " is " + validationResult); } /* @@ -109,21 +108,15 @@ public class Luhn { public static CreditCard fromString(String cardNumber) { Objects.requireNonNull(cardNumber); String trimmedCardNumber = cardNumber.replaceAll(" ", ""); - if ( - trimmedCardNumber.length() != DIGITS_COUNT || - !trimmedCardNumber.matches("\\d+") - ) { - throw new IllegalArgumentException( - "{" + cardNumber + "} - is not a card number" - ); + if (trimmedCardNumber.length() != DIGITS_COUNT || !trimmedCardNumber.matches("\\d+")) { + throw new IllegalArgumentException("{" + cardNumber + "} - is not a card number"); } int[] cardNumbers = toIntArray(trimmedCardNumber); boolean isValid = luhnCheck(cardNumbers); if (!isValid) { throw new IllegalArgumentException( - "Credit card number {" + cardNumber + "} - have a typo" - ); + "Credit card number {" + cardNumber + "} - have a typo"); } return new CreditCard(cardNumbers); @@ -146,11 +139,7 @@ public class Luhn { @Override public String toString() { - return String.format( - "%s {%s}", - CreditCard.class.getSimpleName(), - number() - ); + return String.format("%s {%s}", CreditCard.class.getSimpleName(), number()); } private static int[] toIntArray(String string) { @@ -161,19 +150,11 @@ public class Luhn { private static void businessExample(String cardNumber) { try { System.out.println( - "Trying to create CreditCard object from valid card number: " + - cardNumber - ); + "Trying to create CreditCard object from valid card number: " + cardNumber); CreditCard creditCard = CreditCard.fromString(cardNumber); - System.out.println( - "And business object is successfully created: " + - creditCard + - "\n" - ); + System.out.println("And business object is successfully created: " + creditCard + "\n"); } catch (IllegalArgumentException e) { - System.out.println( - "And fail with exception message: " + e.getMessage() + "\n" - ); + System.out.println("And fail with exception message: " + e.getMessage() + "\n"); } } } diff --git a/src/main/java/com/thealgorithms/others/Mandelbrot.java b/src/main/java/com/thealgorithms/others/Mandelbrot.java index 6ffcc855..8dcaed2b 100644 --- a/src/main/java/com/thealgorithms/others/Mandelbrot.java +++ b/src/main/java/com/thealgorithms/others/Mandelbrot.java @@ -27,23 +27,13 @@ public class Mandelbrot { public static void main(String[] args) { // Test black and white - BufferedImage blackAndWhiteImage = getImage( - 800, - 600, - -0.6, - 0, - 3.2, - 50, - false - ); + BufferedImage blackAndWhiteImage = getImage(800, 600, -0.6, 0, 3.2, 50, false); // Pixel outside the Mandelbrot set should be white. - assert blackAndWhiteImage.getRGB(0, 0) == - new Color(255, 255, 255).getRGB(); + assert blackAndWhiteImage.getRGB(0, 0) == new Color(255, 255, 255).getRGB(); // Pixel inside the Mandelbrot set should be black. - assert blackAndWhiteImage.getRGB(400, 300) == - new Color(0, 0, 0).getRGB(); + assert blackAndWhiteImage.getRGB(400, 300) == new Color(0, 0, 0).getRGB(); // Test color-coding BufferedImage coloredImage = getImage(800, 600, -0.6, 0, 3.2, 50, true); @@ -80,63 +70,38 @@ public class Mandelbrot { * @param useDistanceColorCoding Render in color or black and white. * @return The image of the rendered Mandelbrot set. */ - public static BufferedImage getImage( - int imageWidth, - int imageHeight, - double figureCenterX, - double figureCenterY, - double figureWidth, - int maxStep, - boolean useDistanceColorCoding - ) { + public static BufferedImage getImage(int imageWidth, int imageHeight, double figureCenterX, + double figureCenterY, double figureWidth, int maxStep, boolean useDistanceColorCoding) { if (imageWidth <= 0) { - throw new IllegalArgumentException( - "imageWidth should be greater than zero" - ); + throw new IllegalArgumentException("imageWidth should be greater than zero"); } if (imageHeight <= 0) { - throw new IllegalArgumentException( - "imageHeight should be greater than zero" - ); + throw new IllegalArgumentException("imageHeight should be greater than zero"); } if (maxStep <= 0) { - throw new IllegalArgumentException( - "maxStep should be greater than zero" - ); + throw new IllegalArgumentException("maxStep should be greater than zero"); } - BufferedImage image = new BufferedImage( - imageWidth, - imageHeight, - BufferedImage.TYPE_INT_RGB - ); + BufferedImage image + = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB); double figureHeight = figureWidth / imageWidth * imageHeight; // loop through the image-coordinates for (int imageX = 0; imageX < imageWidth; imageX++) { for (int imageY = 0; imageY < imageHeight; imageY++) { // determine the figure-coordinates based on the image-coordinates - double figureX = - figureCenterX + - ((double) imageX / imageWidth - 0.5) * - figureWidth; - double figureY = - figureCenterY + - ((double) imageY / imageHeight - 0.5) * - figureHeight; + double figureX = figureCenterX + ((double) imageX / imageWidth - 0.5) * figureWidth; + double figureY + = figureCenterY + ((double) imageY / imageHeight - 0.5) * figureHeight; double distance = getDistance(figureX, figureY, maxStep); // color the corresponding pixel based on the selected coloring-function - image.setRGB( - imageX, - imageY, - useDistanceColorCoding - ? colorCodedColorMap(distance).getRGB() - : blackAndWhiteColorMap(distance).getRGB() - ); + image.setRGB(imageX, imageY, + useDistanceColorCoding ? colorCodedColorMap(distance).getRGB() + : blackAndWhiteColorMap(distance).getRGB()); } } @@ -179,18 +144,18 @@ public class Mandelbrot { int t = (int) (val * (1 - (1 - f) * saturation)); switch (hi) { - case 0: - return new Color(v, t, p); - case 1: - return new Color(q, v, p); - case 2: - return new Color(p, v, t); - case 3: - return new Color(p, q, v); - case 4: - return new Color(t, p, v); - default: - return new Color(v, p, q); + case 0: + return new Color(v, t, p); + case 1: + return new Color(q, v, p); + case 2: + return new Color(p, v, t); + case 3: + return new Color(p, q, v); + case 4: + return new Color(t, p, v); + default: + return new Color(v, p, q); } } } @@ -205,11 +170,7 @@ public class Mandelbrot { * @param maxStep Maximum number of steps to check for divergent behavior. * @return The relative distance as the ratio of steps taken to maxStep. */ - private static double getDistance( - double figureX, - double figureY, - int maxStep - ) { + private static double getDistance(double figureX, double figureY, int maxStep) { double a = figureX; double b = figureY; int currentStep = 0; diff --git a/src/main/java/com/thealgorithms/others/MemoryManagementAlgorithms.java b/src/main/java/com/thealgorithms/others/MemoryManagementAlgorithms.java index 576d83a9..a74d4cc8 100644 --- a/src/main/java/com/thealgorithms/others/MemoryManagementAlgorithms.java +++ b/src/main/java/com/thealgorithms/others/MemoryManagementAlgorithms.java @@ -21,18 +21,16 @@ public abstract class MemoryManagementAlgorithms { * @return the ArrayList filled with Integers repressenting the memory * allocation that took place. */ - public abstract ArrayList fitProcess( - int[] sizeOfBlocks, - int[] sizeOfProcesses - ); + public abstract ArrayList fitProcess(int[] sizeOfBlocks, int[] sizeOfProcesses); /** - * A constant value used to indicate that an allocation has not been made. - * This value is used as a sentinel value to represent that no allocation has been made - * when allocating space in an array or other data structure. + * A constant value used to indicate that an allocation has not been made. + * This value is used as a sentinel value to represent that no allocation has been made + * when allocating space in an array or other data structure. * The value is -255 and is marked as protected and final to ensure that it cannot be modified - * from outside the class and that its value remains consistent throughout the program execution. - * + * from outside the class and that its value remains consistent throughout the program + * execution. + * * @author: Ishan Makadia (github.com/intrepid-ishan) * @version: April 06, 2023 */ @@ -44,7 +42,6 @@ public abstract class MemoryManagementAlgorithms { */ class BestFitCPU extends MemoryManagementAlgorithms { - /** * Method to find the maximum valued element of an array filled with * positive integers. @@ -75,13 +72,12 @@ class BestFitCPU extends MemoryManagementAlgorithms { // 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 + 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 - ) { + 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; } @@ -101,18 +97,19 @@ class BestFitCPU extends MemoryManagementAlgorithms { * @return the ArrayList filled with Integers repressenting the memory * allocation that took place. */ - public ArrayList fitProcess( - int[] sizeOfBlocks, - int[] sizeOfProcesses - ) { - // The array list responsible for saving the memory allocations done by the best-fit algorithm + public ArrayList fitProcess(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 + 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 + 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; @@ -136,7 +133,8 @@ class WorstFitCPU extends MemoryManagementAlgorithms { 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. + 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; @@ -161,18 +159,19 @@ class WorstFitCPU extends MemoryManagementAlgorithms { * @return the ArrayList filled with Integers repressenting the memory * allocation that took place. */ - public ArrayList fitProcess( - int[] sizeOfBlocks, - int[] sizeOfProcesses - ) { - // The array list responsible for saving the memory allocations done by the worst-fit algorithm + public ArrayList fitProcess(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 + 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 + 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; @@ -184,7 +183,6 @@ class WorstFitCPU extends MemoryManagementAlgorithms { */ class FirstFitCPU extends MemoryManagementAlgorithms { - /** * Method to find the index of the memory block that is going to fit the * given process based on the first fit algorithm. @@ -216,18 +214,19 @@ class FirstFitCPU extends MemoryManagementAlgorithms { * @return the ArrayList filled with Integers repressenting the memory * allocation that took place. */ - public ArrayList fitProcess( - int[] sizeOfBlocks, - int[] sizeOfProcesses - ) { - // The array list responsible for saving the memory allocations done by the first-fit algorithm + public ArrayList fitProcess(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 + 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 + 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; @@ -239,12 +238,14 @@ class FirstFitCPU extends MemoryManagementAlgorithms { */ class NextFit extends MemoryManagementAlgorithms { - private int counter = 0; // variable that keeps the position of the last registration into the memory + private int counter + = 0; // variable that keeps the position of the last registration into the memory /** * Method to find the index of the memory block that is going to fit the * given process based on the next fit algorithm. In the case of next fit, - * if the search is interrupted in between, the new search is carried out from the last location. + * if the search is interrupted in between, the new search is carried out from the last + * location. * * @param blocks: the array with the available memory blocks. * @param process: the size of the process. @@ -278,18 +279,19 @@ class NextFit extends MemoryManagementAlgorithms { * @return the ArrayList filled with Integers repressenting the memory * allocation that took place. */ - public ArrayList fitProcess( - int[] sizeOfBlocks, - int[] sizeOfProcesses - ) { - // The array list responsible for saving the memory allocations done by the first-fit algorithm + public ArrayList fitProcess(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 = findNextFit(sizeOfBlocks, processSize); // Find the index of the memory block going to be used + int chosenBlockIdx = findNextFit( + 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 + 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; diff --git a/src/main/java/com/thealgorithms/others/MiniMaxAlgorithm.java b/src/main/java/com/thealgorithms/others/MiniMaxAlgorithm.java index f05d1938..539b9dd2 100644 --- a/src/main/java/com/thealgorithms/others/MiniMaxAlgorithm.java +++ b/src/main/java/com/thealgorithms/others/MiniMaxAlgorithm.java @@ -43,11 +43,7 @@ public class MiniMaxAlgorithm { System.out.println(Arrays.toString(miniMaxAlgorith.getScores())); System.out.println( - "The best score for " + - (isMaximizer ? "Maximizer" : "Minimizer") + - " is " + - bestScore - ); + "The best score for " + (isMaximizer ? "Maximizer" : "Minimizer") + " is " + bestScore); } /** @@ -59,12 +55,7 @@ public class MiniMaxAlgorithm { * @param verbose True to show each players choices. * @return The optimal score for the player that made the first move. */ - public int miniMax( - int depth, - boolean isMaximizer, - int index, - boolean verbose - ) { + public int miniMax(int depth, boolean isMaximizer, int index, boolean verbose) { int bestScore, score1, score2; if (depth == height) { // Leaf node reached. @@ -88,13 +79,8 @@ public class MiniMaxAlgorithm { // (1 x 2) = 2; ((1 x 2) + 1) = 3 // (2 x 2) = 4; ((2 x 2) + 1) = 5 ... if (verbose) { - System.out.printf( - "From %02d and %02d, %s chooses %02d%n", - score1, - score2, - (isMaximizer ? "Maximizer" : "Minimizer"), - bestScore - ); + System.out.printf("From %02d and %02d, %s chooses %02d%n", score1, score2, + (isMaximizer ? "Maximizer" : "Minimizer"), bestScore); } return bestScore; diff --git a/src/main/java/com/thealgorithms/others/PageRank.java b/src/main/java/com/thealgorithms/others/PageRank.java index b5a7422a..6cd5a08d 100644 --- a/src/main/java/com/thealgorithms/others/PageRank.java +++ b/src/main/java/com/thealgorithms/others/PageRank.java @@ -11,8 +11,7 @@ class PageRank { nodes = in.nextInt(); PageRank p = new PageRank(); System.out.println( - "Enter the Adjacency Matrix with 1->PATH & 0->NO PATH Between two WebPages: " - ); + "Enter the Adjacency Matrix with 1->PATH & 0->NO PATH Between two WebPages: "); for (i = 1; i <= nodes; i++) { for (j = 1; j <= nodes; j++) { p.path[i][j] = in.nextInt(); @@ -37,13 +36,8 @@ class PageRank { int k = 1; // For Traversing int ITERATION_STEP = 1; InitialPageRank = 1 / totalNodes; - System.out.printf( - " Total Number of Nodes :" + - totalNodes + - "\t Initial PageRank of All Nodes :" + - InitialPageRank + - "\n" - ); + System.out.printf(" Total Number of Nodes :" + totalNodes + + "\t Initial PageRank of All Nodes :" + InitialPageRank + "\n"); // 0th ITERATION _ OR _ INITIALIZATION PHASE // for (k = 1; k <= totalNodes; k++) { @@ -52,9 +46,7 @@ class PageRank { System.out.print("\n Initial PageRank Values , 0th Step \n"); for (k = 1; k <= totalNodes; k++) { - System.out.printf( - " Page Rank of " + k + " is :\t" + this.pagerank[k] + "\n" - ); + System.out.printf(" Page Rank of " + k + " is :\t" + this.pagerank[k] + "\n"); } while (ITERATION_STEP <= 2) { // Iterations @@ -64,21 +56,13 @@ class PageRank { this.pagerank[k] = 0; } - for ( - InternalNodeNumber = 1; - InternalNodeNumber <= totalNodes; - InternalNodeNumber++ - ) { - for ( - ExternalNodeNumber = 1; - ExternalNodeNumber <= totalNodes; - ExternalNodeNumber++ - ) { - if ( - this.path[ExternalNodeNumber][InternalNodeNumber] == 1 - ) { + for (InternalNodeNumber = 1; InternalNodeNumber <= totalNodes; InternalNodeNumber++) { + for (ExternalNodeNumber = 1; ExternalNodeNumber <= totalNodes; + ExternalNodeNumber++) { + if (this.path[ExternalNodeNumber][InternalNodeNumber] == 1) { k = 1; - OutgoingLinks = 0; // Count the Number of Outgoing Links for each ExternalNodeNumber + OutgoingLinks + = 0; // Count the Number of Outgoing Links for each ExternalNodeNumber while (k <= totalNodes) { if (this.path[ExternalNodeNumber][k] == 1) { OutgoingLinks = OutgoingLinks + 1; // Counter for Outgoing Links @@ -86,21 +70,14 @@ class PageRank { k = k + 1; } // Calculate PageRank - this.pagerank[InternalNodeNumber] += - TempPageRank[ExternalNodeNumber] * - (1 / OutgoingLinks); + this.pagerank[InternalNodeNumber] + += TempPageRank[ExternalNodeNumber] * (1 / OutgoingLinks); } } System.out.printf("\n After " + ITERATION_STEP + "th Step \n"); for (k = 1; k <= totalNodes; k++) { - System.out.printf( - " Page Rank of " + - k + - " is :\t" + - this.pagerank[k] + - "\n" - ); + System.out.printf(" Page Rank of " + k + " is :\t" + this.pagerank[k] + "\n"); } ITERATION_STEP = ITERATION_STEP + 1; @@ -108,16 +85,13 @@ class PageRank { // Add the Damping Factor to PageRank for (k = 1; k <= totalNodes; k++) { - this.pagerank[k] = - (1 - DampingFactor) + DampingFactor * this.pagerank[k]; + this.pagerank[k] = (1 - DampingFactor) + DampingFactor * this.pagerank[k]; } // Display PageRank System.out.print("\n Final Page Rank : \n"); for (k = 1; k <= totalNodes; k++) { - System.out.printf( - " Page Rank of " + k + " is :\t" + this.pagerank[k] + "\n" - ); + System.out.printf(" Page Rank of " + k + " is :\t" + this.pagerank[k] + "\n"); } } } diff --git a/src/main/java/com/thealgorithms/others/PasswordGen.java b/src/main/java/com/thealgorithms/others/PasswordGen.java index 38a20841..c079d1cb 100644 --- a/src/main/java/com/thealgorithms/others/PasswordGen.java +++ b/src/main/java/com/thealgorithms/others/PasswordGen.java @@ -38,11 +38,7 @@ class PasswordGen { 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 - ) { + for (int i = random.nextInt(max_length - min_length) + min_length; i > 0; --i) { password.append(letters.get(random.nextInt(letters.size()))); } diff --git a/src/main/java/com/thealgorithms/others/PerlinNoise.java b/src/main/java/com/thealgorithms/others/PerlinNoise.java index c3591cf0..a979c514 100644 --- a/src/main/java/com/thealgorithms/others/PerlinNoise.java +++ b/src/main/java/com/thealgorithms/others/PerlinNoise.java @@ -18,12 +18,7 @@ public class PerlinNoise { * @return float array containing calculated "Perlin-Noise" values */ static float[][] generatePerlinNoise( - int width, - int height, - int octaveCount, - float persistence, - long seed - ) { + 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][][]; @@ -38,8 +33,7 @@ public class PerlinNoise { // calculate octaves with different roughness for (int octave = 0; octave < octaveCount; octave++) { - noiseLayers[octave] = - generatePerlinNoiseLayer(base, width, height, octave); + noiseLayers[octave] = generatePerlinNoiseLayer(base, width, height, octave); } float amplitude = 1f; @@ -76,12 +70,7 @@ public class PerlinNoise { * @param octave current layer * @return float array containing calculated "Perlin-Noise-Layer" values */ - static float[][] generatePerlinNoiseLayer( - float[][] base, - int width, - int height, - int octave - ) { + static float[][] generatePerlinNoiseLayer(float[][] base, int width, int height, int octave) { float[][] perlinNoiseLayer = new float[width][height]; // calculate period (wavelength) for different shapes @@ -101,22 +90,13 @@ public class PerlinNoise { float verticalBlend = (y - y0) * frequency; // blend top corners - float top = interpolate( - base[x0][y0], - base[x1][y0], - horizintalBlend - ); + float top = interpolate(base[x0][y0], base[x1][y0], horizintalBlend); // blend bottom corners - float bottom = interpolate( - base[x0][y1], - base[x1][y1], - horizintalBlend - ); + 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); + perlinNoiseLayer[x][y] = interpolate(top, bottom, verticalBlend); } } @@ -163,8 +143,7 @@ public class PerlinNoise { System.out.println("Charset (String): "); charset = in.next(); - perlinNoise = - generatePerlinNoise(width, height, octaveCount, persistence, seed); + perlinNoise = generatePerlinNoise(width, height, octaveCount, persistence, seed); final char[] chars = charset.toCharArray(); final int length = chars.length; final float step = 1f / length; diff --git a/src/main/java/com/thealgorithms/others/PrintAMatrixInSpiralOrder.java b/src/main/java/com/thealgorithms/others/PrintAMatrixInSpiralOrder.java index d2065085..ddc37a91 100644 --- a/src/main/java/com/thealgorithms/others/PrintAMatrixInSpiralOrder.java +++ b/src/main/java/com/thealgorithms/others/PrintAMatrixInSpiralOrder.java @@ -47,7 +47,6 @@ public class PrintAMatrixInSpiralOrder { } row--; - } // print columns from first except printed elements @@ -57,9 +56,7 @@ public class PrintAMatrixInSpiralOrder { } c++; } - } return result; } - } diff --git a/src/main/java/com/thealgorithms/others/QueueUsingTwoStacks.java b/src/main/java/com/thealgorithms/others/QueueUsingTwoStacks.java index 4bd3fa69..6c5a0b7b 100644 --- a/src/main/java/com/thealgorithms/others/QueueUsingTwoStacks.java +++ b/src/main/java/com/thealgorithms/others/QueueUsingTwoStacks.java @@ -142,8 +142,7 @@ public class QueueUsingTwoStacks { System.out.println(myQueue.remove()); // Will print 1 System.out.println( - (myQueue.isInStackEmpty()) ? "null" : myQueue.peekBack() - ); // Will print NULL + (myQueue.isInStackEmpty()) ? "null" : myQueue.peekBack()); // Will print NULL // instack: [] // outStack: [(top) 2, 3, 4] diff --git a/src/main/java/com/thealgorithms/others/RabinKarp.java b/src/main/java/com/thealgorithms/others/RabinKarp.java index 3c123ace..8757f03b 100644 --- a/src/main/java/com/thealgorithms/others/RabinKarp.java +++ b/src/main/java/com/thealgorithms/others/RabinKarp.java @@ -35,21 +35,19 @@ public class RabinKarp { 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 + // 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; } 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 + // 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 < m; j++) { @@ -65,10 +63,9 @@ public class RabinKarp { } } - // if i element == Type.PRIME) - .count(); + int primesCount + = (int) Arrays.stream(numbers).filter(element -> element == Type.PRIME).count(); int[] primes = new int[primesCount]; int primeIndex = 0; diff --git a/src/main/java/com/thealgorithms/others/SkylineProblem.java b/src/main/java/com/thealgorithms/others/SkylineProblem.java index 015e6a26..3314f6d9 100644 --- a/src/main/java/com/thealgorithms/others/SkylineProblem.java +++ b/src/main/java/com/thealgorithms/others/SkylineProblem.java @@ -19,10 +19,7 @@ public class SkylineProblem { String input = sc.next(); String[] data = input.split(","); this.add( - Integer.parseInt(data[0]), - Integer.parseInt(data[1]), - Integer.parseInt(data[2]) - ); + Integer.parseInt(data[0]), Integer.parseInt(data[1]), Integer.parseInt(data[2])); } this.print(this.findSkyline(0, num - 1)); @@ -62,10 +59,7 @@ public class SkylineProblem { return this.mergeSkyline(sky1, sky2); } - public ArrayList mergeSkyline( - ArrayList sky1, - ArrayList sky2 - ) { + public ArrayList mergeSkyline(ArrayList sky1, ArrayList sky2) { int currentH1 = 0, currentH2 = 0; ArrayList skyline = new ArrayList<>(); int maxH = 0; diff --git a/src/main/java/com/thealgorithms/others/Sudoku.java b/src/main/java/com/thealgorithms/others/Sudoku.java index 574ca983..d2bc1d5c 100644 --- a/src/main/java/com/thealgorithms/others/Sudoku.java +++ b/src/main/java/com/thealgorithms/others/Sudoku.java @@ -102,15 +102,15 @@ class Sudoku { // Driver Code public static void main(String[] args) { int[][] board = new int[][] { - { 3, 0, 6, 5, 0, 8, 4, 0, 0 }, - { 5, 2, 0, 0, 0, 0, 0, 0, 0 }, - { 0, 8, 7, 0, 0, 0, 0, 3, 1 }, - { 0, 0, 3, 0, 1, 0, 0, 8, 0 }, - { 9, 0, 0, 8, 6, 3, 0, 0, 5 }, - { 0, 5, 0, 0, 9, 0, 6, 0, 0 }, - { 1, 3, 0, 0, 0, 0, 2, 5, 0 }, - { 0, 0, 0, 0, 0, 0, 0, 7, 4 }, - { 0, 0, 5, 2, 0, 6, 3, 0, 0 }, + {3, 0, 6, 5, 0, 8, 4, 0, 0}, + {5, 2, 0, 0, 0, 0, 0, 0, 0}, + {0, 8, 7, 0, 0, 0, 0, 3, 1}, + {0, 0, 3, 0, 1, 0, 0, 8, 0}, + {9, 0, 0, 8, 6, 3, 0, 0, 5}, + {0, 5, 0, 0, 9, 0, 6, 0, 0}, + {1, 3, 0, 0, 0, 0, 2, 5, 0}, + {0, 0, 0, 0, 0, 0, 0, 7, 4}, + {0, 0, 5, 2, 0, 6, 3, 0, 0}, }; int N = board.length; diff --git a/src/main/java/com/thealgorithms/others/TopKWords.java b/src/main/java/com/thealgorithms/others/TopKWords.java index 71fd4f91..6473c173 100644 --- a/src/main/java/com/thealgorithms/others/TopKWords.java +++ b/src/main/java/com/thealgorithms/others/TopKWords.java @@ -64,12 +64,11 @@ public class TopKWords { 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} + 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() - ); + List> list = new ArrayList<>(dictionary.entrySet()); // sort by lambda valueComparator list.sort(Comparator.comparing(m -> m.getValue())); diff --git a/src/main/java/com/thealgorithms/others/TowerOfHanoi.java b/src/main/java/com/thealgorithms/others/TowerOfHanoi.java index 0c1889af..c0fb4d75 100644 --- a/src/main/java/com/thealgorithms/others/TowerOfHanoi.java +++ b/src/main/java/com/thealgorithms/others/TowerOfHanoi.java @@ -4,20 +4,15 @@ import java.util.Scanner; class TowerOfHanoi { - public static void shift( - int n, - String startPole, - String intermediatePole, - String 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 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 function is called in recursion for swapping the n-1 disc from the + // intermediatePole to the endPole shift(n - 1, intermediatePole, startPole, endPole); } } diff --git a/src/main/java/com/thealgorithms/others/Verhoeff.java b/src/main/java/com/thealgorithms/others/Verhoeff.java index e6088108..a783aceb 100644 --- a/src/main/java/com/thealgorithms/others/Verhoeff.java +++ b/src/main/java/com/thealgorithms/others/Verhoeff.java @@ -35,16 +35,16 @@ public class Verhoeff { * Dihedral group */ private static final byte[][] MULTIPLICATION_TABLE = { - { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, - { 1, 2, 3, 4, 0, 6, 7, 8, 9, 5 }, - { 2, 3, 4, 0, 1, 7, 8, 9, 5, 6 }, - { 3, 4, 0, 1, 2, 8, 9, 5, 6, 7 }, - { 4, 0, 1, 2, 3, 9, 5, 6, 7, 8 }, - { 5, 9, 8, 7, 6, 0, 4, 3, 2, 1 }, - { 6, 5, 9, 8, 7, 1, 0, 4, 3, 2 }, - { 7, 6, 5, 9, 8, 2, 1, 0, 4, 3 }, - { 8, 7, 6, 5, 9, 3, 2, 1, 0, 4 }, - { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }, + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, + {1, 2, 3, 4, 0, 6, 7, 8, 9, 5}, + {2, 3, 4, 0, 1, 7, 8, 9, 5, 6}, + {3, 4, 0, 1, 2, 8, 9, 5, 6, 7}, + {4, 0, 1, 2, 3, 9, 5, 6, 7, 8}, + {5, 9, 8, 7, 6, 0, 4, 3, 2, 1}, + {6, 5, 9, 8, 7, 1, 0, 4, 3, 2}, + {7, 6, 5, 9, 8, 2, 1, 0, 4, 3}, + {8, 7, 6, 5, 9, 3, 2, 1, 0, 4}, + {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}, }; /** @@ -71,14 +71,14 @@ public class Verhoeff { * {@code p(i+j,n) = p(i, p(j,n))}. */ private static final byte[][] PERMUTATION_TABLE = { - { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, - { 1, 5, 7, 6, 2, 8, 3, 0, 9, 4 }, - { 5, 8, 0, 3, 7, 9, 6, 1, 4, 2 }, - { 8, 9, 1, 6, 0, 4, 3, 5, 2, 7 }, - { 9, 4, 5, 3, 1, 2, 6, 8, 7, 0 }, - { 4, 2, 8, 6, 5, 7, 3, 9, 0, 1 }, - { 2, 7, 9, 3, 8, 0, 6, 4, 1, 5 }, - { 7, 0, 4, 6, 9, 1, 3, 2, 5, 8 }, + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, + {1, 5, 7, 6, 2, 8, 3, 0, 9, 4}, + {5, 8, 0, 3, 7, 9, 6, 1, 4, 2}, + {8, 9, 1, 6, 0, 4, 3, 5, 2, 7}, + {9, 4, 5, 3, 1, 2, 6, 8, 7, 0}, + {4, 2, 8, 6, 5, 7, 3, 9, 0, 1}, + {2, 7, 9, 3, 8, 0, 6, 4, 1, 5}, + {7, 0, 4, 6, 9, 1, 3, 2, 5, 8}, }; /** @@ -147,29 +147,20 @@ public class Verhoeff { } private static void checkAndPrint(String input) { - String validationResult = Verhoeff.verhoeffCheck(input) - ? "valid" - : "not valid"; + String validationResult = Verhoeff.verhoeffCheck(input) ? "valid" : "not valid"; System.out.println("Input '" + input + "' is " + validationResult); } private static void generateAndPrint(String input) { String result = addVerhoeffChecksum(input); System.out.println( - "Generate and add checksum to initial value '" + - input + - "'. Result: '" + - result + - "'" - ); + "Generate and add checksum to initial value '" + input + "'. Result: '" + result + "'"); } private static void checkInput(String input) { Objects.requireNonNull(input); if (!input.matches("\\d+")) { - throw new IllegalArgumentException( - "Input '" + input + "' contains not only digits" - ); + throw new IllegalArgumentException("Input '" + input + "' contains not only digits"); } } diff --git a/src/main/java/com/thealgorithms/others/cn/HammingDistance.java b/src/main/java/com/thealgorithms/others/cn/HammingDistance.java index 418c1c70..8a73e5ac 100644 --- a/src/main/java/com/thealgorithms/others/cn/HammingDistance.java +++ b/src/main/java/com/thealgorithms/others/cn/HammingDistance.java @@ -5,14 +5,9 @@ import java.util.List; public class HammingDistance { - public int getHammingDistanceBetweenBits( - String senderBits, - String receiverBits - ) { + public int getHammingDistanceBetweenBits(String senderBits, String receiverBits) { if (senderBits.length() != receiverBits.length()) { - throw new IllegalArgumentException( - "Sender and Receiver bits should be same" - ); + throw new IllegalArgumentException("Sender and Receiver bits should be same"); } List byteArray = new ArrayList<>(); diff --git a/src/main/java/com/thealgorithms/others/countSetBits.java b/src/main/java/com/thealgorithms/others/countSetBits.java index fe71e1d7..04e0d6f6 100644 --- a/src/main/java/com/thealgorithms/others/countSetBits.java +++ b/src/main/java/com/thealgorithms/others/countSetBits.java @@ -2,37 +2,41 @@ package com.thealgorithms.others; public class countSetBits { - /** - * The below algorithm is called as Brian Kernighan's algorithm - * We can use Brian Kernighan’s algorithm to improve the above naive algorithm’s performance. The idea is to only consider the set bits of an integer by turning off its rightmost set bit (after counting it), so the next iteration of the loop considers the next rightmost bit. + /** + * The below algorithm is called as Brian Kernighan's algorithm + * We can use Brian Kernighan’s algorithm to improve the above naive algorithm’s performance. + The idea is to only consider the set bits of an integer by turning off its rightmost set bit + (after counting it), so the next iteration of the loop considers the next rightmost bit. - The expression n & (n-1) can be used to turn off the rightmost set bit of a number n. This works as the expression n-1 flips all the bits after the rightmost set bit of n, including the rightmost set bit itself. Therefore, n & (n-1) results in the last bit flipped of n. + The expression n & (n-1) can be used to turn off the rightmost set bit of a number n. This + works as the expression n-1 flips all the bits after the rightmost set bit of n, including the + rightmost set bit itself. Therefore, n & (n-1) results in the last bit flipped of n. For example, consider number 52, which is 00110100 in binary, and has a total 3 bits set. 1st iteration of the loop: n = 52 - + 00110100 & (n) 00110011 (n-1) ~~~~~~~~ 00110000 - - + + 2nd iteration of the loop: n = 48 - + 00110000 & (n) 00101111 (n-1) ~~~~~~~~ 00100000 - - + + 3rd iteration of the loop: n = 32 - + 00100000 & (n) 00011111 (n-1) ~~~~~~~~ 00000000 (n = 0) - + * @param num takes Long number whose number of set bit is to be found * @return the count of set bits in the binary equivalent */ diff --git a/src/main/java/com/thealgorithms/scheduling/FCFSScheduling.java b/src/main/java/com/thealgorithms/scheduling/FCFSScheduling.java index b1c3411b..f57ee5c6 100644 --- a/src/main/java/com/thealgorithms/scheduling/FCFSScheduling.java +++ b/src/main/java/com/thealgorithms/scheduling/FCFSScheduling.java @@ -1,11 +1,11 @@ package com.thealgorithms.scheduling; import com.thealgorithms.devutils.entities.ProcessDetails; - import java.util.List; /** - * Non-pre-emptive First Come First Serve scheduling. This can be understood here - https://www.scaler.com/topics/first-come-first-serve/ + * Non-pre-emptive First Come First Serve scheduling. This can be understood here - + * https://www.scaler.com/topics/first-come-first-serve/ */ public class FCFSScheduling { @@ -23,25 +23,27 @@ public class FCFSScheduling { private void evaluateWaitingTime() { int processesNumber = processes.size(); - if(processesNumber == 0) { + if (processesNumber == 0) { return; } int waitingTime = 0; int burstTime = processes.get(0).getBurstTime(); - processes.get(0).setWaitingTime(waitingTime); // for the first process, waiting time will be 0. + processes.get(0).setWaitingTime( + waitingTime); // for the first process, waiting time will be 0. - for(int i=1; i 0){ + if (remainingBurstTime[index] - quantumTime > 0) { remainingBurstTime[index] -= quantumTime; currentTime += quantumTime; } else { currentTime += remainingBurstTime[index]; - processes.get(index).setTurnAroundTimeTime(currentTime - processes.get(index).getArrivalTime()); + processes.get(index).setTurnAroundTimeTime( + currentTime - processes.get(index).getArrivalTime()); completed++; - remainingBurstTime[index]=0; + remainingBurstTime[index] = 0; } - // If some process has arrived when this process was executing, insert them into the queue. - for (int i=1; i < processesNumber; i++){ - if(remainingBurstTime[i] > 0 && processes.get(i).getArrivalTime() <= currentTime && mark[i] == 0){ - mark[i]=1; + // If some process has arrived when this process was executing, insert them into the + // queue. + for (int i = 1; i < processesNumber; i++) { + if (remainingBurstTime[i] > 0 && processes.get(i).getArrivalTime() <= currentTime + && mark[i] == 0) { + mark[i] = 1; queue.add(i); } } - // If the current process has burst time remaining, push the process into the queue again. - if(remainingBurstTime[index] > 0) queue.add(index); + // If the current process has burst time remaining, push the process into the queue + // again. + if (remainingBurstTime[index] > 0) queue.add(index); // If the queue is empty, pick the first process from the list that is not completed. - if(queue.isEmpty()){ - for (int i=1; i 0){ + if (queue.isEmpty()) { + for (int i = 1; i < processesNumber; i++) { + if (remainingBurstTime[i] > 0) { mark[i] = 1; queue.add(i); break; @@ -94,6 +98,7 @@ public class RRScheduling { private void evaluateWaitingTime() { for (int i = 0; i < processes.size(); i++) - processes.get(i).setWaitingTime(processes.get(i).getTurnAroundTimeTime() - processes.get(i).getBurstTime()); + processes.get(i).setWaitingTime( + processes.get(i).getTurnAroundTimeTime() - processes.get(i).getBurstTime()); } } diff --git a/src/main/java/com/thealgorithms/scheduling/SJFScheduling.java b/src/main/java/com/thealgorithms/scheduling/SJFScheduling.java index bf3a9f00..5eb8879a 100644 --- a/src/main/java/com/thealgorithms/scheduling/SJFScheduling.java +++ b/src/main/java/com/thealgorithms/scheduling/SJFScheduling.java @@ -1,17 +1,17 @@ package com.thealgorithms.scheduling; import com.thealgorithms.devutils.entities.ProcessDetails; - import java.util.ArrayList; /** - * Implementation of Shortest Job First Algorithm: The algorithm allows the waiting process with the minimal burst time to be executed first. - * see more here: https://www.guru99.com/shortest-job-first-sjf-scheduling.html + * Implementation of Shortest Job First Algorithm: The algorithm allows the waiting process with the + * minimal burst time to be executed first. see more here: + * https://www.guru99.com/shortest-job-first-sjf-scheduling.html */ public class SJFScheduling { protected ArrayList processes; - protected ArrayListschedule ; + protected ArrayList schedule; /** * a simple constructor @@ -20,85 +20,79 @@ public class SJFScheduling { */ SJFScheduling(final ArrayList processes) { this.processes = processes; - schedule=new ArrayList<>(); + schedule = new ArrayList<>(); sortByArrivalTime(); } -protected void sortByArrivalTime() { - int size=processes.size(),i,j; + protected void sortByArrivalTime() { + int size = processes.size(), i, j; ProcessDetails temp; - for(i=0;iprocesses.get(j+1).getArrivalTime()) - { - temp=processes.get(j); - processes.set(j,processes.get(j+1)); - processes.set(j+1,temp); + for (i = 0; i < size; i++) { + for (j = i + 1; j < size - 1; j++) { + if (processes.get(j).getArrivalTime() > processes.get(j + 1).getArrivalTime()) { + temp = processes.get(j); + processes.set(j, processes.get(j + 1)); + processes.set(j + 1, temp); } } } - -} + } /** * this functions returns the order of the executions */ public void scheduleProcesses() { - ArrayList ready=new ArrayList<>(); + ArrayList ready = new ArrayList<>(); - int size = processes.size(),runtime,time=0; - int executed=0,j,k=0; + int size = processes.size(), runtime, time = 0; + int executed = 0, j, k = 0; ProcessDetails running; if (size == 0) { return; } - - while(executed ReadyProcesses) { - if (ReadyProcesses.isEmpty()){ + if (ReadyProcesses.isEmpty()) { return null; } - int i,size = ReadyProcesses.size(); + int i, size = ReadyProcesses.size(); int minBurstTime = ReadyProcesses.get(0).getBurstTime(), temp, positionOfShortestJob = 0; - for (i = 1; i < size; i++) { temp = ReadyProcesses.get(i).getBurstTime(); - if (minBurstTime > temp ) { + if (minBurstTime > temp) { minBurstTime = temp; positionOfShortestJob = i; } @@ -106,10 +100,4 @@ protected void sortByArrivalTime() { return ReadyProcesses.get(positionOfShortestJob); } - - - - - - } - +} diff --git a/src/main/java/com/thealgorithms/searches/BinarySearch.java b/src/main/java/com/thealgorithms/searches/BinarySearch.java index 1373748e..42502c36 100644 --- a/src/main/java/com/thealgorithms/searches/BinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/BinarySearch.java @@ -41,12 +41,7 @@ class BinarySearch implements SearchAlgorithm { * @param right The upper bound * @return the location of the key */ - private > int search( - T[] array, - T key, - int left, - int right - ) { + private > int search(T[] array, T key, int left, int right) { if (right < left) { return -1; // this means that the key not found } @@ -71,12 +66,11 @@ class BinarySearch implements SearchAlgorithm { 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)]; @@ -84,15 +78,11 @@ class BinarySearch implements SearchAlgorithm { BinarySearch search = new BinarySearch(); int atIndex = search.find(integers, shouldBeFound); - System.out.printf( - "Should be found: %d. Found %d at index %d. An array length %d%n", - shouldBeFound, - integers[atIndex], - atIndex, - size - ); + System.out.printf("Should be found: %d. Found %d at index %d. An array length %d%n", + shouldBeFound, integers[atIndex], atIndex, size); int toCheck = Arrays.binarySearch(integers, shouldBeFound); - System.out.printf("Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex); + System.out.printf( + "Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex); } } diff --git a/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java b/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java index aae8f58e..e2995747 100644 --- a/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java +++ b/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java @@ -1,11 +1,12 @@ package com.thealgorithms.searches; /* -To apply this method, the provided array must be strictly sorted. In this method, two pointers, one at 0th row -& the other at the last row are taken & the searching is done on the basis of the middle element of the middle column. -If that element is equal to target, its coordinates are returned, else if it is smaller than the target, the rows above -that element are ignored (because the elements above it will also be smaller than the target), else that element is -greater than the target, then the rows below it are ignored. +To apply this method, the provided array must be strictly sorted. In this method, two pointers, one +at 0th row & the other at the last row are taken & the searching is done on the basis of the middle +element of the middle column. If that element is equal to target, its coordinates are returned, else +if it is smaller than the target, the rows above that element are ignored (because the elements +above it will also be smaller than the target), else that element is greater than the target, then +the rows below it are ignored. */ public class BinarySearch2dArray { @@ -19,69 +20,55 @@ public class BinarySearch2dArray { int startRow = 0, endRow = rowCount - 1, midCol = colCount / 2; while (startRow < endRow - 1) { - int midRow = startRow + (endRow - startRow) / 2; //getting the index of middle row + int midRow = startRow + (endRow - startRow) / 2; // getting the index of middle row if (arr[midRow][midCol] == target) { - return new int[] { midRow, midCol }; - } else if (arr[midRow][midCol] < target) startRow = - midRow; else endRow = midRow; + return new int[] {midRow, midCol}; + } else if (arr[midRow][midCol] < target) + startRow = midRow; + else + endRow = midRow; } /* - if the above search fails to find the target element, these conditions will be used to find the target - element, which further uses the binary search algorithm in the places which were left unexplored. + if the above search fails to find the target element, these conditions will be used to + find the target element, which further uses the binary search algorithm in the places + which were left unexplored. */ - if (arr[startRow][midCol] == target) return new int[] { - startRow, - midCol, - }; + if (arr[startRow][midCol] == target) + return new int[] { + startRow, + midCol, + }; - if (arr[endRow][midCol] == target) return new int[] { endRow, midCol }; + if (arr[endRow][midCol] == target) return new int[] {endRow, midCol}; - if (target <= arr[startRow][midCol - 1]) return binarySearch( - arr, - target, - startRow, - 0, - midCol - 1 - ); + if (target <= arr[startRow][midCol - 1]) + return binarySearch(arr, target, startRow, 0, midCol - 1); - if ( - target >= arr[startRow][midCol + 1] && - target <= arr[startRow][colCount - 1] - ) return binarySearch(arr, target, startRow, midCol + 1, colCount - 1); + if (target >= arr[startRow][midCol + 1] && target <= arr[startRow][colCount - 1]) + return binarySearch(arr, target, startRow, midCol + 1, colCount - 1); - if (target <= arr[endRow][midCol - 1]) return binarySearch( - arr, - target, - endRow, - 0, - midCol - 1 - ); else return binarySearch( - arr, - target, - endRow, - midCol + 1, - colCount - 1 - ); + if (target <= arr[endRow][midCol - 1]) + return binarySearch(arr, target, endRow, 0, midCol - 1); + else + return binarySearch(arr, target, endRow, midCol + 1, colCount - 1); } - static int[] binarySearch( - int[][] arr, - int target, - int row, - int colStart, - int colEnd - ) { + static int[] binarySearch(int[][] arr, int target, int row, int colStart, int colEnd) { while (colStart <= colEnd) { int midIndex = colStart + (colEnd - colStart) / 2; - if (arr[row][midIndex] == target) return new int[] { - row, - midIndex, - }; else if (arr[row][midIndex] < target) colStart = - midIndex + 1; else colEnd = midIndex - 1; + if (arr[row][midIndex] == target) + return new int[] { + row, + midIndex, + }; + else if (arr[row][midIndex] < target) + colStart = midIndex + 1; + else + colEnd = midIndex - 1; } - return new int[] { -1, -1 }; + return new int[] {-1, -1}; } } diff --git a/src/main/java/com/thealgorithms/searches/DepthFirstSearch.java b/src/main/java/com/thealgorithms/searches/DepthFirstSearch.java index 94a3d55f..feb7cf29 100644 --- a/src/main/java/com/thealgorithms/searches/DepthFirstSearch.java +++ b/src/main/java/com/thealgorithms/searches/DepthFirstSearch.java @@ -40,8 +40,7 @@ public class DepthFirstSearch { return Optional.of(node); } - return node - .getSubNodes() + return node.getSubNodes() .stream() .map(value -> search(value, name)) .flatMap(Optional::stream) @@ -51,32 +50,22 @@ public class DepthFirstSearch { public static void assertThat(final Object actual, final Object expected) { if (!Objects.equals(actual, expected)) { throw new AssertionError( - String.format("expected=%s but was actual=%s", expected, actual) - ); + String.format("expected=%s but was actual=%s", expected, actual)); } } public static void main(final String[] args) { - final Node rootNode = new Node( - "A", + final Node rootNode = new Node("A", List.of( - new Node( - "B", - List.of( - new Node("D"), - new Node("F", List.of(new Node("H"), new Node("I"))) - ) - ), - new Node("C", List.of(new Node("G"))), - new Node("E") - ) - ); + new Node("B", + List.of(new Node("D"), new Node("F", List.of(new Node("H"), new Node("I"))))), + new Node("C", List.of(new Node("G"))), new Node("E"))); { final String expected = "I"; final Node result = search(rootNode, expected) - .orElseThrow(() -> new AssertionError("Node not found!")); + .orElseThrow(() -> new AssertionError("Node not found!")); assertThat(result.getName(), expected); } @@ -85,7 +74,7 @@ public class DepthFirstSearch { final String expected = "G"; final Node result = search(rootNode, expected) - .orElseThrow(() -> new AssertionError("Node not found!")); + .orElseThrow(() -> new AssertionError("Node not found!")); assertThat(result.getName(), expected); } @@ -94,7 +83,7 @@ public class DepthFirstSearch { final String expected = "E"; final Node result = search(rootNode, expected) - .orElseThrow(() -> new AssertionError("Node not found!")); + .orElseThrow(() -> new AssertionError("Node not found!")); assertThat(result.getName(), expected); } diff --git a/src/main/java/com/thealgorithms/searches/ExponentalSearch.java b/src/main/java/com/thealgorithms/searches/ExponentalSearch.java index 1b9accdc..f3b86849 100644 --- a/src/main/java/com/thealgorithms/searches/ExponentalSearch.java +++ b/src/main/java/com/thealgorithms/searches/ExponentalSearch.java @@ -14,12 +14,11 @@ class ExponentialSearch implements SearchAlgorithm { 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)]; @@ -27,16 +26,12 @@ class ExponentialSearch implements SearchAlgorithm { ExponentialSearch search = new ExponentialSearch(); int atIndex = search.find(integers, shouldBeFound); - System.out.printf( - "Should be found: %d. Found %d at index %d. An array length %d%n", - shouldBeFound, - integers[atIndex], - atIndex, - size - ); + System.out.printf("Should be found: %d. Found %d at index %d. An array length %d%n", + shouldBeFound, integers[atIndex], atIndex, size); int toCheck = Arrays.binarySearch(integers, shouldBeFound); - System.out.printf("Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex); + System.out.printf( + "Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex); } @Override @@ -54,11 +49,6 @@ class ExponentialSearch implements SearchAlgorithm { range = range * 2; } - return Arrays.binarySearch( - array, - range / 2, - Math.min(range, array.length), - key - ); + return Arrays.binarySearch(array, range / 2, Math.min(range, array.length), key); } } diff --git a/src/main/java/com/thealgorithms/searches/FibonacciSearch.java b/src/main/java/com/thealgorithms/searches/FibonacciSearch.java index bd4af6e5..041802cf 100644 --- a/src/main/java/com/thealgorithms/searches/FibonacciSearch.java +++ b/src/main/java/com/thealgorithms/searches/FibonacciSearch.java @@ -59,22 +59,14 @@ public class FibonacciSearch implements SearchAlgorithm { // Driver Program public static void main(String[] args) { - Integer[] integers = { 1, 2, 4, 8, 16, 32, 64, 128, 256, 512 }; + Integer[] integers = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512}; int size = integers.length; Integer shouldBeFound = 128; FibonacciSearch fsearch = new FibonacciSearch(); int atIndex = fsearch.find(integers, shouldBeFound); - System.out.println( - "Should be found: " + - shouldBeFound + - ". Found " + - integers[atIndex] + - " at index " + - atIndex + - ". An array length " + - size - ); + System.out.println("Should be found: " + shouldBeFound + ". Found " + integers[atIndex] + + " at index " + atIndex + ". An array length " + size); } } diff --git a/src/main/java/com/thealgorithms/searches/HowManyTimesRotated.java b/src/main/java/com/thealgorithms/searches/HowManyTimesRotated.java index df2d2e42..dea0db37 100644 --- a/src/main/java/com/thealgorithms/searches/HowManyTimesRotated.java +++ b/src/main/java/com/thealgorithms/searches/HowManyTimesRotated.java @@ -3,8 +3,8 @@ package com.thealgorithms.searches; import java.util.*; /* - Problem Statement: - Given an array, find out how many times it has to been rotated + Problem Statement: + Given an array, find out how many times it has to been rotated from its initial sorted position. Input-Output: Eg. [11,12,15,18,2,5,6,8] @@ -12,14 +12,16 @@ import java.util.*; (One rotation means putting the first element to the end) Note: The array cannot contain duplicates - Logic: + Logic: The position of the minimum element will give the number of times the array has been rotated from its initial sorted position. - Eg. For [2,5,6,8,11,12,15,18], 1 rotation gives [5,6,8,11,12,15,18,2], 2 rotations [6,8,11,12,15,18,2,5] and so on. - Finding the minimum element will take O(N) time but, we can use Binary Search to find the mimimum element, we can reduce the complexity to O(log N). - If we look at the rotated array, to identify the minimum element (say a[i]), we observe that a[i-1]>a[i]a[i]= 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]) - ); + int pos + = start + (((end - start) / (array[end] - array[start])) * (key - array[start])); // Condition of target found if (array[pos] == key) { @@ -58,11 +54,8 @@ class InterpolationSearch { Random r = new Random(); int size = 100; int maxElement = 100000; - int[] integers = IntStream - .generate(() -> r.nextInt(maxElement)) - .limit(size) - .sorted() - .toArray(); + int[] integers + = IntStream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray(); // the element that should be found int shouldBeFound = integers[r.nextInt(size - 1)]; @@ -70,15 +63,11 @@ class InterpolationSearch { InterpolationSearch search = new InterpolationSearch(); int atIndex = search.find(integers, shouldBeFound); - System.out.printf( - "Should be found: %d. Found %d at index %d. An array length %d%n", - shouldBeFound, - integers[atIndex], - atIndex, - size - ); + System.out.printf("Should be found: %d. Found %d at index %d. An array length %d%n", + shouldBeFound, integers[atIndex], atIndex, size); int toCheck = Arrays.binarySearch(integers, shouldBeFound); - System.out.printf("Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex); + System.out.printf( + "Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex); } } diff --git a/src/main/java/com/thealgorithms/searches/IterativeBinarySearch.java b/src/main/java/com/thealgorithms/searches/IterativeBinarySearch.java index cec8703b..7fa6a37c 100644 --- a/src/main/java/com/thealgorithms/searches/IterativeBinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/IterativeBinarySearch.java @@ -58,11 +58,10 @@ public final class IterativeBinarySearch implements SearchAlgorithm { Random r = new Random(); int size = 100; int maxElement = 100000; - Integer[] integers = Stream - .generate(() -> r.nextInt(maxElement)) - .limit(size) - .sorted() - .toArray(Integer[]::new); + 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)]; @@ -70,15 +69,11 @@ public final class IterativeBinarySearch implements SearchAlgorithm { IterativeBinarySearch search = new IterativeBinarySearch(); int atIndex = search.find(integers, shouldBeFound); - System.out.printf( - "Should be found: %d. Found %d at index %d. An array length %d%n", - shouldBeFound, - integers[atIndex], - atIndex, - size - ); + System.out.printf("Should be found: %d. Found %d at index %d. An array length %d%n", + shouldBeFound, integers[atIndex], atIndex, size); int toCheck = Arrays.binarySearch(integers, shouldBeFound); - System.out.printf("Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex); + System.out.printf( + "Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex); } } diff --git a/src/main/java/com/thealgorithms/searches/IterativeTernarySearch.java b/src/main/java/com/thealgorithms/searches/IterativeTernarySearch.java index 93305698..efff17c9 100644 --- a/src/main/java/com/thealgorithms/searches/IterativeTernarySearch.java +++ b/src/main/java/com/thealgorithms/searches/IterativeTernarySearch.java @@ -56,11 +56,10 @@ public class IterativeTernarySearch implements SearchAlgorithm { Random r = new Random(); int size = 100; int maxElement = 100000; - Integer[] integers = Stream - .generate(() -> r.nextInt(maxElement)) - .limit(size) - .sorted() - .toArray(Integer[]::new); + 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)]; @@ -68,15 +67,11 @@ public class IterativeTernarySearch implements SearchAlgorithm { IterativeTernarySearch search = new IterativeTernarySearch(); int atIndex = search.find(integers, shouldBeFound); - System.out.printf( - "Should be found: %d. Found %d at index %d. An array length %d%n", - shouldBeFound, - integers[atIndex], - atIndex, - size - ); + System.out.printf("Should be found: %d. Found %d at index %d. An array length %d%n", + shouldBeFound, integers[atIndex], atIndex, size); int toCheck = Arrays.binarySearch(integers, shouldBeFound); - System.out.printf("Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex); + System.out.printf( + "Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex); } } diff --git a/src/main/java/com/thealgorithms/searches/JumpSearch.java b/src/main/java/com/thealgorithms/searches/JumpSearch.java index 36bbb393..f499cf80 100644 --- a/src/main/java/com/thealgorithms/searches/JumpSearch.java +++ b/src/main/java/com/thealgorithms/searches/JumpSearch.java @@ -6,7 +6,7 @@ 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 }; + 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; } diff --git a/src/main/java/com/thealgorithms/searches/KMPSearch.java b/src/main/java/com/thealgorithms/searches/KMPSearch.java index c9b647fd..dd728d81 100644 --- a/src/main/java/com/thealgorithms/searches/KMPSearch.java +++ b/src/main/java/com/thealgorithms/searches/KMPSearch.java @@ -22,7 +22,8 @@ class KMPSearch { i++; } if (j == M) { - System.out.println("Found pattern " + "at index " + (i - j)); + System.out.println("Found pattern " + + "at index " + (i - j)); int index = (i - j); j = lps[j - 1]; return index; @@ -31,7 +32,10 @@ class KMPSearch { else if (i < N && pat.charAt(j) != txt.charAt(i)) { // Do not match lps[0..lps[j-1]] characters, // they will match anyway - if (j != 0) j = lps[j - 1]; else i = i + 1; + if (j != 0) + j = lps[j - 1]; + else + i = i + 1; } } System.out.println("No pattern found"); diff --git a/src/main/java/com/thealgorithms/searches/LinearSearch.java b/src/main/java/com/thealgorithms/searches/LinearSearch.java index 350cfc6e..94939518 100644 --- a/src/main/java/com/thealgorithms/searches/LinearSearch.java +++ b/src/main/java/com/thealgorithms/searches/LinearSearch.java @@ -42,10 +42,8 @@ public class LinearSearch implements SearchAlgorithm { Random r = new Random(); int size = 200; int maxElement = 100; - Integer[] integers = Stream - .generate(() -> r.nextInt(maxElement)) - .limit(size) - .toArray(Integer[]::new); + 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)]; @@ -53,12 +51,7 @@ public class LinearSearch implements SearchAlgorithm { LinearSearch search = new LinearSearch(); int atIndex = search.find(integers, shouldBeFound); - System.out.printf( - "Should be found: %d. Found %d at index %d. An array length %d%n", - shouldBeFound, - integers[atIndex], - atIndex, - size - ); + System.out.printf("Should be found: %d. Found %d at index %d. An array length %d%n", + shouldBeFound, integers[atIndex], atIndex, size); } } diff --git a/src/main/java/com/thealgorithms/searches/LinearSearchThread.java b/src/main/java/com/thealgorithms/searches/LinearSearchThread.java index 98638ef4..c277b68f 100644 --- a/src/main/java/com/thealgorithms/searches/LinearSearchThread.java +++ b/src/main/java/com/thealgorithms/searches/LinearSearchThread.java @@ -29,9 +29,9 @@ public class LinearSearchThread { t1.join(); t2.join(); t3.join(); - } catch (InterruptedException e) {} - boolean found = - t.getResult() || t1.getResult() || t2.getResult() || t3.getResult(); + } catch (InterruptedException e) { + } + boolean found = t.getResult() || t1.getResult() || t2.getResult() || t3.getResult(); System.out.println("Found = " + found); } } diff --git a/src/main/java/com/thealgorithms/searches/LowerBound.java b/src/main/java/com/thealgorithms/searches/LowerBound.java index d800a6cc..be0f1131 100644 --- a/src/main/java/com/thealgorithms/searches/LowerBound.java +++ b/src/main/java/com/thealgorithms/searches/LowerBound.java @@ -33,12 +33,11 @@ class LowerBound implements SearchAlgorithm { 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 for which the lower bound is to be found int val = integers[r.nextInt(size - 1)] + 1; @@ -46,16 +45,12 @@ class LowerBound implements SearchAlgorithm { LowerBound search = new LowerBound(); int atIndex = search.find(integers, val); - System.out.printf( - "Val: %d. Lower Bound Found %d at index %d. An array length %d%n", - val, - integers[atIndex], - atIndex, - size - ); + System.out.printf("Val: %d. Lower Bound Found %d at index %d. An array length %d%n", val, + integers[atIndex], atIndex, size); boolean toCheck = integers[atIndex] >= val || integers[size - 1] < val; - System.out.printf("Lower Bound found at an index: %d. Is greater or max element: %b%n", atIndex, toCheck); + System.out.printf( + "Lower Bound found at an index: %d. Is greater or max element: %b%n", atIndex, toCheck); } /** @@ -78,12 +73,7 @@ class LowerBound implements SearchAlgorithm { * @param right The upper bound * @return the location of the key */ - private > int search( - T[] array, - T key, - int left, - int right - ) { + private > int search(T[] array, T key, int left, int right) { if (right <= left) { return left; } diff --git a/src/main/java/com/thealgorithms/searches/MonteCarloTreeSearch.java b/src/main/java/com/thealgorithms/searches/MonteCarloTreeSearch.java index 88c097b0..4ba8110c 100644 --- a/src/main/java/com/thealgorithms/searches/MonteCarloTreeSearch.java +++ b/src/main/java/com/thealgorithms/searches/MonteCarloTreeSearch.java @@ -23,7 +23,8 @@ public class MonteCarloTreeSearch { int score; int visitCount; - public Node() {} + public Node() { + } public Node(Node parent, boolean isPlayersTurn) { this.parent = parent; @@ -78,9 +79,7 @@ public class MonteCarloTreeSearch { winnerNode = getWinnerNode(rootNode); printScores(rootNode); System.out.format( - "\nThe optimal node is: %02d\n", - rootNode.childNodes.indexOf(winnerNode) + 1 - ); + "\nThe optimal node is: %02d\n", rootNode.childNodes.indexOf(winnerNode) + 1); return winnerNode; } @@ -120,13 +119,10 @@ public class MonteCarloTreeSearch { break; } - uctTemp = - ((double) childNode.score / childNode.visitCount) + - 1.41 * - Math.sqrt( - Math.log(promisingNode.visitCount) / - (double) childNode.visitCount - ); + uctTemp = ((double) childNode.score / childNode.visitCount) + + 1.41 + * Math.sqrt( + Math.log(promisingNode.visitCount) / (double) childNode.visitCount); if (uctTemp > uctIndex) { uctIndex = uctTemp; @@ -165,10 +161,8 @@ public class MonteCarloTreeSearch { tempNode.visitCount++; // Add wining scores to bouth player and opponent depending on the turn. - if ( - (tempNode.isPlayersTurn && isPlayerWinner) || - (!tempNode.isPlayersTurn && !isPlayerWinner) - ) { + if ((tempNode.isPlayersTurn && isPlayerWinner) + || (!tempNode.isPlayersTurn && !isPlayerWinner)) { tempNode.score += WIN_SCORE; } @@ -177,22 +171,15 @@ public class MonteCarloTreeSearch { } public Node getWinnerNode(Node rootNode) { - return Collections.max( - rootNode.childNodes, - Comparator.comparing(c -> c.score) - ); + return Collections.max(rootNode.childNodes, Comparator.comparing(c -> c.score)); } public void printScores(Node rootNode) { System.out.println("N.\tScore\t\tVisits"); for (int i = 0; i < rootNode.childNodes.size(); i++) { - System.out.printf( - "%02d\t%d\t\t%d%n", - i + 1, - rootNode.childNodes.get(i).score, - rootNode.childNodes.get(i).visitCount - ); + System.out.printf("%02d\t%d\t\t%d%n", i + 1, rootNode.childNodes.get(i).score, + rootNode.childNodes.get(i).visitCount); } } } diff --git a/src/main/java/com/thealgorithms/searches/OrderAgnosticBinarySearch.java b/src/main/java/com/thealgorithms/searches/OrderAgnosticBinarySearch.java index 1ff56004..8ae304f6 100644 --- a/src/main/java/com/thealgorithms/searches/OrderAgnosticBinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/OrderAgnosticBinarySearch.java @@ -1,6 +1,6 @@ package com.thealgorithms.searches; -//URL: https://www.geeksforgeeks.org/order-agnostic-binary-search/ +// URL: https://www.geeksforgeeks.org/order-agnostic-binary-search/ /* Order Agnostic Binary Search is an algorithm where we do not know whether the given sorted array is ascending or descending order. @@ -11,37 +11,36 @@ package com.thealgorithms.searches; Depending upon the condition, respective statements will be executed and we will get our answer. */ - public class OrderAgnosticBinarySearch { +public class OrderAgnosticBinarySearch { - static int BinSearchAlgo(int[] arr, int start, int end, int target) { + static int BinSearchAlgo(int[] arr, int start, int end, int target) { - // Checking whether the given array is ascending order - boolean AscOrd = arr[start] < arr[end]; + // Checking whether the given array is ascending order + boolean AscOrd = arr[start] < arr[end]; - while (start <= end) { - int middle = start + (end - start) / 2; + while (start <= end) { + int middle = start + (end - start) / 2; - // Check if the desired element is present at the middle position - if (arr[middle] == target) - return middle; // returns the index of the middle element + // Check if the desired element is present at the middle position + if (arr[middle] == target) return middle; // returns the index of the middle element - // Ascending order - if (AscOrd) { - if (arr[middle] < target) - start = middle + 1; - else - end = middle - 1; - } + // Ascending order + if (AscOrd) { + if (arr[middle] < target) + start = middle + 1; + else + end = middle - 1; + } - // Descending order - else { - if (arr[middle] > target) - start = middle + 1; - else - end = middle - 1; - } - } - // Element is not present - return -1; - } - } + // Descending order + else { + if (arr[middle] > target) + start = middle + 1; + else + end = middle - 1; + } + } + // Element is not present + return -1; + } +} diff --git a/src/main/java/com/thealgorithms/searches/PerfectBinarySearch.java b/src/main/java/com/thealgorithms/searches/PerfectBinarySearch.java index 416ddf6e..8ce01575 100644 --- a/src/main/java/com/thealgorithms/searches/PerfectBinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/PerfectBinarySearch.java @@ -22,7 +22,7 @@ class PerfectBinarySearch { public static void main(String[] args) { PerfectBinarySearch BinarySearch = new PerfectBinarySearch(); - int[] array = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + 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/src/main/java/com/thealgorithms/searches/QuickSelect.java b/src/main/java/com/thealgorithms/searches/QuickSelect.java index 9747a817..db8223e3 100644 --- a/src/main/java/com/thealgorithms/searches/QuickSelect.java +++ b/src/main/java/com/thealgorithms/searches/QuickSelect.java @@ -45,19 +45,12 @@ public final class QuickSelect { return list.get(index); } - private static > int selectIndex( - List list, - int n - ) { + private static > int selectIndex(List list, int n) { return selectIndex(list, 0, list.size() - 1, n); } private static > int selectIndex( - List list, - int left, - int right, - int n - ) { + List list, int left, int right, int n) { while (true) { if (left == right) return left; int pivotIndex = pivot(list, left, right); @@ -73,12 +66,7 @@ public final class QuickSelect { } private static > int partition( - List list, - int left, - int right, - int pivotIndex, - int n - ) { + List list, int left, int right, int pivotIndex, int n) { T pivotValue = list.get(pivotIndex); Collections.swap(list, pivotIndex, right); int storeIndex = left; @@ -104,11 +92,7 @@ public final class QuickSelect { return (n < storeIndex) ? storeIndex : Math.min(n, storeIndexEq); } - private static > int pivot( - List list, - int left, - int right - ) { + private static > int pivot(List list, int left, int right) { if (right - left < 5) { return partition5(list, left, right); } @@ -128,11 +112,7 @@ public final class QuickSelect { return selectIndex(list, left, rightIndex, mid); } - private static > int partition5( - List list, - int left, - int right - ) { + private static > int partition5(List list, int left, int right) { List ts = list.subList(left, right); ts.sort(Comparator.naturalOrder()); return (left + right) >>> 1; diff --git a/src/main/java/com/thealgorithms/searches/RabinKarpAlgorithm.java b/src/main/java/com/thealgorithms/searches/RabinKarpAlgorithm.java index cda1bfec..8343310d 100644 --- a/src/main/java/com/thealgorithms/searches/RabinKarpAlgorithm.java +++ b/src/main/java/com/thealgorithms/searches/RabinKarpAlgorithm.java @@ -13,7 +13,7 @@ public class RabinKarpAlgorithm { q -> A prime number */ public int search(String pat, String txt, int q) { - int index = -1; //note: -1 here represent not found, it is not an index + int index = -1; // note: -1 here represent not found, it is not an index int M = pat.length(); int N = txt.length(); int i, j; diff --git a/src/main/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearch.java b/src/main/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearch.java index 3a672d7c..3b4b0b08 100644 --- a/src/main/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearch.java @@ -10,37 +10,38 @@ import com.thealgorithms.devutils.searches.MatrixSearchAlgorithm; * {21, 31, 41, 51}} * * This array is sorted in both row and column manner. - * In this two pointers are taken, the first points to the 0th row and the second one points to end column, and then the - * element corresponding to the pointers placed in the array is compared with the target that either its equal, greater or - * smaller than the target. If the element is equal to the target, the co-ordinates of that element is returned i.e. an - * array of the two pointers will be returned, else if the target is greater than corresponding element then the pointer - * pointing to the 0th row will be incremented by 1, else if the target is lesser than the corresponding element then the - * pointer pointing to the end column will be decremented by 1. And if the element doesn't exist in the array, an array + * In this two pointers are taken, the first points to the 0th row and the second one points to end + * column, and then the element corresponding to the pointers placed in the array is compared with + * the target that either its equal, greater or smaller than the target. If the element is equal to + * the target, the co-ordinates of that element is returned i.e. an array of the two pointers will + * be returned, else if the target is greater than corresponding element then the pointer pointing + * to the 0th row will be incremented by 1, else if the target is lesser than the corresponding + * element then the pointer pointing to the end column will be decremented by 1. And if the element + * doesn't exist in the array, an array * {-1, -1} will be returned. */ -public class RowColumnWiseSorted2dArrayBinarySearch - implements MatrixSearchAlgorithm { +public class RowColumnWiseSorted2dArrayBinarySearch implements MatrixSearchAlgorithm { - @Override - public > int[] find(T[][] matrix, T key) { - return search(matrix, key); - } - - public static > int[] search(T[][] matrix, T target) { - int rowPointer = 0; //The pointer at 0th row - int colPointer = matrix.length - 1; //The pointer at end column - - while (rowPointer < matrix.length && colPointer >= 0) { - int comp = target.compareTo(matrix[rowPointer][colPointer]); - - if (comp == 0) { - return new int[] { rowPointer, colPointer }; - } else if (comp > 0) { - rowPointer++; //Incrementing the row pointer if the target is greater - } else { - colPointer--; //Decrementing the column pointer if the target is lesser - } + @Override + public > int[] find(T[][] matrix, T key) { + return search(matrix, key); + } + + public static > int[] search(T[][] matrix, T target) { + int rowPointer = 0; // The pointer at 0th row + int colPointer = matrix.length - 1; // The pointer at end column + + while (rowPointer < matrix.length && colPointer >= 0) { + int comp = target.compareTo(matrix[rowPointer][colPointer]); + + if (comp == 0) { + return new int[] {rowPointer, colPointer}; + } else if (comp > 0) { + rowPointer++; // Incrementing the row pointer if the target is greater + } else { + colPointer--; // Decrementing the column pointer if the target is lesser + } + } + return new int[] {-1, -1}; // The not found condition } - return new int[] { -1, -1 }; //The not found condition - } } diff --git a/src/main/java/com/thealgorithms/searches/SaddlebackSearch.java b/src/main/java/com/thealgorithms/searches/SaddlebackSearch.java index 44d38a48..4e5939d6 100644 --- a/src/main/java/com/thealgorithms/searches/SaddlebackSearch.java +++ b/src/main/java/com/thealgorithms/searches/SaddlebackSearch.java @@ -30,7 +30,7 @@ public class SaddlebackSearch { */ private static int[] find(int[][] arr, int row, int col, int key) { // array to store the answer row and column - int[] ans = { -1, -1 }; + int[] ans = {-1, -1}; if (row < 0 || col >= arr[row].length) { return ans; } diff --git a/src/main/java/com/thealgorithms/searches/SearchInARowAndColWiseSortedMatrix.java b/src/main/java/com/thealgorithms/searches/SearchInARowAndColWiseSortedMatrix.java index c92569cf..b173f665 100644 --- a/src/main/java/com/thealgorithms/searches/SearchInARowAndColWiseSortedMatrix.java +++ b/src/main/java/com/thealgorithms/searches/SearchInARowAndColWiseSortedMatrix.java @@ -17,7 +17,7 @@ public class SearchInARowAndColWiseSortedMatrix { int i = 0; // This variable iterates over columns int j = n - 1; - int[] result = { -1, -1 }; + int[] result = {-1, -1}; while (i < n && j >= 0) { if (matrix[i][j] == value) { @@ -30,7 +30,6 @@ public class SearchInARowAndColWiseSortedMatrix { } else { j--; } - } return result; } diff --git a/src/main/java/com/thealgorithms/searches/SquareRootBinarySearch.java b/src/main/java/com/thealgorithms/searches/SquareRootBinarySearch.java index 5b305831..b8ee476b 100644 --- a/src/main/java/com/thealgorithms/searches/SquareRootBinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/SquareRootBinarySearch.java @@ -23,9 +23,7 @@ public class SquareRootBinarySearch { */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); - System.out.print( - "Enter a number you want to calculate square root of : " - ); + System.out.print("Enter a number you want to calculate square root of : "); int num = sc.nextInt(); long ans = squareRoot(num); System.out.println("The square root is : " + ans); diff --git a/src/main/java/com/thealgorithms/searches/TernarySearch.java b/src/main/java/com/thealgorithms/searches/TernarySearch.java index 5b447fa4..e79f0e66 100644 --- a/src/main/java/com/thealgorithms/searches/TernarySearch.java +++ b/src/main/java/com/thealgorithms/searches/TernarySearch.java @@ -39,12 +39,7 @@ public class TernarySearch implements SearchAlgorithm { * @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 - ) { + private > int ternarySearch(T[] arr, T key, int start, int end) { if (start > end) { return -1; } @@ -57,15 +52,11 @@ public class TernarySearch implements SearchAlgorithm { 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 - ) { + } /* 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 - ) { + } /* 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 { + } /* Search middle (1/3)rd part of the array */ else { return ternarySearch(arr, key, mid1, mid2); } } @@ -75,11 +66,10 @@ public class TernarySearch implements SearchAlgorithm { Random r = new Random(); int size = 100; int maxElement = 100000; - Integer[] integers = Stream - .generate(() -> r.nextInt(maxElement)) - .limit(size) - .sorted() - .toArray(Integer[]::new); + 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)]; @@ -87,15 +77,11 @@ public class TernarySearch implements SearchAlgorithm { TernarySearch search = new TernarySearch(); int atIndex = search.find(integers, shouldBeFound); - System.out.printf( - "Should be found: %d. Found %d at index %d. An array length %d%n", - shouldBeFound, - integers[atIndex], - atIndex, - size - ); + System.out.printf("Should be found: %d. Found %d at index %d. An array length %d%n", + shouldBeFound, integers[atIndex], atIndex, size); int toCheck = Arrays.binarySearch(integers, shouldBeFound); - System.out.printf("Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex); + System.out.printf( + "Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex); } } diff --git a/src/main/java/com/thealgorithms/searches/UnionFind.java b/src/main/java/com/thealgorithms/searches/UnionFind.java index ec0a694b..d32e4fd3 100644 --- a/src/main/java/com/thealgorithms/searches/UnionFind.java +++ b/src/main/java/com/thealgorithms/searches/UnionFind.java @@ -61,27 +61,19 @@ public class UnionFind { // Tests public static void main(String[] args) { UnionFind uf = new UnionFind(5); - System.out.println( - "init /w 5 (should print 'p [0, 1, 2, 3, 4] r [0, 0, 0, 0, 0]'):" - ); + System.out.println("init /w 5 (should print 'p [0, 1, 2, 3, 4] r [0, 0, 0, 0, 0]'):"); System.out.println(uf); uf.union(1, 2); - System.out.println( - "union 1 2 (should print 'p [0, 1, 1, 3, 4] r [0, 1, 0, 0, 0]'):" - ); + System.out.println("union 1 2 (should print 'p [0, 1, 1, 3, 4] r [0, 1, 0, 0, 0]'):"); System.out.println(uf); uf.union(3, 4); - System.out.println( - "union 3 4 (should print 'p [0, 1, 1, 3, 3] r [0, 1, 0, 1, 0]'):" - ); + System.out.println("union 3 4 (should print 'p [0, 1, 1, 3, 3] r [0, 1, 0, 1, 0]'):"); System.out.println(uf); uf.find(4); - System.out.println( - "find 4 (should print 'p [0, 1, 1, 3, 3] r [0, 1, 0, 1, 0]'):" - ); + System.out.println("find 4 (should print 'p [0, 1, 1, 3, 3] r [0, 1, 0, 1, 0]'):"); System.out.println(uf); System.out.println("count (should print '3'):"); diff --git a/src/main/java/com/thealgorithms/searches/UpperBound.java b/src/main/java/com/thealgorithms/searches/UpperBound.java index 1c842fbc..cddd3cb8 100644 --- a/src/main/java/com/thealgorithms/searches/UpperBound.java +++ b/src/main/java/com/thealgorithms/searches/UpperBound.java @@ -33,12 +33,11 @@ class UpperBound implements SearchAlgorithm { 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 for which the upper bound is to be found int val = integers[r.nextInt(size - 1)] + 1; @@ -46,16 +45,12 @@ class UpperBound implements SearchAlgorithm { UpperBound search = new UpperBound(); int atIndex = search.find(integers, val); - System.out.printf( - "Val: %d. Upper Bound Found %d at index %d. An array length %d%n", - val, - integers[atIndex], - atIndex, - size - ); + System.out.printf("Val: %d. Upper Bound Found %d at index %d. An array length %d%n", val, + integers[atIndex], atIndex, size); boolean toCheck = integers[atIndex] > val || integers[size - 1] < val; - System.out.printf("Upper Bound found at an index: %d. Is greater or max element: %b%n", atIndex, toCheck); + System.out.printf( + "Upper Bound found at an index: %d. Is greater or max element: %b%n", atIndex, toCheck); } /** @@ -78,12 +73,7 @@ class UpperBound implements SearchAlgorithm { * @param right The upper bound * @return the location of the key */ - private > int search( - T[] array, - T key, - int left, - int right - ) { + private > int search(T[] array, T key, int left, int right) { if (right <= left) { return left; } diff --git a/src/main/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearch.java b/src/main/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearch.java index eb62555f..c21e307c 100644 --- a/src/main/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearch.java @@ -1,31 +1,29 @@ package com.thealgorithms.searches; import java.util.*; public class sortOrderAgnosticBinarySearch { - public static int find(int[] arr, int key){ + public static int find(int[] arr, int key) { int start = 0; - int end = arr.length-1; - boolean arrDescending = arr[start]>arr[end]; //checking for Array is in ascending order or descending order. - while(start<=end){ - int mid = end-start/2; - if (arr[mid]==key){ + int end = arr.length - 1; + boolean arrDescending = arr[start] + > arr[end]; // checking for Array is in ascending order or descending order. + while (start <= end) { + int mid = end - start / 2; + if (arr[mid] == key) { return mid; } - if(arrDescending){ // boolean is true then our array is in descending order - if(key arr[mid]) { + start = mid + 1; + } else { + end = mid - 1; } } - else { // otherwise our array is in ascending order - if(key>arr[mid]){ - start=mid+1; - } - else{ - end=mid-1; - } - } } return -1; } diff --git a/src/main/java/com/thealgorithms/sorts/BeadSort.java b/src/main/java/com/thealgorithms/sorts/BeadSort.java index cd60ab0b..101a5c50 100644 --- a/src/main/java/com/thealgorithms/sorts/BeadSort.java +++ b/src/main/java/com/thealgorithms/sorts/BeadSort.java @@ -1,41 +1,40 @@ package com.thealgorithms.sorts; - -//BeadSort Algorithm(wikipedia) : https://en.wikipedia.org/wiki/Bead_sort -//BeadSort can't sort negative number, Character, String. It can sort positive number only +// BeadSort Algorithm(wikipedia) : https://en.wikipedia.org/wiki/Bead_sort +// BeadSort can't sort negative number, Character, String. It can sort positive number only public class BeadSort { public int[] sort(int[] unsorted) { - int[] sorted = new int[unsorted.length]; - int max = 0; - for(int i = 0; i < unsorted.length; i++) { - max = Math.max(max, unsorted[i]); - } - - char[][] grid = new char[unsorted.length][max]; - int[] count = new int[max]; - - for(int i = 0; i < unsorted.length; i++) { - for(int j = 0; j < max; j++) { - grid[i][j] = '-'; - } - } - - for(int i = 0; i < max; i++) { - count[i] = 0; - } - - for(int i = 0; i < unsorted.length; i++) { - int k = 0; - for(int j = 0; j < unsorted[i]; j++) { - grid[count[max - k - 1]++][k] = '*'; - k++; - } + int[] sorted = new int[unsorted.length]; + int max = 0; + for (int i = 0; i < unsorted.length; i++) { + max = Math.max(max, unsorted[i]); } - for(int i = 0; i < unsorted.length; i++) { + char[][] grid = new char[unsorted.length][max]; + int[] count = new int[max]; + + for (int i = 0; i < unsorted.length; i++) { + for (int j = 0; j < max; j++) { + grid[i][j] = '-'; + } + } + + for (int i = 0; i < max; i++) { + count[i] = 0; + } + + for (int i = 0; i < unsorted.length; i++) { int k = 0; - for(int j = 0; j < max && grid[unsorted.length - 1 - i][j] == '*'; j++) { + for (int j = 0; j < unsorted[i]; j++) { + grid[count[max - k - 1]++][k] = '*'; + k++; + } + } + + for (int i = 0; i < unsorted.length; i++) { + int k = 0; + for (int j = 0; j < max && grid[unsorted.length - 1 - i][j] == '*'; j++) { k++; } sorted[i] = k; diff --git a/src/main/java/com/thealgorithms/sorts/BitonicSort.java b/src/main/java/com/thealgorithms/sorts/BitonicSort.java index 414aa647..346d8605 100644 --- a/src/main/java/com/thealgorithms/sorts/BitonicSort.java +++ b/src/main/java/com/thealgorithms/sorts/BitonicSort.java @@ -69,7 +69,7 @@ public class BitonicSort { } public static void main(String[] args) { - int[] a = { 3, 7, 4, 8, 6, 2, 1, 5 }; + int[] a = {3, 7, 4, 8, 6, 2, 1, 5}; int up = 1; BitonicSort ob = new BitonicSort(); ob.sort(a, a.length, up); diff --git a/src/main/java/com/thealgorithms/sorts/BogoSort.java b/src/main/java/com/thealgorithms/sorts/BogoSort.java index 26a2a3a1..75f1e843 100644 --- a/src/main/java/com/thealgorithms/sorts/BogoSort.java +++ b/src/main/java/com/thealgorithms/sorts/BogoSort.java @@ -39,7 +39,7 @@ public class BogoSort implements SortAlgorithm { // Driver Program public static void main(String[] args) { // Integer Input - Integer[] integers = { 4, 23, 6, 78, 1, 54, 231, 9, 12 }; + Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12}; BogoSort bogoSort = new BogoSort(); @@ -47,7 +47,7 @@ public class BogoSort implements SortAlgorithm { SortUtils.print(bogoSort.sort(integers)); // String Input - String[] strings = { "c", "a", "e", "b", "d" }; + String[] strings = {"c", "a", "e", "b", "d"}; SortUtils.print(bogoSort.sort(strings)); } diff --git a/src/main/java/com/thealgorithms/sorts/BubbleSortRecursion.java b/src/main/java/com/thealgorithms/sorts/BubbleSortRecursion.java index c95f549a..10197969 100644 --- a/src/main/java/com/thealgorithms/sorts/BubbleSortRecursion.java +++ b/src/main/java/com/thealgorithms/sorts/BubbleSortRecursion.java @@ -41,10 +41,7 @@ public class BubbleSortRecursion implements SortAlgorithm { * @param unsorted array contains elements * @param len length of given array */ - private static > void bubbleSort( - T[] unsorted, - int len - ) { + 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) { diff --git a/src/main/java/com/thealgorithms/sorts/BucketSort.java b/src/main/java/com/thealgorithms/sorts/BucketSort.java index f2288479..184e36f0 100644 --- a/src/main/java/com/thealgorithms/sorts/BucketSort.java +++ b/src/main/java/com/thealgorithms/sorts/BucketSort.java @@ -67,7 +67,7 @@ public class BucketSort { arr[index++] = value; } } - + return arr; } diff --git a/src/main/java/com/thealgorithms/sorts/CircleSort.java b/src/main/java/com/thealgorithms/sorts/CircleSort.java index 3d013c88..74b3fc62 100644 --- a/src/main/java/com/thealgorithms/sorts/CircleSort.java +++ b/src/main/java/com/thealgorithms/sorts/CircleSort.java @@ -10,7 +10,8 @@ public class CircleSort implements SortAlgorithm { @Override public > T[] sort(T[] array) { int n = array.length; - while (doSort(array, 0, n - 1)); + while (doSort(array, 0, n - 1)) + ; return array; } @@ -19,11 +20,7 @@ public class CircleSort implements SortAlgorithm { * @param the left boundary of the part currently being sorted * @param the right boundary of the part currently being sorted */ - private > Boolean doSort( - T[] array, - int left, - int right - ) { + private > Boolean doSort(T[] array, int left, int right) { boolean swapped = false; if (left == right) { @@ -58,13 +55,13 @@ public class CircleSort implements SortAlgorithm { public static void main(String[] args) { CircleSort CSort = new CircleSort(); - Integer[] arr = { 4, 23, 6, 78, 1, 54, 231, 9, 12 }; + Integer[] arr = {4, 23, 6, 78, 1, 54, 231, 9, 12}; CSort.sort(arr); for (int i = 0; i < arr.length - 1; ++i) { assert arr[i] <= arr[i + 1]; } - String[] stringArray = { "c", "a", "e", "b", "d" }; + String[] stringArray = {"c", "a", "e", "b", "d"}; CSort.sort(stringArray); for (int i = 0; i < stringArray.length - 1; ++i) { assert arr[i].compareTo(arr[i + 1]) <= 0; diff --git a/src/main/java/com/thealgorithms/sorts/CocktailShakerSort.java b/src/main/java/com/thealgorithms/sorts/CocktailShakerSort.java index 474fa3d7..dc3a9a10 100644 --- a/src/main/java/com/thealgorithms/sorts/CocktailShakerSort.java +++ b/src/main/java/com/thealgorithms/sorts/CocktailShakerSort.java @@ -43,14 +43,14 @@ class CocktailShakerSort implements SortAlgorithm { // Driver Program public static void main(String[] args) { // Integer Input - Integer[] integers = { 4, 23, 6, 78, 1, 54, 231, 9, 12 }; + 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" }; + String[] strings = {"c", "a", "e", "b", "d"}; SortUtils.print(shakerSort.sort(strings)); } } diff --git a/src/main/java/com/thealgorithms/sorts/CountingSort.java b/src/main/java/com/thealgorithms/sorts/CountingSort.java index 570fd3e8..11c2ce18 100644 --- a/src/main/java/com/thealgorithms/sorts/CountingSort.java +++ b/src/main/java/com/thealgorithms/sorts/CountingSort.java @@ -53,25 +53,20 @@ class CountingSort implements SortAlgorithm { * @param list The list to be sorted */ private static > List streamSort(List list) { - return list - .stream() + 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()) - ) + .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()); + 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:"); @@ -86,9 +81,8 @@ class CountingSort implements SortAlgorithm { System.out.println("\n------------------------------\n"); // String Input - List unsortedStrings = Stream - .of("c", "a", "e", "b", "d", "a", "f", "g", "c") - .collect(toList()); + List unsortedStrings + = Stream.of("c", "a", "e", "b", "d", "a", "f", "g", "c").collect(toList()); System.out.println("Before Sorting:"); print(unsortedStrings); diff --git a/src/main/java/com/thealgorithms/sorts/DNFSort.java b/src/main/java/com/thealgorithms/sorts/DNFSort.java index 4c4520c6..7e18b657 100644 --- a/src/main/java/com/thealgorithms/sorts/DNFSort.java +++ b/src/main/java/com/thealgorithms/sorts/DNFSort.java @@ -10,26 +10,24 @@ public class DNFSort { int mid = 0, temp = 0; while (mid <= high) { switch (a[mid]) { - case 0: - { - temp = a[low]; - a[low] = a[mid]; - a[mid] = temp; - low++; - mid++; - break; - } - case 1: - mid++; - break; - case 2: - { - temp = a[mid]; - a[mid] = a[high]; - a[high] = temp; - high--; - break; - } + case 0: { + temp = a[low]; + a[low] = a[mid]; + a[mid] = temp; + low++; + mid++; + break; + } + case 1: + mid++; + break; + case 2: { + temp = a[mid]; + a[mid] = a[high]; + a[high] = temp; + high--; + break; + } } } } @@ -44,7 +42,7 @@ public class DNFSort { /*Driver function to check for above functions*/ public static void main(String[] args) { - int[] arr = { 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 }; + int[] arr = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int arr_size = arr.length; sort012(arr, arr_size); System.out.println("Array after seggregation "); diff --git a/src/main/java/com/thealgorithms/sorts/DualPivotQuickSort.java b/src/main/java/com/thealgorithms/sorts/DualPivotQuickSort.java index 69a09e67..6fabddcb 100644 --- a/src/main/java/com/thealgorithms/sorts/DualPivotQuickSort.java +++ b/src/main/java/com/thealgorithms/sorts/DualPivotQuickSort.java @@ -2,7 +2,7 @@ package com.thealgorithms.sorts; /** * Dual Pivot Quick Sort Algorithm - * + * * @author Debasish Biswas (https://github.com/debasishbsws) * * @see SortAlgorithm */ @@ -26,7 +26,8 @@ public class DualPivotQuickSort implements SortAlgorithm { * @param right The last index of an array * @param array The array to be sorted */ - private static > void dualPivotQuicksort(T[] array, int left, int right) { + private static > void dualPivotQuicksort( + T[] array, int left, int right) { if (left < right) { int[] pivots = partition(array, left, right); @@ -44,8 +45,7 @@ public class DualPivotQuickSort implements SortAlgorithm { * @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) { - if (array[left].compareTo(array[right]) > 0) - swap(array, left, right); + if (array[left].compareTo(array[right]) > 0) swap(array, left, right); T pivot1 = array[left]; T pivot2 = array[right]; @@ -62,14 +62,11 @@ public class DualPivotQuickSort implements SortAlgorithm { // If element is greater or equal to pivot2 else if (array[less].compareTo(pivot2) >= 0) { - while (less < great && array[great].compareTo(pivot2) > 0) - great--; + while (less < great && array[great].compareTo(pivot2) > 0) great--; swap(array, less, great--); - if (array[less].compareTo(pivot1) < 0) - swap(array, less, left++); - + if (array[less].compareTo(pivot1) < 0) swap(array, less, left++); } less++; @@ -81,7 +78,7 @@ public class DualPivotQuickSort implements SortAlgorithm { swap(array, right, great); // return the pivots' indices - return new int[] { less, great }; + return new int[] {less, great}; } private static > void swap(T[] array, int left, int right) { @@ -96,7 +93,7 @@ public class DualPivotQuickSort implements SortAlgorithm { * @param args the command line arguments */ public static void main(String[] args) { - Integer[] array = { 24, 8, -42, 75, -29, -77, 38, 57 }; + Integer[] array = {24, 8, -42, 75, -29, -77, 38, 57}; DualPivotQuickSort dualPivotQuickSort = new DualPivotQuickSort(); dualPivotQuickSort.sort(array); for (int i = 0; i < array.length; i++) { @@ -107,5 +104,4 @@ public class DualPivotQuickSort implements SortAlgorithm { /* * References: https://www.geeksforgeeks.org/dual-pivot-quicksort/ */ - } \ No newline at end of file diff --git a/src/main/java/com/thealgorithms/sorts/DutchNationalFlagSort.java b/src/main/java/com/thealgorithms/sorts/DutchNationalFlagSort.java index 5a2c8a01..123f22d8 100644 --- a/src/main/java/com/thealgorithms/sorts/DutchNationalFlagSort.java +++ b/src/main/java/com/thealgorithms/sorts/DutchNationalFlagSort.java @@ -1,34 +1,27 @@ package com.thealgorithms.sorts; /** - * The Dutch National Flag Sort sorts a sequence of values into three permutations which are defined by a value given - * as the indented middle. - * First permutation: values less than middle. - * Second permutation: values equal middle. - * Third permutation: values greater than middle. - * If no indented middle is given, this implementation will use a value from the given Array. - * This value is the one positioned in the arrays' middle if the arrays' length is odd. - * If the arrays' length is even, the value left to the middle will be used. - * More information and Pseudocode: https://en.wikipedia.org/wiki/Dutch_national_flag_problem + * The Dutch National Flag Sort sorts a sequence of values into three permutations which are defined + * by a value given as the indented middle. First permutation: values less than middle. Second + * permutation: values equal middle. Third permutation: values greater than middle. If no indented + * middle is given, this implementation will use a value from the given Array. This value is the one + * positioned in the arrays' middle if the arrays' length is odd. If the arrays' length is even, the + * value left to the middle will be used. More information and Pseudocode: + * https://en.wikipedia.org/wiki/Dutch_national_flag_problem */ public class DutchNationalFlagSort implements SortAlgorithm { @Override public > T[] sort(T[] unsorted) { return dutch_national_flag_sort( - unsorted, - unsorted[(int) Math.ceil((unsorted.length) / 2.0) - 1] - ); + unsorted, unsorted[(int) Math.ceil((unsorted.length) / 2.0) - 1]); } public > T[] sort(T[] unsorted, T intendedMiddle) { return dutch_national_flag_sort(unsorted, intendedMiddle); } - private > T[] dutch_national_flag_sort( - T[] arr, - T intendedMiddle - ) { + private > T[] dutch_national_flag_sort(T[] arr, T intendedMiddle) { int i = 0; int j = 0; int k = arr.length - 1; diff --git a/src/main/java/com/thealgorithms/sorts/InsertionSort.java b/src/main/java/com/thealgorithms/sorts/InsertionSort.java index e9031cb9..c74ff316 100644 --- a/src/main/java/com/thealgorithms/sorts/InsertionSort.java +++ b/src/main/java/com/thealgorithms/sorts/InsertionSort.java @@ -1,9 +1,9 @@ package com.thealgorithms.sorts; -import java.util.function.Function; - import static com.thealgorithms.sorts.SortUtils.*; +import java.util.function.Function; + class InsertionSort implements SortAlgorithm { /** @@ -40,14 +40,12 @@ class InsertionSort implements SortAlgorithm { public > T[] sentinelSort(T[] array) { int minElemIndex = 0; int n = array.length; - if (n < 1) - return array; + if (n < 1) return array; // put the smallest element to the 0 position as a sentinel, which will allow us to avoid // redundant comparisons like `j > 0` further for (int i = 1; i < n; i++) - if (less(array[i], array[minElemIndex])) - minElemIndex = i; + if (less(array[i], array[minElemIndex])) minElemIndex = i; swap(array, 0, minElemIndex); for (int i = 2; i < n; i++) { @@ -77,15 +75,17 @@ class InsertionSort implements SortAlgorithm { double insertionTime = measureApproxExecTime(insertionSort::sort, randomArray); System.out.printf("Original insertion time: %5.2f sec.\n", insertionTime); - double insertionSentinelTime = measureApproxExecTime(insertionSort::sentinelSort, copyRandomArray); + double insertionSentinelTime + = measureApproxExecTime(insertionSort::sentinelSort, copyRandomArray); System.out.printf("Sentinel insertion time: %5.2f sec.\n", insertionSentinelTime); // ~ 1.5 time sentinel sort is faster, then classical Insertion sort implementation. System.out.printf("Sentinel insertion is %f3.2 time faster than Original insertion sort\n", - insertionTime / insertionSentinelTime); + insertionTime / insertionSentinelTime); } - private static double measureApproxExecTime(Function sortAlgorithm, Double[] randomArray) { + private static double measureApproxExecTime( + Function sortAlgorithm, Double[] randomArray) { long start = System.currentTimeMillis(); sortAlgorithm.apply(randomArray); long end = System.currentTimeMillis(); diff --git a/src/main/java/com/thealgorithms/sorts/LinkListSort.java b/src/main/java/com/thealgorithms/sorts/LinkListSort.java index 07f03cca..e679fa9f 100644 --- a/src/main/java/com/thealgorithms/sorts/LinkListSort.java +++ b/src/main/java/com/thealgorithms/sorts/LinkListSort.java @@ -1,4 +1,5 @@ -/** Author : Siddhant Swarup Mallick +/** + * Author : Siddhant Swarup Mallick * Github : https://github.com/siddhant2002 */ @@ -21,86 +22,86 @@ public class LinkListSort { // Choice is choosed as any number from 1 to 3 (So the linked list will be // sorted by Merge sort technique/Insertion sort technique/Heap sort technique) switch (ch) { - case 1: - Task nm = new Task(); - Node start = null, prev = null, fresh, ptr; - for (int i = 0; i < a.length; i++) { - // New nodes are created and values are added - fresh = new Node(); // Node class is called - fresh.val = a[i]; // Node val is stored - if (start == null) - start = fresh; - else - prev.next = fresh; - prev = fresh; - } - start = nm.sortByMergeSort(start); - // method is being called - int i = 0; - for (ptr = start; ptr != null; ptr = ptr.next) { - a[i++] = ptr.val; - // storing the sorted values in the array - } - Arrays.sort(b); - // array b is sorted and it will return true when checked with sorted list - LinkListSort uu = new LinkListSort(); - return uu.compare(a, b); - // The given array and the expected array is checked if both are same then true - // is displayed else false is displayed - case 2: - Node start1 = null, prev1 = null, fresh1, ptr1; - for (int i1 = 0; i1 < a.length; i1++) { - // New nodes are created and values are added - fresh1 = new Node(); // New node is created - fresh1.val = a[i1]; // Value is stored in the value part of the node - if (start1 == null) - start1 = fresh1; - else - prev1.next = fresh1; - prev1 = fresh1; - } - Task1 kk = new Task1(); - start1 = kk.sortByInsertionSort(start1); - // method is being called - int i1 = 0; - for (ptr1 = start1; ptr1 != null; ptr1 = ptr1.next) { - a[i1++] = ptr1.val; - // storing the sorted values in the array - } - LinkListSort uu1 = new LinkListSort(); - // array b is not sorted and it will return false when checked with sorted list - return uu1.compare(a, b); - // The given array and the expected array is checked if both are same then true - // is displayed else false is displayed - case 3: - Task2 mm = new Task2(); - Node start2 = null, prev2 = null, fresh2, ptr2; - for (int i2 = 0; i2 < a.length; i2++) { - // New nodes are created and values are added - fresh2 = new Node(); // Node class is created - fresh2.val = a[i2]; // Value is stored in the value part of the Node - if (start2 == null) - start2 = fresh2; - else - prev2.next = fresh2; - prev2 = fresh2; - } - start2 = mm.sortByHeapSort(start2); - // method is being called - int i3 = 0; - for (ptr2 = start2; ptr2 != null; ptr2 = ptr2.next) { - a[i3++] = ptr2.val; - // storing the sorted values in the array - } - Arrays.sort(b); - // array b is sorted and it will return true when checked with sorted list - LinkListSort uu2 = new LinkListSort(); - return uu2.compare(a, b); - // The given array and the expected array is checked if both are same then true - // is displayed else false is displayed - default: - // default is used incase user puts a unauthorized value - System.out.println("Wrong choice"); + case 1: + Task nm = new Task(); + Node start = null, prev = null, fresh, ptr; + for (int i = 0; i < a.length; i++) { + // New nodes are created and values are added + fresh = new Node(); // Node class is called + fresh.val = a[i]; // Node val is stored + if (start == null) + start = fresh; + else + prev.next = fresh; + prev = fresh; + } + start = nm.sortByMergeSort(start); + // method is being called + int i = 0; + for (ptr = start; ptr != null; ptr = ptr.next) { + a[i++] = ptr.val; + // storing the sorted values in the array + } + Arrays.sort(b); + // array b is sorted and it will return true when checked with sorted list + LinkListSort uu = new LinkListSort(); + return uu.compare(a, b); + // The given array and the expected array is checked if both are same then true + // is displayed else false is displayed + case 2: + Node start1 = null, prev1 = null, fresh1, ptr1; + for (int i1 = 0; i1 < a.length; i1++) { + // New nodes are created and values are added + fresh1 = new Node(); // New node is created + fresh1.val = a[i1]; // Value is stored in the value part of the node + if (start1 == null) + start1 = fresh1; + else + prev1.next = fresh1; + prev1 = fresh1; + } + Task1 kk = new Task1(); + start1 = kk.sortByInsertionSort(start1); + // method is being called + int i1 = 0; + for (ptr1 = start1; ptr1 != null; ptr1 = ptr1.next) { + a[i1++] = ptr1.val; + // storing the sorted values in the array + } + LinkListSort uu1 = new LinkListSort(); + // array b is not sorted and it will return false when checked with sorted list + return uu1.compare(a, b); + // The given array and the expected array is checked if both are same then true + // is displayed else false is displayed + case 3: + Task2 mm = new Task2(); + Node start2 = null, prev2 = null, fresh2, ptr2; + for (int i2 = 0; i2 < a.length; i2++) { + // New nodes are created and values are added + fresh2 = new Node(); // Node class is created + fresh2.val = a[i2]; // Value is stored in the value part of the Node + if (start2 == null) + start2 = fresh2; + else + prev2.next = fresh2; + prev2 = fresh2; + } + start2 = mm.sortByHeapSort(start2); + // method is being called + int i3 = 0; + for (ptr2 = start2; ptr2 != null; ptr2 = ptr2.next) { + a[i3++] = ptr2.val; + // storing the sorted values in the array + } + Arrays.sort(b); + // array b is sorted and it will return true when checked with sorted list + LinkListSort uu2 = new LinkListSort(); + return uu2.compare(a, b); + // The given array and the expected array is checked if both are same then true + // is displayed else false is displayed + default: + // default is used incase user puts a unauthorized value + System.out.println("Wrong choice"); } // Switch case is used to call the classes as per the user requirement return false; @@ -108,8 +109,7 @@ public class LinkListSort { boolean compare(int[] a, int[] b) { for (int i = 0; i < a.length; i++) { - if (a[i] != b[i]) - return false; + if (a[i] != b[i]) return false; } return true; // Both the arrays are checked for equalness. If both are equal then true is @@ -140,8 +140,7 @@ class Task { static int[] a; public Node sortByMergeSort(Node head) { - if (head == null || head.next == null) - return head; + if (head == null || head.next == null) return head; int c = count(head); a = new int[c]; // Array of size c is created @@ -207,8 +206,7 @@ class Task { class Task1 { public Node sortByInsertionSort(Node head) { - if (head == null || head.next == null) - return head; + if (head == null || head.next == null) return head; int c = count(head); int[] a = new int[c]; // Array of size c is created @@ -250,8 +248,7 @@ class Task2 { static int[] a; public Node sortByHeapSort(Node head) { - if (head == null || head.next == null) - return head; + if (head == null || head.next == null) return head; int c = count(head); a = new int[c]; // Array of size c is created @@ -298,10 +295,8 @@ class Task2 { int p = i; int l = 2 * i + 1; int r = 2 * i + 2; - if (l < k && n[l] > n[p]) - p = l; - if (r < k && n[r] > n[p]) - p = r; + if (l < k && n[l] > n[p]) p = l; + if (r < k && n[r] > n[p]) p = r; if (p != i) { int d = n[p]; n[p] = n[i]; diff --git a/src/main/java/com/thealgorithms/sorts/MergeSort.java b/src/main/java/com/thealgorithms/sorts/MergeSort.java index 7c9bf9eb..0950b468 100644 --- a/src/main/java/com/thealgorithms/sorts/MergeSort.java +++ b/src/main/java/com/thealgorithms/sorts/MergeSort.java @@ -9,8 +9,7 @@ import static com.thealgorithms.sorts.SortUtils.less; */ class MergeSort implements SortAlgorithm { - @SuppressWarnings("rawtypes") - private static Comparable[] aux; + @SuppressWarnings("rawtypes") private static Comparable[] aux; /** * Generic merge sort algorithm implements. diff --git a/src/main/java/com/thealgorithms/sorts/MergeSortNoExtraSpace.java b/src/main/java/com/thealgorithms/sorts/MergeSortNoExtraSpace.java index c0652860..92405d3d 100644 --- a/src/main/java/com/thealgorithms/sorts/MergeSortNoExtraSpace.java +++ b/src/main/java/com/thealgorithms/sorts/MergeSortNoExtraSpace.java @@ -13,7 +13,8 @@ public class MergeSortNoExtraSpace { merge_sort(a, 0, n - 1, maxele); } - public static void merge_sort(int[] a, int start, int end, int maxele) { //this function divides the array into 2 halves + public static void merge_sort( + int[] a, int start, int end, int maxele) { // this function divides the array into 2 halves if (start < end) { int mid = (start + end) / 2; merge_sort(a, start, mid, maxele); @@ -22,13 +23,8 @@ public class MergeSortNoExtraSpace { } } - public static void implement_merge_sort( - int[] a, - int start, - int mid, - int end, - int maxele - ) { //implementation of mergesort + public static void implement_merge_sort(int[] a, int start, int mid, int end, + int maxele) { // implementation of mergesort int i = start; int j = mid + 1; int k = start; diff --git a/src/main/java/com/thealgorithms/sorts/MergeSortRecursive.java b/src/main/java/com/thealgorithms/sorts/MergeSortRecursive.java index 902507ab..9d4a5871 100644 --- a/src/main/java/com/thealgorithms/sorts/MergeSortRecursive.java +++ b/src/main/java/com/thealgorithms/sorts/MergeSortRecursive.java @@ -34,10 +34,7 @@ public class MergeSortRecursive { return sort(arrA, arrB); } - private static List sort( - List unsortedA, - List unsortedB - ) { + private static List sort(List unsortedA, List unsortedB) { if (unsortedA.size() <= 0 && unsortedB.size() <= 0) { return new ArrayList<>(); } @@ -49,23 +46,15 @@ public class MergeSortRecursive { } if (unsortedA.get(0) <= unsortedB.get(0)) { List newAl = new ArrayList() { - { - add(unsortedA.get(0)); - } + { add(unsortedA.get(0)); } }; - newAl.addAll( - sort(unsortedA.subList(1, unsortedA.size()), unsortedB) - ); + newAl.addAll(sort(unsortedA.subList(1, unsortedA.size()), unsortedB)); return newAl; } else { List newAl = new ArrayList() { - { - add(unsortedB.get(0)); - } + { add(unsortedB.get(0)); } }; - newAl.addAll( - sort(unsortedA, unsortedB.subList(1, unsortedB.size())) - ); + newAl.addAll(sort(unsortedA, unsortedB.subList(1, unsortedB.size()))); return newAl; } } @@ -75,8 +64,7 @@ class App { public static void main(String[] args) { MergeSortRecursive sort = new MergeSortRecursive( - new ArrayList<>(Arrays.asList(4, 3, 1, 8, 5, 10, 0, 1, 4, 11, 8, 9)) - ); + new ArrayList<>(Arrays.asList(4, 3, 1, 8, 5, 10, 0, 1, 4, 11, 8, 9))); sort.mergeSort(); } } diff --git a/src/main/java/com/thealgorithms/sorts/OddEvenSort.java b/src/main/java/com/thealgorithms/sorts/OddEvenSort.java index e6fe5e6c..b5213792 100644 --- a/src/main/java/com/thealgorithms/sorts/OddEvenSort.java +++ b/src/main/java/com/thealgorithms/sorts/OddEvenSort.java @@ -19,7 +19,7 @@ public class OddEvenSort { oddEvenSort(arr); - //Print Sorted elements + // Print Sorted elements for (int i = 0; i < arr.length - 1; ++i) { System.out.println(arr[i]); assert arr[i] <= arr[i + 1]; diff --git a/src/main/java/com/thealgorithms/sorts/PigeonholeSort.java b/src/main/java/com/thealgorithms/sorts/PigeonholeSort.java index ce1aa774..cd399fb7 100644 --- a/src/main/java/com/thealgorithms/sorts/PigeonholeSort.java +++ b/src/main/java/com/thealgorithms/sorts/PigeonholeSort.java @@ -39,7 +39,7 @@ public class PigeonholeSort { public static void main(String[] args) { PigeonholeSort pigeonholeSort = new PigeonholeSort(); - Integer[] arr = { 8, 3, 2, 7, 4, 6, 8 }; + Integer[] arr = {8, 3, 2, 7, 4, 6, 8}; System.out.print("Unsorted order is : "); print(arr); diff --git a/src/main/java/com/thealgorithms/sorts/QuickSort.java b/src/main/java/com/thealgorithms/sorts/QuickSort.java index c0fe66e2..2842b08a 100644 --- a/src/main/java/com/thealgorithms/sorts/QuickSort.java +++ b/src/main/java/com/thealgorithms/sorts/QuickSort.java @@ -27,11 +27,7 @@ class QuickSort implements SortAlgorithm { * @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 - ) { + private static > void doSort(T[] array, int left, int right) { if (left < right) { int pivot = randomPartition(array, left, right); doSort(array, left, pivot - 1); @@ -47,11 +43,7 @@ class QuickSort implements SortAlgorithm { * @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 - ) { + 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); @@ -65,11 +57,7 @@ class QuickSort implements SortAlgorithm { * @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 - ) { + private static > int partition(T[] array, int left, int right) { int mid = (left + right) >>> 1; T pivot = array[mid]; diff --git a/src/main/java/com/thealgorithms/sorts/RadixSort.java b/src/main/java/com/thealgorithms/sorts/RadixSort.java index 93d57914..d2090bf8 100644 --- a/src/main/java/com/thealgorithms/sorts/RadixSort.java +++ b/src/main/java/com/thealgorithms/sorts/RadixSort.java @@ -53,7 +53,7 @@ class RadixSort { } public static void main(String[] args) { - int[] arr = { 170, 45, 75, 90, 802, 24, 2, 66 }; + int[] arr = {170, 45, 75, 90, 802, 24, 2, 66}; int n = arr.length; radixsort(arr, n); print(arr, n); diff --git a/src/main/java/com/thealgorithms/sorts/SelectionSort.java b/src/main/java/com/thealgorithms/sorts/SelectionSort.java index 3c4dfe25..555b4b60 100644 --- a/src/main/java/com/thealgorithms/sorts/SelectionSort.java +++ b/src/main/java/com/thealgorithms/sorts/SelectionSort.java @@ -32,14 +32,14 @@ public class SelectionSort implements SortAlgorithm { * Driver Code */ public static void main(String[] args) { - Integer[] arr = { 4, 23, 6, 78, 1, 54, 231, 9, 12 }; + Integer[] arr = {4, 23, 6, 78, 1, 54, 231, 9, 12}; SelectionSort selectionSort = new SelectionSort(); Integer[] sorted = selectionSort.sort(arr); for (int i = 0; i < sorted.length - 1; ++i) { assert sorted[i] <= sorted[i + 1]; } - String[] strings = { "c", "a", "e", "b", "d" }; + String[] strings = {"c", "a", "e", "b", "d"}; String[] sortedStrings = selectionSort.sort(strings); for (int i = 0; i < sortedStrings.length - 1; ++i) { assert strings[i].compareTo(strings[i + 1]) <= 0; diff --git a/src/main/java/com/thealgorithms/sorts/ShellSort.java b/src/main/java/com/thealgorithms/sorts/ShellSort.java index fe2c387f..5f41a544 100644 --- a/src/main/java/com/thealgorithms/sorts/ShellSort.java +++ b/src/main/java/com/thealgorithms/sorts/ShellSort.java @@ -36,7 +36,7 @@ public class ShellSort implements SortAlgorithm { /* Driver Code */ public static void main(String[] args) { - Integer[] toSort = { 4, 23, 6, 78, 1, 54, 231, 9, 12 }; + Integer[] toSort = {4, 23, 6, 78, 1, 54, 231, 9, 12}; ShellSort sort = new ShellSort(); sort.sort(toSort); diff --git a/src/main/java/com/thealgorithms/sorts/SimpleSort.java b/src/main/java/com/thealgorithms/sorts/SimpleSort.java index 1255f392..138ebb62 100644 --- a/src/main/java/com/thealgorithms/sorts/SimpleSort.java +++ b/src/main/java/com/thealgorithms/sorts/SimpleSort.java @@ -23,7 +23,7 @@ public class SimpleSort implements SortAlgorithm { public static void main(String[] args) { // ==== Int ======= - Integer[] a = { 3, 7, 45, 1, 33, 5, 2, 9 }; + Integer[] a = {3, 7, 45, 1, 33, 5, 2, 9}; System.out.print("unsorted: "); print(a); System.out.println(); diff --git a/src/main/java/com/thealgorithms/sorts/SortAlgorithm.java b/src/main/java/com/thealgorithms/sorts/SortAlgorithm.java index 85886b74..7a3ded37 100644 --- a/src/main/java/com/thealgorithms/sorts/SortAlgorithm.java +++ b/src/main/java/com/thealgorithms/sorts/SortAlgorithm.java @@ -24,9 +24,7 @@ public interface SortAlgorithm { * @return a sorted list */ @SuppressWarnings("unchecked") - default > List sort(List unsorted) { - return Arrays.asList( - sort(unsorted.toArray((T[]) new Comparable[unsorted.size()])) - ); + default> List sort(List unsorted) { + return Arrays.asList(sort(unsorted.toArray((T[]) new Comparable[unsorted.size()]))); } } diff --git a/src/main/java/com/thealgorithms/sorts/SortUtils.java b/src/main/java/com/thealgorithms/sorts/SortUtils.java index 5f3563fb..9e114b20 100644 --- a/src/main/java/com/thealgorithms/sorts/SortUtils.java +++ b/src/main/java/com/thealgorithms/sorts/SortUtils.java @@ -59,9 +59,7 @@ final class SortUtils { * @param listToPrint the list to print */ static void print(List listToPrint) { - String result = listToPrint.stream() - .map(Object::toString) - .collect(Collectors.joining(" ")); + String result = listToPrint.stream().map(Object::toString).collect(Collectors.joining(" ")); System.out.println(result); } diff --git a/src/main/java/com/thealgorithms/sorts/SortUtilsRandomGenerator.java b/src/main/java/com/thealgorithms/sorts/SortUtilsRandomGenerator.java index 2e2561e8..e75b8e1e 100644 --- a/src/main/java/com/thealgorithms/sorts/SortUtilsRandomGenerator.java +++ b/src/main/java/com/thealgorithms/sorts/SortUtilsRandomGenerator.java @@ -12,7 +12,6 @@ public class SortUtilsRandomGenerator { random = new Random(seed); } - /** * Function to generate array of double values, with predefined size. * @@ -21,8 +20,7 @@ public class SortUtilsRandomGenerator { */ public static Double[] generateArray(int size) { Double[] arr = new Double[size]; - for (int i = 0; i < size; i++) - arr[i] = generateDouble(); + for (int i = 0; i < size; i++) arr[i] = generateDouble(); return arr; } @@ -43,5 +41,4 @@ public class SortUtilsRandomGenerator { public static int generateInt(int n) { return random.nextInt(n); } - } diff --git a/src/main/java/com/thealgorithms/sorts/StoogeSort.java b/src/main/java/com/thealgorithms/sorts/StoogeSort.java index 0089eaed..330f9752 100644 --- a/src/main/java/com/thealgorithms/sorts/StoogeSort.java +++ b/src/main/java/com/thealgorithms/sorts/StoogeSort.java @@ -12,11 +12,7 @@ public class StoogeSort implements SortAlgorithm { return unsortedArray; } - public > T[] sort( - T[] unsortedArray, - int start, - int end - ) { + public > T[] sort(T[] unsortedArray, int start, int end) { if (SortUtils.less(unsortedArray[end - 1], unsortedArray[start])) { T temp = unsortedArray[start]; unsortedArray[start] = unsortedArray[end - 1]; @@ -36,7 +32,7 @@ public class StoogeSort implements SortAlgorithm { public static void main(String[] args) { StoogeSort stoogeSort = new StoogeSort(); - Integer[] integerArray = { 8, 84, 53, 953, 64, 2, 202 }; + Integer[] integerArray = {8, 84, 53, 953, 64, 2, 202}; // Print integerArray unsorted SortUtils.print(integerArray); @@ -44,7 +40,7 @@ public class StoogeSort implements SortAlgorithm { // Print integerArray sorted SortUtils.print(integerArray); - String[] stringArray = { "g", "d", "a", "b", "f", "c", "e" }; + String[] stringArray = {"g", "d", "a", "b", "f", "c", "e"}; // Print stringArray unsorted SortUtils.print(stringArray); diff --git a/src/main/java/com/thealgorithms/sorts/StrandSort.java b/src/main/java/com/thealgorithms/sorts/StrandSort.java index 3e7b02f2..87489b8d 100644 --- a/src/main/java/com/thealgorithms/sorts/StrandSort.java +++ b/src/main/java/com/thealgorithms/sorts/StrandSort.java @@ -6,19 +6,17 @@ import java.util.LinkedList; public class StrandSort { // note: the input list is destroyed - public static > LinkedList strandSort( - LinkedList list - ) { + public static > LinkedList strandSort(LinkedList list) { if (list.size() <= 1) return list; LinkedList result = new LinkedList(); while (list.size() > 0) { LinkedList sorted = new LinkedList(); - sorted.add(list.removeFirst()); //same as remove() or remove(0) + sorted.add(list.removeFirst()); // same as remove() or remove(0) for (Iterator it = list.iterator(); it.hasNext();) { E elem = it.next(); if (sorted.peekLast().compareTo(elem) <= 0) { - sorted.addLast(elem); //same as add(elem) or add(0, elem) + sorted.addLast(elem); // same as add(elem) or add(0, elem) it.remove(); } } @@ -28,15 +26,14 @@ public class StrandSort { } private static > LinkedList merge( - LinkedList left, - LinkedList right - ) { + LinkedList left, LinkedList right) { LinkedList result = new LinkedList(); while (!left.isEmpty() && !right.isEmpty()) { - //change the direction of this comparison to change the direction of the sort - if (left.peek().compareTo(right.peek()) <= 0) result.add( - left.remove() - ); else result.add(right.remove()); + // change the direction of this comparison to change the direction of the sort + if (left.peek().compareTo(right.peek()) <= 0) + result.add(left.remove()); + else + result.add(right.remove()); } result.addAll(left); result.addAll(right); diff --git a/src/main/java/com/thealgorithms/sorts/SwapSort.java b/src/main/java/com/thealgorithms/sorts/SwapSort.java index 718de04e..a626e511 100644 --- a/src/main/java/com/thealgorithms/sorts/SwapSort.java +++ b/src/main/java/com/thealgorithms/sorts/SwapSort.java @@ -17,8 +17,7 @@ public class SwapSort implements SortAlgorithm { int index = 0; while (index < LENGTH - 1) { - int amountSmallerElements = - this.getSmallerElementCount(array, index); + int amountSmallerElements = this.getSmallerElementCount(array, index); if (amountSmallerElements > 0 && index != amountSmallerElements) { T element = array[index]; @@ -32,10 +31,7 @@ public class SwapSort implements SortAlgorithm { return array; } - private > int getSmallerElementCount( - T[] array, - int index - ) { + private > int getSmallerElementCount(T[] array, int index) { int counter = 0; for (int i = 0; i < array.length; i++) { if (less(array[i], array[index])) { @@ -48,7 +44,7 @@ public class SwapSort implements SortAlgorithm { public static void main(String[] args) { // ==== Int ======= - Integer[] a = { 3, 7, 45, 1, 33, 5, 2, 9 }; + Integer[] a = {3, 7, 45, 1, 33, 5, 2, 9}; System.out.print("unsorted: "); print(a); System.out.println(); diff --git a/src/main/java/com/thealgorithms/sorts/TimSort.java b/src/main/java/com/thealgorithms/sorts/TimSort.java index 41337bc5..be7eaa27 100644 --- a/src/main/java/com/thealgorithms/sorts/TimSort.java +++ b/src/main/java/com/thealgorithms/sorts/TimSort.java @@ -9,8 +9,7 @@ import static com.thealgorithms.sorts.SortUtils.less; */ class TimSort implements SortAlgorithm { private static final int SUB_ARRAY_SIZE = 32; - @SuppressWarnings("rawtypes") - private static Comparable[] aux; + @SuppressWarnings("rawtypes") private static Comparable[] aux; @Override public > T[] sort(T[] a) { @@ -48,5 +47,4 @@ class TimSort implements SortAlgorithm { } } } - } diff --git a/src/main/java/com/thealgorithms/sorts/TopologicalSort.java b/src/main/java/com/thealgorithms/sorts/TopologicalSort.java index b72a3d77..947e158a 100644 --- a/src/main/java/com/thealgorithms/sorts/TopologicalSort.java +++ b/src/main/java/com/thealgorithms/sorts/TopologicalSort.java @@ -79,20 +79,14 @@ public class TopologicalSort { * */ public void addEdge(String label, String... next) { adj.put(label, new Vertex(label)); - if (!next[0].isEmpty()) Collections.addAll( - adj.get(label).next, - next - ); + if (!next[0].isEmpty()) Collections.addAll(adj.get(label).next, next); } } static class BackEdgeException extends RuntimeException { public BackEdgeException(String backEdge) { - super( - "This graph contains a cycle. No linear ordering is possible. " + - backEdge - ); + super("This graph contains a cycle. No linear ordering is possible. " + backEdge); } } @@ -144,24 +138,20 @@ public class TopologicalSort { time++; u.weight = time; u.color = Color.GRAY; - graph.adj - .get(u.label) - .next.forEach(label -> { - if (graph.adj.get(label).color == Color.WHITE) { - graph.adj.get(label).predecessor = u; - list.addFirst(sort(graph, graph.adj.get(label), list)); - } else if (graph.adj.get(label).color == Color.GRAY) { - /* - * A back edge exists if an edge (u, v) connects a vertex u to its ancestor vertex v - * in a depth first tree. If v.d ≤ u.d < u.f ≤ v.f - * - * In many cases, we will not know u.f, but v.color denotes the type of edge - * */ - throw new BackEdgeException( - "Back edge: " + u.label + " -> " + label - ); - } - }); + graph.adj.get(u.label).next.forEach(label -> { + if (graph.adj.get(label).color == Color.WHITE) { + graph.adj.get(label).predecessor = u; + list.addFirst(sort(graph, graph.adj.get(label), list)); + } else if (graph.adj.get(label).color == Color.GRAY) { + /* + * A back edge exists if an edge (u, v) connects a vertex u to its ancestor vertex v + * in a depth first tree. If v.d ≤ u.d < u.f ≤ v.f + * + * In many cases, we will not know u.f, but v.color denotes the type of edge + * */ + throw new BackEdgeException("Back edge: " + u.label + " -> " + label); + } + }); u.color = Color.BLACK; time++; u.finished = time; diff --git a/src/main/java/com/thealgorithms/sorts/TreeSort.java b/src/main/java/com/thealgorithms/sorts/TreeSort.java index 78f23378..be95d643 100644 --- a/src/main/java/com/thealgorithms/sorts/TreeSort.java +++ b/src/main/java/com/thealgorithms/sorts/TreeSort.java @@ -51,9 +51,7 @@ public class TreeSort implements SortAlgorithm { return unsortedArray; } - private > List doTreeSortList( - List unsortedList - ) { + private > List doTreeSortList(List unsortedList) { // create a generic BST tree BSTRecursiveGeneric tree = new BSTRecursiveGeneric(); @@ -71,7 +69,7 @@ public class TreeSort implements SortAlgorithm { // ==== Integer Array ======= System.out.println("Testing for Integer Array...."); - Integer[] a = { 3, -7, 45, 1, 343, -5, 2, 9 }; + Integer[] a = {3, -7, 45, 1, 343, -5, 2, 9}; System.out.printf("%-10s", "unsorted: "); print(a); a = treeSort.sort(a); @@ -111,15 +109,7 @@ public class TreeSort implements SortAlgorithm { // ==== String List ======= System.out.println("Testing for String List...."); List stringList = List.of( - "banana", - "berry", - "orange", - "grape", - "peach", - "cherry", - "apple", - "pineapple" - ); + "banana", "berry", "orange", "grape", "peach", "cherry", "apple", "pineapple"); System.out.printf("%-10s", "unsorted: "); print(stringList); stringList = treeSort.sort(stringList); diff --git a/src/main/java/com/thealgorithms/sorts/WiggleSort.java b/src/main/java/com/thealgorithms/sorts/WiggleSort.java index dc05de43..e6f7f10a 100644 --- a/src/main/java/com/thealgorithms/sorts/WiggleSort.java +++ b/src/main/java/com/thealgorithms/sorts/WiggleSort.java @@ -9,9 +9,11 @@ import java.util.Arrays; /** * A wiggle sort implementation based on John L.s' answer in * https://cs.stackexchange.com/questions/125372/how-to-wiggle-sort-an-array-in-linear-time-complexity - * Also have a look at: https://cs.stackexchange.com/questions/125372/how-to-wiggle-sort-an-array-in-linear-time-complexity?noredirect=1&lq=1 - * Not all arrays are wiggle-sortable. This algorithm will find some obviously not wiggle-sortable arrays and throw an error, - * but there are some exceptions that won't be caught, for example [1, 2, 2]. + * Also have a look at: + * https://cs.stackexchange.com/questions/125372/how-to-wiggle-sort-an-array-in-linear-time-complexity?noredirect=1&lq=1 + * Not all arrays are wiggle-sortable. This algorithm will find some obviously not wiggle-sortable + * arrays and throw an error, but there are some exceptions that won't be caught, for example [1, 2, + * 2]. */ public class WiggleSort implements SortAlgorithm { @@ -31,10 +33,7 @@ public class WiggleSort implements SortAlgorithm { * @param median defines the groups * @param extends interface Comparable */ - private > void triColorSort( - T[] sortThis, - T median - ) { + private > void triColorSort(T[] sortThis, T median) { int n = sortThis.length; int i = 0; int j = 0; @@ -54,14 +53,11 @@ public class WiggleSort implements SortAlgorithm { } private > T[] wiggleSort(T[] sortThis) { - // find the median using quickSelect (if the result isn't in the array, use the next greater value) + // find the median using quickSelect (if the result isn't in the array, use the next greater + // value) T median; - median = - select( - Arrays.asList(sortThis), - (int) floor(sortThis.length / 2.0) - ); + median = select(Arrays.asList(sortThis), (int) floor(sortThis.length / 2.0)); int numMedians = 0; @@ -72,22 +68,17 @@ public class WiggleSort implements SortAlgorithm { } // added condition preventing off-by-one errors for odd arrays. // https://cs.stackexchange.com/questions/150886/how-to-find-wiggle-sortable-arrays-did-i-misunderstand-john-l-s-answer?noredirect=1&lq=1 - if ( - sortThis.length % 2 == 1 && - numMedians == ceil(sortThis.length / 2.0) - ) { + if (sortThis.length % 2 == 1 && numMedians == ceil(sortThis.length / 2.0)) { T smallestValue = select(Arrays.asList(sortThis), 0); if (!(0 == smallestValue.compareTo(median))) { throw new IllegalArgumentException( - "For odd Arrays if the median appears ceil(n/2) times, " + - "the median has to be the smallest values in the array." - ); + "For odd Arrays if the median appears ceil(n/2) times, " + + "the median has to be the smallest values in the array."); } } if (numMedians > ceil(sortThis.length / 2.0)) { throw new IllegalArgumentException( - "No more than half the number of values may be the same." - ); + "No more than half the number of values may be the same."); } triColorSort(sortThis, median); diff --git a/src/main/java/com/thealgorithms/strings/Alphabetical.java b/src/main/java/com/thealgorithms/strings/Alphabetical.java index 09d533ea..fde17c88 100644 --- a/src/main/java/com/thealgorithms/strings/Alphabetical.java +++ b/src/main/java/com/thealgorithms/strings/Alphabetical.java @@ -25,10 +25,7 @@ class Alphabetical { 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)) - ) { + if (!Character.isLetter(s.charAt(i)) || !(s.charAt(i) <= s.charAt(i + 1))) { return false; } } diff --git a/src/main/java/com/thealgorithms/strings/Anagrams.java b/src/main/java/com/thealgorithms/strings/Anagrams.java index 33ea900e..dcfc2f85 100644 --- a/src/main/java/com/thealgorithms/strings/Anagrams.java +++ b/src/main/java/com/thealgorithms/strings/Anagrams.java @@ -12,24 +12,21 @@ import java.util.HashMap; */ public class Anagrams { - // 4 approaches are provided for anagram checking. approach 2 and approach 3 are similar but differ in running time. + // 4 approaches are provided for anagram checking. approach 2 and approach 3 are similar but + // differ in running time. public static void main(String[] args) { String first = "deal"; String second = "lead"; // All the below methods takes input but doesn't return any output to the main method. Anagrams nm = new Anagrams(); System.out.println( - nm.approach2(first, second) - );/* To activate methods for different approaches*/ + nm.approach2(first, second)); /* To activate methods for different approaches*/ System.out.println( - nm.approach1(first, second) - );/* To activate methods for different approaches*/ + nm.approach1(first, second)); /* To activate methods for different approaches*/ System.out.println( - nm.approach3(first, second) - );/* To activate methods for different approaches*/ + nm.approach3(first, second)); /* To activate methods for different approaches*/ System.out.println( - nm.approach4(first, second) - );/* To activate methods for different approaches*/ + nm.approach4(first, second)); /* To activate methods for different approaches*/ /** * OUTPUT : * first string ="deal" second string ="lead" @@ -55,9 +52,9 @@ public class Anagrams { char[] c = s.toCharArray(); char[] d = t.toCharArray(); Arrays.sort(c); - Arrays.sort( - d - );/* In this approach the strings are stored in the character arrays and both the arrays are sorted. After that both the arrays are compared for checking anangram */ + Arrays.sort(d); /* In this approach the strings are stored in the character arrays and + both the arrays are sorted. After that both the arrays are compared + for checking anangram */ return Arrays.equals(c, d); } @@ -72,8 +69,10 @@ public class Anagrams { for (char c : a.toCharArray()) { m[c - 'a']++; } - // In this approach the frequency of both the strings are stored and after that the frequencies are iterated from 0 to 26(from 'a' to 'z' ). If the frequencies match then anagram message is displayed in the form of boolean format - // Running time and space complexity of this algo is less as compared to others + // In this approach the frequency of both the strings are stored and after that the + // frequencies are iterated from 0 to 26(from 'a' to 'z' ). If the frequencies match + // then anagram message is displayed in the form of boolean format Running time and + // space complexity of this algo is less as compared to others for (char c : b.toCharArray()) { n[c - 'a']++; } @@ -90,7 +89,8 @@ public class Anagrams { if (s.length() != t.length()) { return false; } - // this is similar to approach number 2 but here the string is not converted to character array + // this is similar to approach number 2 but here the string is not converted to character + // array else { int[] a = new int[26]; int[] b = new int[26]; @@ -110,7 +110,9 @@ public class Anagrams { if (s.length() != t.length()) { return false; } - // This approach is done using hashmap where frequencies are stored and checked iteratively and if all the frequencies of first string match with the second string then anagram message is displayed in boolean format + // This approach is done using hashmap where frequencies are stored and checked iteratively + // and if all the frequencies of first string match with the second string then anagram + // message is displayed in boolean format else { HashMap nm = new HashMap<>(); HashMap kk = new HashMap<>(); @@ -126,22 +128,25 @@ public class Anagrams { } boolean approach5(String s, String t) { - if(s.length() != t.length()){ + if (s.length() != t.length()) { return false; } - // Approach is different from above 4 aproaches. - // Here we initialize an array of size 26 where each element corresponds to the frequency of a character. + // Approach is different from above 4 aproaches. + // Here we initialize an array of size 26 where each element corresponds to the frequency of + // a character. int[] freq = new int[26]; - // iterate through both strings, incrementing the frequency of each character in the first string and decrementing the frequency of each character in the second string. - for(int i=0; i VOWELS = new HashSet<>( - Arrays.asList('a', 'e', 'i', 'o', 'u') - ); + private static final Set VOWELS + = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u')); /** * Check if a string is has vowels or not diff --git a/src/main/java/com/thealgorithms/strings/HammingDistance.java b/src/main/java/com/thealgorithms/strings/HammingDistance.java index a6f6db19..bfa3114b 100644 --- a/src/main/java/com/thealgorithms/strings/HammingDistance.java +++ b/src/main/java/com/thealgorithms/strings/HammingDistance.java @@ -1,7 +1,7 @@ package com.thealgorithms.strings; -/* In information theory, the Hamming distance between two strings of equal length -is the number of positions at which the corresponding symbols are different. +/* In information theory, the Hamming distance between two strings of equal length +is the number of positions at which the corresponding symbols are different. https://en.wikipedia.org/wiki/Hamming_distance */ public class HammingDistance { @@ -14,8 +14,7 @@ public class HammingDistance { * @return {@code int} hamming distance * @throws Exception */ - public static int calculateHammingDistance(String s1, String s2) - throws Exception { + public static int calculateHammingDistance(String s1, String s2) throws Exception { if (s1.length() != s2.length()) { throw new Exception("String lengths must be equal"); } diff --git a/src/main/java/com/thealgorithms/strings/HorspoolSearch.java b/src/main/java/com/thealgorithms/strings/HorspoolSearch.java index 9ac0d50c..aa318d87 100644 --- a/src/main/java/com/thealgorithms/strings/HorspoolSearch.java +++ b/src/main/java/com/thealgorithms/strings/HorspoolSearch.java @@ -92,11 +92,7 @@ public class HorspoolSearch { * @param text text String * @return index of first occurrence of the pattern in the text */ - private static int firstOccurrence( - String pattern, - String text, - boolean caseSensitive - ) { + private static int firstOccurrence(String pattern, String text, boolean caseSensitive) { shiftValues = calcShiftValues(pattern); // build the bad symbol table comparisons = 0; // reset comparisons @@ -104,7 +100,8 @@ public class HorspoolSearch { return -1; } - int textIndex = pattern.length() - 1; // align pattern with text start and get index of the last character + int textIndex = pattern.length() + - 1; // align pattern with text start and get index of the last character // while pattern is not out of text bounds while (textIndex < text.length()) { @@ -113,10 +110,9 @@ public class HorspoolSearch { while (i >= 0) { comparisons++; char patternChar = pattern.charAt(i); - char textChar = text.charAt( - (textIndex + i) - (pattern.length() - 1) - ); - if (!charEquals(patternChar, textChar, caseSensitive)) { // bad character, shift pattern + char textChar = text.charAt((textIndex + i) - (pattern.length() - 1)); + if (!charEquals( + patternChar, textChar, caseSensitive)) { // bad character, shift pattern textIndex += getShiftValue(text.charAt(textIndex)); break; } @@ -163,7 +159,8 @@ public class HorspoolSearch { patternLength = pattern.length(); HashMap table = new HashMap<>(); - for (int i = pattern.length() - 2; i >= 0; i--) { // length - 2 is the index of the second to last character + for (int i = pattern.length() - 2; i >= 0; + i--) { // length - 2 is the index of the second to last character char c = pattern.charAt(i); int finalI = i; table.computeIfAbsent(c, k -> pattern.length() - 1 - finalI); diff --git a/src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java b/src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java index fcdc310d..7ad9971e 100644 --- a/src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java +++ b/src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java @@ -15,8 +15,7 @@ public class LetterCombinationsOfPhoneNumber { for (int i = 0; i < numberToCharMap[numbers[numIndex]].length; i++) { String sCopy = String.copyValueOf(s.toCharArray()); - sCopy = - sCopy.concat(numberToCharMap[numbers[numIndex]][i].toString()); + sCopy = sCopy.concat(numberToCharMap[numbers[numIndex]][i].toString()); stringList.addAll(printWords(numbers, len, numIndex + 1, sCopy)); } return stringList; @@ -30,21 +29,21 @@ public class LetterCombinationsOfPhoneNumber { protected static void generateNumberToCharMap() { numberToCharMap = new Character[10][5]; - numberToCharMap[0] = new Character[] { '\0' }; - numberToCharMap[1] = new Character[] { '\0' }; - numberToCharMap[2] = new Character[] { 'a', 'b', 'c' }; - numberToCharMap[3] = new Character[] { 'd', 'e', 'f' }; - numberToCharMap[4] = new Character[] { 'g', 'h', 'i' }; - numberToCharMap[5] = new Character[] { 'j', 'k', 'l' }; - numberToCharMap[6] = new Character[] { 'm', 'n', 'o' }; - numberToCharMap[7] = new Character[] { 'p', 'q', 'r', 's' }; - numberToCharMap[8] = new Character[] { 't', 'u', 'v' }; - numberToCharMap[9] = new Character[] { 'w', 'x', 'y', 'z' }; + numberToCharMap[0] = new Character[] {'\0'}; + numberToCharMap[1] = new Character[] {'\0'}; + numberToCharMap[2] = new Character[] {'a', 'b', 'c'}; + numberToCharMap[3] = new Character[] {'d', 'e', 'f'}; + numberToCharMap[4] = new Character[] {'g', 'h', 'i'}; + numberToCharMap[5] = new Character[] {'j', 'k', 'l'}; + numberToCharMap[6] = new Character[] {'m', 'n', 'o'}; + numberToCharMap[7] = new Character[] {'p', 'q', 'r', 's'}; + numberToCharMap[8] = new Character[] {'t', 'u', 'v'}; + numberToCharMap[9] = new Character[] {'w', 'x', 'y', 'z'}; } // Driver code public static void main(String[] args) { - int[] number = { 2, 3, 4 }; + int[] number = {2, 3, 4}; printWords(number); } } diff --git a/src/main/java/com/thealgorithms/strings/LongestPalindromicSubstring.java b/src/main/java/com/thealgorithms/strings/LongestPalindromicSubstring.java index 8ebff857..6efdabce 100644 --- a/src/main/java/com/thealgorithms/strings/LongestPalindromicSubstring.java +++ b/src/main/java/com/thealgorithms/strings/LongestPalindromicSubstring.java @@ -11,9 +11,7 @@ class LongestPalindromicSubstring { Scanner sc = new Scanner(System.in); System.out.print("Enter the string: "); str = sc.nextLine(); - System.out.println( - "Longest substring is : " + s.longestPalindrome(str) - ); + System.out.println("Longest substring is : " + s.longestPalindrome(str)); } } diff --git a/src/main/java/com/thealgorithms/strings/Lower.java b/src/main/java/com/thealgorithms/strings/Lower.java index c5288d1a..ef3902b1 100644 --- a/src/main/java/com/thealgorithms/strings/Lower.java +++ b/src/main/java/com/thealgorithms/strings/Lower.java @@ -6,7 +6,7 @@ public class Lower { * Driver Code */ public static void main(String[] args) { - String[] strings = { "ABC", "ABC123", "abcABC", "abc123ABC" }; + String[] strings = {"ABC", "ABC123", "abcABC", "abc123ABC"}; for (String s : strings) { assert toLowerCase(s).equals(s.toLowerCase()); } @@ -21,10 +21,7 @@ public class Lower { 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]) - ) { + if (Character.isLetter(values[i]) && Character.isUpperCase(values[i])) { values[i] = Character.toLowerCase(values[i]); } } diff --git a/src/main/java/com/thealgorithms/strings/MyAtoi.java b/src/main/java/com/thealgorithms/strings/MyAtoi.java index 327cc4c1..a8669273 100644 --- a/src/main/java/com/thealgorithms/strings/MyAtoi.java +++ b/src/main/java/com/thealgorithms/strings/MyAtoi.java @@ -1,9 +1,10 @@ -// Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). Here is my implementation +// Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer +// (similar to C/C++'s atoi function). Here is my implementation package com.thealgorithms.strings; public class MyAtoi { -public static int myAtoi(String s) { + public static int myAtoi(String s) { s = s.trim(); char[] char_1 = s.toCharArray(); String number = ""; @@ -22,8 +23,7 @@ public static int myAtoi(String s) { number = "0"; break; } - if(ch >= '0' && ch <= '9') - number += ch; + if (ch >= '0' && ch <= '9') number += ch; } else if (ch == '-' && !isDigit) { number += "0"; negative = true; @@ -40,15 +40,14 @@ public static int myAtoi(String s) { break; } } - - if (!isDigit) { + + if (!isDigit) { return 0; } - - number = number.replaceFirst("^0+(?!$)", ""); - - - if (number.length() > 10 && negative) { + + number = number.replaceFirst("^0+(?!$)", ""); + + if (number.length() > 10 && negative) { return -2147483648; } else if (number.length() > 10) { return 2147483647; @@ -64,9 +63,9 @@ public static int myAtoi(String s) { } } - if(negative){ - return Integer.parseInt(number)*-1; - } + if (negative) { + return Integer.parseInt(number) * -1; + } return Integer.parseInt(number); } diff --git a/src/main/java/com/thealgorithms/strings/Palindrome.java b/src/main/java/com/thealgorithms/strings/Palindrome.java index 0046e545..cfc4efd1 100644 --- a/src/main/java/com/thealgorithms/strings/Palindrome.java +++ b/src/main/java/com/thealgorithms/strings/Palindrome.java @@ -14,9 +14,7 @@ class Palindrome { */ public static boolean isPalindrome(String s) { return ( - (s == null || s.length() <= 1) || - s.equals(new StringBuilder(s).reverse().toString()) - ); + (s == null || s.length() <= 1) || s.equals(new StringBuilder(s).reverse().toString())); } /** diff --git a/src/main/java/com/thealgorithms/strings/Pangram.java b/src/main/java/com/thealgorithms/strings/Pangram.java index 71924e0b..4772ac82 100644 --- a/src/main/java/com/thealgorithms/strings/Pangram.java +++ b/src/main/java/com/thealgorithms/strings/Pangram.java @@ -36,7 +36,7 @@ public class Pangram { } return true; } - + /** * Checks if a String is Pangram or not by checking if each alhpabet is present or not * diff --git a/src/main/java/com/thealgorithms/strings/PermuteString.java b/src/main/java/com/thealgorithms/strings/PermuteString.java index b7705c9b..d4abb674 100644 --- a/src/main/java/com/thealgorithms/strings/PermuteString.java +++ b/src/main/java/com/thealgorithms/strings/PermuteString.java @@ -7,13 +7,13 @@ Backtracking algorithm used in the program:- Like in ABC, in the first iteration three strings are formed: ABC, BAC, and CBA by swapping A with A, B and C respectively. >>Repeat step 1 for the rest of the characters like fixing second character B and so on. ->>Now swap again to go back to the previous position. E.g., from ABC, we formed ABC by fixing B again, - and we backtrack to the previous position and swap B with C. So, now we got ABC and ACB. +>>Now swap again to go back to the previous position. E.g., from ABC, we formed ABC by fixing B +again, and we backtrack to the previous position and swap B with C. So, now we got ABC and ACB. >>Repeat these steps for BAC and CBA, to get all the permutations. */ public class PermuteString { - //Function for swapping the characters at position I with character at position j + // Function for swapping the characters at position I with character at position j public static String swapString(String a, int i, int j) { char[] b = a.toCharArray(); char ch; @@ -30,18 +30,18 @@ public class PermuteString { generatePermutation(str, 0, len); } - //Function for generating different permutations of the string + // Function for generating different permutations of the string public static void generatePermutation(String str, int start, int end) { - //Prints the permutations + // Prints the permutations if (start == end - 1) { System.out.println(str); } else { for (int i = start; i < end; i++) { - //Swapping the string by fixing a character + // Swapping the string by fixing a character str = swapString(str, start, i); - //Recursively calling function generatePermutation() for rest of the characters + // Recursively calling function generatePermutation() for rest of the characters generatePermutation(str, start + 1, end); - //Backtracking and swapping the characters again. + // Backtracking and swapping the characters again. str = swapString(str, start, i); } } diff --git a/src/main/java/com/thealgorithms/strings/ReverseStringRecursive.java b/src/main/java/com/thealgorithms/strings/ReverseStringRecursive.java index 95833220..0cd2a971 100644 --- a/src/main/java/com/thealgorithms/strings/ReverseStringRecursive.java +++ b/src/main/java/com/thealgorithms/strings/ReverseStringRecursive.java @@ -9,12 +9,11 @@ public class ReverseStringRecursive { * @param str string to be reversed * @return reversed string */ - public static String reverse(String str) - { - if(str.isEmpty()){ + public static String reverse(String str) { + if (str.isEmpty()) { return str; } else { - return reverse(str.substring(1))+str.charAt(0); + return reverse(str.substring(1)) + str.charAt(0); } } } diff --git a/src/main/java/com/thealgorithms/strings/StringCompression.java b/src/main/java/com/thealgorithms/strings/StringCompression.java index 0d209f88..9e8f31d2 100644 --- a/src/main/java/com/thealgorithms/strings/StringCompression.java +++ b/src/main/java/com/thealgorithms/strings/StringCompression.java @@ -1,60 +1,62 @@ package com.thealgorithms.strings; /* References : https://en.wikipedia.org/wiki/Run-length_encoding - * String compression algorithm deals with encoding the string, that is, shortening the size of the string + * String compression algorithm deals with encoding the string, that is, shortening the size of the + * string * @author Swarga-codes (https://github.com/Swarga-codes) -*/ + */ public class StringCompression { - /** - * Returns the compressed or encoded string - * - * @param ch character array that contains the group of characters to be encoded - * @return the compressed character array as string - */ - public static String compress(String input) { - // Keeping the count as 1 since every element present will have atleast a count - // of 1 - int count = 1; - String compressedString = ""; - // Base condition to check whether the array is of size 1, if it is then we - // return the array - if (input.length() == 1) { - return "" + input.charAt(0); - } - // If the array has a length greater than 1 we move into this loop - for (int i = 0; i < input.length() - 1; i++) { - // here we check for similarity of the adjacent elements and change the count - // accordingly - if (input.charAt(i) == input.charAt(i + 1)) { - count = count + 1; - } - if ((i + 1) == input.length() - 1 && input.charAt(i + 1) == input.charAt(i)) { - compressedString = appendCount(compressedString, count, input.charAt(i)); - break; - } else if (input.charAt(i) != input.charAt(i+1)) { - if ((i + 1) == input.length() - 1) { - compressedString = appendCount(compressedString, count, input.charAt(i)) + input.charAt(i+1); - break; - } else { - compressedString = appendCount(compressedString, count, input.charAt(i)); - count = 1; + /** + * Returns the compressed or encoded string + * + * @param ch character array that contains the group of characters to be encoded + * @return the compressed character array as string + */ + public static String compress(String input) { + // Keeping the count as 1 since every element present will have atleast a count + // of 1 + int count = 1; + String compressedString = ""; + // Base condition to check whether the array is of size 1, if it is then we + // return the array + if (input.length() == 1) { + return "" + input.charAt(0); } - } + // If the array has a length greater than 1 we move into this loop + for (int i = 0; i < input.length() - 1; i++) { + // here we check for similarity of the adjacent elements and change the count + // accordingly + if (input.charAt(i) == input.charAt(i + 1)) { + count = count + 1; + } + if ((i + 1) == input.length() - 1 && input.charAt(i + 1) == input.charAt(i)) { + compressedString = appendCount(compressedString, count, input.charAt(i)); + break; + } else if (input.charAt(i) != input.charAt(i + 1)) { + if ((i + 1) == input.length() - 1) { + compressedString = appendCount(compressedString, count, input.charAt(i)) + + input.charAt(i + 1); + break; + } else { + compressedString = appendCount(compressedString, count, input.charAt(i)); + count = 1; + } + } + } + return compressedString; } - return compressedString; - } - /** - * @param res the resulting string - * @param count current count - * @param ch the character at a particular index - * @return the res string appended with the count - */ - public static String appendCount(String res, int count, char ch) { - if (count > 1) { - res += ch + "" + count; - count = 1; - } else { - res += ch + ""; + /** + * @param res the resulting string + * @param count current count + * @param ch the character at a particular index + * @return the res string appended with the count + */ + public static String appendCount(String res, int count, char ch) { + if (count > 1) { + res += ch + "" + count; + count = 1; + } else { + res += ch + ""; + } + return res; } - return res; - } } \ No newline at end of file diff --git a/src/main/java/com/thealgorithms/strings/Upper.java b/src/main/java/com/thealgorithms/strings/Upper.java index 35558462..8f306a20 100644 --- a/src/main/java/com/thealgorithms/strings/Upper.java +++ b/src/main/java/com/thealgorithms/strings/Upper.java @@ -6,7 +6,7 @@ public class Upper { * Driver Code */ public static void main(String[] args) { - String[] strings = { "ABC", "ABC123", "abcABC", "abc123ABC" }; + String[] strings = {"ABC", "ABC123", "abcABC", "abc123ABC"}; for (String s : strings) { assert toUpperCase(s).equals(s.toUpperCase()); } @@ -24,10 +24,7 @@ public class Upper { } char[] values = s.toCharArray(); for (int i = 0; i < values.length; ++i) { - if ( - Character.isLetter(values[i]) && - Character.isLowerCase(values[i]) - ) { + if (Character.isLetter(values[i]) && Character.isLowerCase(values[i])) { values[i] = Character.toUpperCase(values[i]); } } diff --git a/src/main/java/com/thealgorithms/strings/ValidParentheses.java b/src/main/java/com/thealgorithms/strings/ValidParentheses.java index e2b0f8e9..5d373852 100644 --- a/src/main/java/com/thealgorithms/strings/ValidParentheses.java +++ b/src/main/java/com/thealgorithms/strings/ValidParentheses.java @@ -1,33 +1,31 @@ package com.thealgorithms.strings; -// Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. -// An input string is valid if: -// Open brackets must be closed by the same type of brackets. -// Open brackets must be closed in the correct order. -// Every close bracket has a corresponding open bracket of the same type. - +// Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine +// if the input string is valid. An input string is valid if: Open brackets must be closed by +// the same type of brackets. Open brackets must be closed in the correct order. Every close +// bracket has a corresponding open bracket of the same type. public class ValidParentheses { - public static boolean isValid(String s) { - char[] stack = new char[s.length()]; - int head = 0; - for(char c : s.toCharArray()) { - switch(c) { - case '{': - case '[': - case '(': - stack[head++] = c; - break; - case '}': - if(head == 0 || stack[--head] != '{') return false; - break; - case ')': - if(head == 0 || stack[--head] != '(') return false; - break; - case ']': - if(head == 0 || stack[--head] != '[') return false; - break; - } - } - return head == 0; - } + public static boolean isValid(String s) { + char[] stack = new char[s.length()]; + int head = 0; + for (char c : s.toCharArray()) { + switch (c) { + case '{': + case '[': + case '(': + stack[head++] = c; + break; + case '}': + if (head == 0 || stack[--head] != '{') return false; + break; + case ')': + if (head == 0 || stack[--head] != '(') return false; + break; + case ']': + if (head == 0 || stack[--head] != '[') return false; + break; + } + } + return head == 0; + } } diff --git a/src/main/java/com/thealgorithms/strings/WordLadder.java b/src/main/java/com/thealgorithms/strings/WordLadder.java index c4d8aeb9..edeb7036 100644 --- a/src/main/java/com/thealgorithms/strings/WordLadder.java +++ b/src/main/java/com/thealgorithms/strings/WordLadder.java @@ -8,22 +8,26 @@ import java.util.Queue; /* **Problem Statement:** - A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: + A transformation sequence from word beginWord to word endWord using a dictionary wordList is a + sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: Every adjacent pair of words differs by a single letter. Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList. sk == endWord - Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists. + Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in + the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists. **Example 1:** Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] - Output: 5 - Explanation: One shortest transformation sequence is "hit" -> "hot" -> "dot" -> "dog" -> cog", which is 5 words long. + Output: 5 + Explanation: One shortest transformation sequence is "hit" -> "hot" -> "dot" -> "dog" -> cog", + which is 5 words long. **Example 2:** Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"] Output: 0 - Explanation: The endWord "cog" is not in wordList, therefore there is no valid transformation sequence. + Explanation: The endWord "cog" is not in wordList, therefore there is no valid transformation + sequence. **Constraints:** 1 <= beginWord.length <= 10 diff --git a/src/main/java/com/thealgorithms/strings/longestNonRepeativeSubstring.java b/src/main/java/com/thealgorithms/strings/longestNonRepeativeSubstring.java index 7549dd2a..252517dc 100644 --- a/src/main/java/com/thealgorithms/strings/longestNonRepeativeSubstring.java +++ b/src/main/java/com/thealgorithms/strings/longestNonRepeativeSubstring.java @@ -14,7 +14,8 @@ class longestNonRepeativeSubstring { // adding key to map if not present if (!map.containsKey(temp)) map.put(temp, 0); // checking if the first value is the dublicate value - else if (s.charAt(start) == temp) start++; + else if (s.charAt(start) == temp) + start++; // checking if the previous value is dublicate value else if (s.charAt(i - 1) == temp) { if (max < map.size()) max = map.size(); diff --git a/src/main/java/com/thealgorithms/strings/zigZagPattern/zigZagPattern.java b/src/main/java/com/thealgorithms/strings/zigZagPattern/zigZagPattern.java index a1d67614..cc6654c1 100644 --- a/src/main/java/com/thealgorithms/strings/zigZagPattern/zigZagPattern.java +++ b/src/main/java/com/thealgorithms/strings/zigZagPattern/zigZagPattern.java @@ -7,14 +7,16 @@ class zigZagPattern { int start = 0, index = 0, height = 1, depth = numRows; char[] zigZagedArray = new char[s.length()]; while (depth != 0) { - int pointer = start, height_space = - 2 + ((height - 2) * 2), depth_space = 2 + ((depth - 2) * 2); + int pointer = start, height_space = 2 + ((height - 2) * 2), + depth_space = 2 + ((depth - 2) * 2); boolean bool = true; while (pointer < s.length()) { zigZagedArray[index++] = s.charAt(pointer); - if (height_space == 0) pointer += depth_space; else if ( - depth_space == 0 - ) pointer += height_space; else if (bool) { + if (height_space == 0) + pointer += depth_space; + else if (depth_space == 0) + pointer += height_space; + else if (bool) { pointer += depth_space; bool = false; } else { diff --git a/src/test/java/com/thealgorithms/backtracking/AllPathsFromSourceToTargetTest.java b/src/test/java/com/thealgorithms/backtracking/AllPathsFromSourceToTargetTest.java index 139cd107..b9de924a 100644 --- a/src/test/java/com/thealgorithms/backtracking/AllPathsFromSourceToTargetTest.java +++ b/src/test/java/com/thealgorithms/backtracking/AllPathsFromSourceToTargetTest.java @@ -1,6 +1,7 @@ package com.thealgorithms.backtracking; import static org.junit.jupiter.api.Assertions.*; + import java.util.*; import org.junit.jupiter.api.Test; @@ -9,48 +10,56 @@ public class AllPathsFromSourceToTargetTest { @Test void testForFirstCase() { int vertices = 4; - int[][] a = {{0,1},{0,2},{0,3},{2,0},{2,1},{1,3}}; + int[][] a = {{0, 1}, {0, 2}, {0, 3}, {2, 0}, {2, 1}, {1, 3}}; int source = 2; int destination = 3; - List> list2 = List.of(List.of(2, 0, 1, 3),List.of(2, 0, 3),List.of(2, 1, 3)); - List> list1 = AllPathsFromSourceToTarget.allPathsFromSourceToTarget(vertices,a,source,destination); - list2=list1; + List> list2 + = List.of(List.of(2, 0, 1, 3), List.of(2, 0, 3), List.of(2, 1, 3)); + List> list1 = AllPathsFromSourceToTarget.allPathsFromSourceToTarget( + vertices, a, source, destination); + list2 = list1; assertIterableEquals(list1, list2); } @Test void testForSecondCase() { int vertices = 5; - int[][] a = {{0,1},{0,2},{0,3},{2,0},{2,1},{1,3},{1,4},{3,4},{2,4}}; + int[][] a = {{0, 1}, {0, 2}, {0, 3}, {2, 0}, {2, 1}, {1, 3}, {1, 4}, {3, 4}, {2, 4}}; int source = 0; int destination = 4; - List> list2 = List.of(List.of(0, 1, 3, 4),List.of(0, 1, 4),List.of(0, 2, 1, 3, 4),List.of(0, 2, 1, 4),List.of(0, 2, 4),List.of(0, 3, 4)); - List> list1 = AllPathsFromSourceToTarget.allPathsFromSourceToTarget(vertices,a,source,destination); - list2=list1; + List> list2 = List.of(List.of(0, 1, 3, 4), List.of(0, 1, 4), + List.of(0, 2, 1, 3, 4), List.of(0, 2, 1, 4), List.of(0, 2, 4), List.of(0, 3, 4)); + List> list1 = AllPathsFromSourceToTarget.allPathsFromSourceToTarget( + vertices, a, source, destination); + list2 = list1; assertIterableEquals(list1, list2); } @Test void testForThirdCase() { int vertices = 6; - int[][] a = {{1,0},{2,3},{0,4},{1,5},{4,3},{0,2},{0,3},{1,2},{0,5},{3,4},{2,5},{2,4}}; + int[][] a = {{1, 0}, {2, 3}, {0, 4}, {1, 5}, {4, 3}, {0, 2}, {0, 3}, {1, 2}, {0, 5}, {3, 4}, + {2, 5}, {2, 4}}; int source = 1; int destination = 5; - List> list2 = List.of(List.of(1, 0, 2, 5),List.of(1, 0, 5),List.of(1, 5),List.of(1, 2, 5)); - List> list1 = AllPathsFromSourceToTarget.allPathsFromSourceToTarget(vertices,a,source,destination); - list2=list1; + List> list2 + = List.of(List.of(1, 0, 2, 5), List.of(1, 0, 5), List.of(1, 5), List.of(1, 2, 5)); + List> list1 = AllPathsFromSourceToTarget.allPathsFromSourceToTarget( + vertices, a, source, destination); + list2 = list1; assertIterableEquals(list1, list2); } @Test void testForFourthcase() { int vertices = 3; - int[][] a = {{0,1},{0,2},{1,2}}; + int[][] a = {{0, 1}, {0, 2}, {1, 2}}; int source = 0; int destination = 2; - List> list2 = List.of(List.of(0, 1, 2),List.of(0, 2)); - List> list1 = AllPathsFromSourceToTarget.allPathsFromSourceToTarget(vertices,a,source,destination); - list2=list1; + List> list2 = List.of(List.of(0, 1, 2), List.of(0, 2)); + List> list1 = AllPathsFromSourceToTarget.allPathsFromSourceToTarget( + vertices, a, source, destination); + list2 = list1; assertIterableEquals(list1, list2); } } \ No newline at end of file diff --git a/src/test/java/com/thealgorithms/backtracking/CombinationTest.java b/src/test/java/com/thealgorithms/backtracking/CombinationTest.java index 418383c8..ed614827 100644 --- a/src/test/java/com/thealgorithms/backtracking/CombinationTest.java +++ b/src/test/java/com/thealgorithms/backtracking/CombinationTest.java @@ -10,29 +10,20 @@ public class CombinationTest { @Test void testNoElement() { - List> result = Combination.combination( - new Integer[] { 1, 2 }, - 0 - ); + List> result = Combination.combination(new Integer[] {1, 2}, 0); assertTrue(result == null); } @Test void testLengthOne() { - List> result = Combination.combination( - new Integer[] { 1, 2 }, - 1 - ); + List> result = Combination.combination(new Integer[] {1, 2}, 1); assertTrue(result.get(0).iterator().next() == 1); assertTrue(result.get(1).iterator().next() == 2); } @Test void testLengthTwo() { - List> result = Combination.combination( - new Integer[] { 1, 2 }, - 2 - ); + List> result = Combination.combination(new Integer[] {1, 2}, 2); Integer[] arr = result.get(0).toArray(new Integer[2]); assertTrue(arr[0] == 1); assertTrue(arr[1] == 2); diff --git a/src/test/java/com/thealgorithms/backtracking/FloodFillTest.java b/src/test/java/com/thealgorithms/backtracking/FloodFillTest.java index b46c7e0f..7a59b210 100644 --- a/src/test/java/com/thealgorithms/backtracking/FloodFillTest.java +++ b/src/test/java/com/thealgorithms/backtracking/FloodFillTest.java @@ -17,8 +17,8 @@ class FloodFillTest { @Test void testForSingleElementImage() { - int[][] image = { { 1 } }; - int[][] expected = { { 3 } }; + int[][] image = {{1}}; + int[][] expected = {{3}}; FloodFill.floodFill(image, 0, 0, 3, 1); assertArrayEquals(expected, image); @@ -27,23 +27,23 @@ class FloodFillTest { @Test void testForImageOne() { int[][] image = { - { 0, 0, 0, 0, 0, 0, 0 }, - { 0, 3, 3, 3, 3, 0, 0 }, - { 0, 3, 1, 1, 5, 0, 0 }, - { 0, 3, 1, 1, 5, 5, 3 }, - { 0, 3, 5, 5, 1, 1, 3 }, - { 0, 0, 0, 5, 1, 1, 3 }, - { 0, 0, 0, 3, 3, 3, 3 }, + {0, 0, 0, 0, 0, 0, 0}, + {0, 3, 3, 3, 3, 0, 0}, + {0, 3, 1, 1, 5, 0, 0}, + {0, 3, 1, 1, 5, 5, 3}, + {0, 3, 5, 5, 1, 1, 3}, + {0, 0, 0, 5, 1, 1, 3}, + {0, 0, 0, 3, 3, 3, 3}, }; int[][] expected = { - { 0, 0, 0, 0, 0, 0, 0 }, - { 0, 3, 3, 3, 3, 0, 0 }, - { 0, 3, 2, 2, 5, 0, 0 }, - { 0, 3, 2, 2, 5, 5, 3 }, - { 0, 3, 5, 5, 2, 2, 3 }, - { 0, 0, 0, 5, 2, 2, 3 }, - { 0, 0, 0, 3, 3, 3, 3 }, + {0, 0, 0, 0, 0, 0, 0}, + {0, 3, 3, 3, 3, 0, 0}, + {0, 3, 2, 2, 5, 0, 0}, + {0, 3, 2, 2, 5, 5, 3}, + {0, 3, 5, 5, 2, 2, 3}, + {0, 0, 0, 5, 2, 2, 3}, + {0, 0, 0, 3, 3, 3, 3}, }; FloodFill.floodFill(image, 2, 2, 2, 1); @@ -53,23 +53,23 @@ class FloodFillTest { @Test void testForImageTwo() { int[][] image = { - { 0, 0, 1, 1, 0, 0, 0 }, - { 1, 1, 3, 3, 3, 0, 0 }, - { 1, 3, 1, 1, 5, 0, 0 }, - { 0, 3, 1, 1, 5, 5, 3 }, - { 0, 3, 5, 5, 1, 1, 3 }, - { 0, 0, 0, 5, 1, 1, 3 }, - { 0, 0, 0, 1, 3, 1, 3 }, + {0, 0, 1, 1, 0, 0, 0}, + {1, 1, 3, 3, 3, 0, 0}, + {1, 3, 1, 1, 5, 0, 0}, + {0, 3, 1, 1, 5, 5, 3}, + {0, 3, 5, 5, 1, 1, 3}, + {0, 0, 0, 5, 1, 1, 3}, + {0, 0, 0, 1, 3, 1, 3}, }; int[][] expected = { - { 0, 0, 2, 2, 0, 0, 0 }, - { 2, 2, 3, 3, 3, 0, 0 }, - { 2, 3, 2, 2, 5, 0, 0 }, - { 0, 3, 2, 2, 5, 5, 3 }, - { 0, 3, 5, 5, 2, 2, 3 }, - { 0, 0, 0, 5, 2, 2, 3 }, - { 0, 0, 0, 2, 3, 2, 3 }, + {0, 0, 2, 2, 0, 0, 0}, + {2, 2, 3, 3, 3, 0, 0}, + {2, 3, 2, 2, 5, 0, 0}, + {0, 3, 2, 2, 5, 5, 3}, + {0, 3, 5, 5, 2, 2, 3}, + {0, 0, 0, 5, 2, 2, 3}, + {0, 0, 0, 2, 3, 2, 3}, }; FloodFill.floodFill(image, 2, 2, 2, 1); @@ -79,15 +79,15 @@ class FloodFillTest { @Test void testForImageThree() { int[][] image = { - { 1, 1, 2, 3, 1, 1, 1 }, - { 1, 0, 0, 1, 0, 0, 1 }, - { 1, 1, 1, 0, 3, 1, 2 }, + {1, 1, 2, 3, 1, 1, 1}, + {1, 0, 0, 1, 0, 0, 1}, + {1, 1, 1, 0, 3, 1, 2}, }; int[][] expected = { - { 4, 4, 2, 3, 4, 4, 4 }, - { 4, 0, 0, 4, 0, 0, 4 }, - { 4, 4, 4, 0, 3, 4, 2 }, + {4, 4, 2, 3, 4, 4, 4}, + {4, 0, 0, 4, 0, 0, 4}, + {4, 4, 4, 0, 3, 4, 2}, }; FloodFill.floodFill(image, 0, 1, 4, 1); diff --git a/src/test/java/com/thealgorithms/backtracking/MazeRecursionTest.java b/src/test/java/com/thealgorithms/backtracking/MazeRecursionTest.java index 35f66f92..1464c522 100644 --- a/src/test/java/com/thealgorithms/backtracking/MazeRecursionTest.java +++ b/src/test/java/com/thealgorithms/backtracking/MazeRecursionTest.java @@ -35,7 +35,7 @@ public class MazeRecursionTest { map[3][1] = 1; map[3][2] = 1; - //clone another map for setWay2 method + // clone another map for setWay2 method for (int i = 0; i < map.length; i++) { for (int j = 0; j < map[i].length; j++) { map2[i][j] = map[i][j]; @@ -46,25 +46,25 @@ public class MazeRecursionTest { MazeRecursion.setWay2(map2, 1, 1); int[][] expectedMap = new int[][] { - { 1, 1, 1, 1, 1, 1, 1 }, - { 1, 2, 0, 0, 0, 0, 1 }, - { 1, 2, 2, 2, 0, 0, 1 }, - { 1, 1, 1, 2, 0, 0, 1 }, - { 1, 0, 0, 2, 0, 0, 1 }, - { 1, 0, 0, 2, 0, 0, 1 }, - { 1, 0, 0, 2, 2, 2, 1 }, - { 1, 1, 1, 1, 1, 1, 1 }, + {1, 1, 1, 1, 1, 1, 1}, + {1, 2, 0, 0, 0, 0, 1}, + {1, 2, 2, 2, 0, 0, 1}, + {1, 1, 1, 2, 0, 0, 1}, + {1, 0, 0, 2, 0, 0, 1}, + {1, 0, 0, 2, 0, 0, 1}, + {1, 0, 0, 2, 2, 2, 1}, + {1, 1, 1, 1, 1, 1, 1}, }; int[][] expectedMap2 = new int[][] { - { 1, 1, 1, 1, 1, 1, 1 }, - { 1, 2, 2, 2, 2, 2, 1 }, - { 1, 0, 0, 0, 0, 2, 1 }, - { 1, 1, 1, 0, 0, 2, 1 }, - { 1, 0, 0, 0, 0, 2, 1 }, - { 1, 0, 0, 0, 0, 2, 1 }, - { 1, 0, 0, 0, 0, 2, 1 }, - { 1, 1, 1, 1, 1, 1, 1 }, + {1, 1, 1, 1, 1, 1, 1}, + {1, 2, 2, 2, 2, 2, 1}, + {1, 0, 0, 0, 0, 2, 1}, + {1, 1, 1, 0, 0, 2, 1}, + {1, 0, 0, 0, 0, 2, 1}, + {1, 0, 0, 0, 0, 2, 1}, + {1, 0, 0, 0, 0, 2, 1}, + {1, 1, 1, 1, 1, 1, 1}, }; assertArrayEquals(map, expectedMap); diff --git a/src/test/java/com/thealgorithms/backtracking/PermutationTest.java b/src/test/java/com/thealgorithms/backtracking/PermutationTest.java index 3d865da1..b6c0400c 100644 --- a/src/test/java/com/thealgorithms/backtracking/PermutationTest.java +++ b/src/test/java/com/thealgorithms/backtracking/PermutationTest.java @@ -16,16 +16,14 @@ public class PermutationTest { @Test void testSingleElement() { - List result = Permutation.permutation(new Integer[] { 1 }); + List result = Permutation.permutation(new Integer[] {1}); assertEquals(result.get(0)[0], 1); } @Test void testMultipleElements() { - List result = Permutation.permutation( - new Integer[] { 1, 2 } - ); - assertTrue(Arrays.equals(result.get(0), new Integer[] { 1, 2 })); - assertTrue(Arrays.equals(result.get(1), new Integer[] { 2, 1 })); + List result = Permutation.permutation(new Integer[] {1, 2}); + assertTrue(Arrays.equals(result.get(0), new Integer[] {1, 2})); + assertTrue(Arrays.equals(result.get(1), new Integer[] {2, 1})); } } diff --git a/src/test/java/com/thealgorithms/backtracking/PowerSumTest.java b/src/test/java/com/thealgorithms/backtracking/PowerSumTest.java index ae16cc15..b14bce2b 100644 --- a/src/test/java/com/thealgorithms/backtracking/PowerSumTest.java +++ b/src/test/java/com/thealgorithms/backtracking/PowerSumTest.java @@ -1,5 +1,6 @@ package com.thealgorithms.backtracking; import static org.junit.jupiter.api.Assertions.assertEquals; + import org.junit.jupiter.api.Test; public class PowerSumTest { @@ -17,12 +18,11 @@ public class PowerSumTest { int result = powerSum.powSum(100, 2); assertEquals(3, result); } - + @Test void testNumberHundredAndPowerThree() { PowerSum powerSum = new PowerSum(); int result = powerSum.powSum(100, 3); assertEquals(1, result); } - } diff --git a/src/test/java/com/thealgorithms/backtracking/WordSearchTest.java b/src/test/java/com/thealgorithms/backtracking/WordSearchTest.java index 198217bb..fb224a0b 100644 --- a/src/test/java/com/thealgorithms/backtracking/WordSearchTest.java +++ b/src/test/java/com/thealgorithms/backtracking/WordSearchTest.java @@ -9,7 +9,7 @@ public class WordSearchTest { @Test void test1() { WordSearch ws = new WordSearch(); - char[][] board = {{'A','B','C','E'},{'S','F','C','S'},{'A','D','E','E'}}; + char[][] board = {{'A', 'B', 'C', 'E'}, {'S', 'F', 'C', 'S'}, {'A', 'D', 'E', 'E'}}; String word = "ABCCED"; assertTrue(ws.exist(board, word)); } @@ -17,7 +17,7 @@ public class WordSearchTest { @Test void test2() { WordSearch ws = new WordSearch(); - char[][] board = {{'A','B','C','E'},{'S','F','C','S'},{'A','D','E','E'}}; + char[][] board = {{'A', 'B', 'C', 'E'}, {'S', 'F', 'C', 'S'}, {'A', 'D', 'E', 'E'}}; String word = "SEE"; assertTrue(ws.exist(board, word)); } @@ -25,7 +25,7 @@ public class WordSearchTest { @Test void test3() { WordSearch ws = new WordSearch(); - char[][] board = {{'A','B','C','E'},{'S','F','C','S'},{'A','D','E','E'}}; + char[][] board = {{'A', 'B', 'C', 'E'}, {'S', 'F', 'C', 'S'}, {'A', 'D', 'E', 'E'}}; String word = "ABCB"; Assertions.assertFalse(ws.exist(board, word)); } diff --git a/src/test/java/com/thealgorithms/ciphers/BlowfishTest.java b/src/test/java/com/thealgorithms/ciphers/BlowfishTest.java index 984457e3..e143850e 100644 --- a/src/test/java/com/thealgorithms/ciphers/BlowfishTest.java +++ b/src/test/java/com/thealgorithms/ciphers/BlowfishTest.java @@ -10,29 +10,29 @@ class BlowfishTest { @Test void testEncrypt() { - //given + // given String plainText = "123456abcd132536"; String key = "aabb09182736ccdd"; String expectedOutput = "d748ec383d3405f7"; - //when + // when String cipherText = blowfish.encrypt(plainText, key); - //then + // then assertEquals(expectedOutput, cipherText); } @Test void testDecrypt() { - //given + // given String cipherText = "d748ec383d3405f7"; String key = "aabb09182736ccdd"; String expectedOutput = "123456abcd132536"; - //when + // when String plainText = blowfish.decrypt(cipherText, key); - //then + // then assertEquals(expectedOutput, plainText); } } diff --git a/src/test/java/com/thealgorithms/ciphers/CaesarTest.java b/src/test/java/com/thealgorithms/ciphers/CaesarTest.java index 5eb4a37f..5fa81f95 100644 --- a/src/test/java/com/thealgorithms/ciphers/CaesarTest.java +++ b/src/test/java/com/thealgorithms/ciphers/CaesarTest.java @@ -1,9 +1,9 @@ package com.thealgorithms.ciphers; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + class CaesarTest { Caesar caesar = new Caesar(); @@ -43,5 +43,4 @@ class CaesarTest { assertEquals(27, allPossibleAnswers.length); assertEquals("Encrypt this text", allPossibleAnswers[5]); } - } diff --git a/src/test/java/com/thealgorithms/ciphers/DESTest.java b/src/test/java/com/thealgorithms/ciphers/DESTest.java index a0c529d5..e652c028 100644 --- a/src/test/java/com/thealgorithms/ciphers/DESTest.java +++ b/src/test/java/com/thealgorithms/ciphers/DESTest.java @@ -5,7 +5,7 @@ import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -//Test example taken from https://page.math.tu-berlin.de/~kant/teaching/hess/krypto-ws2006/des.htm +// Test example taken from https://page.math.tu-berlin.de/~kant/teaching/hess/krypto-ws2006/des.htm public class DESTest { DES des; @@ -17,35 +17,40 @@ public class DESTest { @Test void testEncrypt() { - //given + // given String plainText = "Your lips are smoother than vaseline\r\n"; - //This is equal to c0999fdde378d7ed727da00bca5a84ee47f269a4d6438190d9d52f78f5358499828ac9b453e0e653 in hexadecimal - String expectedOutput = "11000000100110011001111111011101111000110111100011010111111" + - "011010111001001111101101000000000101111001010010110101000010011101110010001111111001" + - "001101001101001001101011001000011100000011001000011011001110101010010111101111000111" + - "101010011010110000100100110011000001010001010110010011011010001010011111000001110011001010011"; + // This is equal to + // c0999fdde378d7ed727da00bca5a84ee47f269a4d6438190d9d52f78f5358499828ac9b453e0e653 in + // hexadecimal + String expectedOutput = "11000000100110011001111111011101111000110111100011010111111" + + "011010111001001111101101000000000101111001010010110101000010011101110010001111111001" + + "001101001101001001101011001000011100000011001000011011001110101010010111101111000111" + + "101010011010110000100100110011000001010001010110010011011010001010011111000001110011001010011"; - //when + // when String cipherText = des.encrypt(plainText); - //then + // then assertEquals(expectedOutput, cipherText); } @Test void testDecrypt() { - //given - //This is equal to c0999fdde378d7ed727da00bca5a84ee47f269a4d6438190d9d52f78f5358499828ac9b453e0e653 in hexadecimal - String cipherText = "11000000100110011001111111011101111000110111100011010111111" + - "011010111001001111101101000000000101111001010010110101000010011101110010001111111001" + - "001101001101001001101011001000011100000011001000011011001110101010010111101111000111" + - "101010011010110000100100110011000001010001010110010011011010001010011111000001110011001010011"; - String expectedOutput = "Your lips are smoother than vaseline\r\n";; + // given + // This is equal to + // c0999fdde378d7ed727da00bca5a84ee47f269a4d6438190d9d52f78f5358499828ac9b453e0e653 in + // hexadecimal + String cipherText = "11000000100110011001111111011101111000110111100011010111111" + + "011010111001001111101101000000000101111001010010110101000010011101110010001111111001" + + "001101001101001001101011001000011100000011001000011011001110101010010111101111000111" + + "101010011010110000100100110011000001010001010110010011011010001010011111000001110011001010011"; + String expectedOutput = "Your lips are smoother than vaseline\r\n"; + ; - //when + // when String plainText = des.decrypt(cipherText); - //then + // then assertEquals(expectedOutput, plainText); } } diff --git a/src/test/java/com/thealgorithms/ciphers/RSATest.java b/src/test/java/com/thealgorithms/ciphers/RSATest.java index 46fff796..c82f68d1 100644 --- a/src/test/java/com/thealgorithms/ciphers/RSATest.java +++ b/src/test/java/com/thealgorithms/ciphers/RSATest.java @@ -1,9 +1,9 @@ package com.thealgorithms.ciphers; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + class RSATest { RSA rsa = new RSA(1024); @@ -20,5 +20,4 @@ class RSATest { // then assertEquals("Such secure", decryptedText); } - } diff --git a/src/test/java/com/thealgorithms/ciphers/SimpleSubCipherTest.java b/src/test/java/com/thealgorithms/ciphers/SimpleSubCipherTest.java index e9bbcf95..f593a07d 100644 --- a/src/test/java/com/thealgorithms/ciphers/SimpleSubCipherTest.java +++ b/src/test/java/com/thealgorithms/ciphers/SimpleSubCipherTest.java @@ -1,9 +1,9 @@ package com.thealgorithms.ciphers; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + class SimpleSubCipherTest { SimpleSubCipher simpleSubCipher = new SimpleSubCipher(); @@ -33,5 +33,4 @@ class SimpleSubCipherTest { // then assertEquals("defend the east wall of the castle", decryptedText); } - } diff --git a/src/test/java/com/thealgorithms/ciphers/SimpleSubstitutionCipherTest.java b/src/test/java/com/thealgorithms/ciphers/SimpleSubstitutionCipherTest.java index 59fb9c07..f7cace2e 100644 --- a/src/test/java/com/thealgorithms/ciphers/SimpleSubstitutionCipherTest.java +++ b/src/test/java/com/thealgorithms/ciphers/SimpleSubstitutionCipherTest.java @@ -1,9 +1,9 @@ package com.thealgorithms.ciphers; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + public class SimpleSubstitutionCipherTest { @Test diff --git a/src/test/java/com/thealgorithms/ciphers/VigenereTest.java b/src/test/java/com/thealgorithms/ciphers/VigenereTest.java index 421edf3a..c5935de9 100644 --- a/src/test/java/com/thealgorithms/ciphers/VigenereTest.java +++ b/src/test/java/com/thealgorithms/ciphers/VigenereTest.java @@ -1,9 +1,9 @@ package com.thealgorithms.ciphers; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + class VigenereTest { Vigenere vigenere = new Vigenere(); @@ -33,5 +33,4 @@ class VigenereTest { // then assertEquals("Hello World!", decryptedText); } - } diff --git a/src/test/java/com/thealgorithms/ciphers/a5/LFSRTest.java b/src/test/java/com/thealgorithms/ciphers/a5/LFSRTest.java index 0ad4c9fb..6ef478f9 100644 --- a/src/test/java/com/thealgorithms/ciphers/a5/LFSRTest.java +++ b/src/test/java/com/thealgorithms/ciphers/a5/LFSRTest.java @@ -23,7 +23,7 @@ class LFSRTest { }; // Represents 11 1010 1011 0011 1100 1011 - byte[] frameCounterBytes = { (byte) 203, (byte) 179, 58 }; + byte[] frameCounterBytes = {(byte) 203, (byte) 179, 58}; @Test void initialize() { @@ -46,7 +46,7 @@ class LFSRTest { expected.set(16); expected.set(17); - LFSR lfsr0 = new LFSR(19, 8, new int[] { 13, 16, 17, 18 }); + LFSR lfsr0 = new LFSR(19, 8, new int[] {13, 16, 17, 18}); lfsr0.initialize(sessionKey, frameCounter); assertEquals(expected.toString(), lfsr0.toString()); } @@ -56,7 +56,7 @@ class LFSRTest { BitSet sessionKey = BitSet.valueOf(sessionKeyBytes); BitSet frameCounter = BitSet.valueOf(frameCounterBytes); - LFSR lfsr0 = new LFSR(19, 8, new int[] { 13, 16, 17, 18 }); + LFSR lfsr0 = new LFSR(19, 8, new int[] {13, 16, 17, 18}); lfsr0.initialize(sessionKey, frameCounter); BitSet expected = new BitSet(19); @@ -85,7 +85,7 @@ class LFSRTest { BitSet sessionKey = BitSet.valueOf(sessionKeyBytes); BitSet frameCounter = BitSet.valueOf(frameCounterBytes); - LFSR lfsr0 = new LFSR(19, 8, new int[] { 13, 16, 17, 18 }); + LFSR lfsr0 = new LFSR(19, 8, new int[] {13, 16, 17, 18}); assertFalse(lfsr0.getClockBit()); diff --git a/src/test/java/com/thealgorithms/conversions/BinaryToDecimalTest.java b/src/test/java/com/thealgorithms/conversions/BinaryToDecimalTest.java index 336aeef3..29265bd9 100644 --- a/src/test/java/com/thealgorithms/conversions/BinaryToDecimalTest.java +++ b/src/test/java/com/thealgorithms/conversions/BinaryToDecimalTest.java @@ -1,9 +1,9 @@ package com.thealgorithms.conversions; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + public class BinaryToDecimalTest { @Test diff --git a/src/test/java/com/thealgorithms/conversions/HexaDecimalToBinaryTest.java b/src/test/java/com/thealgorithms/conversions/HexaDecimalToBinaryTest.java index 57379323..a5abcb95 100644 --- a/src/test/java/com/thealgorithms/conversions/HexaDecimalToBinaryTest.java +++ b/src/test/java/com/thealgorithms/conversions/HexaDecimalToBinaryTest.java @@ -1,12 +1,13 @@ package com.thealgorithms.conversions; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + public class HexaDecimalToBinaryTest { @Test - public void testHexaDecimalToBinary(){ + public void testHexaDecimalToBinary() { HexaDecimalToBinary hexaDecimalToBinary = new HexaDecimalToBinary(); assertEquals("1111111111111111111111111111111", hexaDecimalToBinary.convert("7fffffff")); assertEquals("101010111100110111101111", hexaDecimalToBinary.convert("abcdef")); diff --git a/src/test/java/com/thealgorithms/conversions/HexaDecimalToDecimalTest.java b/src/test/java/com/thealgorithms/conversions/HexaDecimalToDecimalTest.java index 5a7838e7..c9c2ab21 100644 --- a/src/test/java/com/thealgorithms/conversions/HexaDecimalToDecimalTest.java +++ b/src/test/java/com/thealgorithms/conversions/HexaDecimalToDecimalTest.java @@ -1,13 +1,13 @@ package com.thealgorithms.conversions; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + public class HexaDecimalToDecimalTest { @Test - public void testhexaDecimalToDecimal(){ + public void testhexaDecimalToDecimal() { assertEquals(161, HexaDecimalToDecimal.getHexaToDec("A1")); assertEquals(428, HexaDecimalToDecimal.getHexaToDec("1ac")); } diff --git a/src/test/java/com/thealgorithms/conversions/RomanToIntegerTest.java b/src/test/java/com/thealgorithms/conversions/RomanToIntegerTest.java index 52eda44c..c51986f2 100644 --- a/src/test/java/com/thealgorithms/conversions/RomanToIntegerTest.java +++ b/src/test/java/com/thealgorithms/conversions/RomanToIntegerTest.java @@ -1,9 +1,9 @@ package com.thealgorithms.conversions; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + public class RomanToIntegerTest { @Test diff --git a/src/test/java/com/thealgorithms/datastructures/buffers/CircularBufferTest.java b/src/test/java/com/thealgorithms/datastructures/buffers/CircularBufferTest.java index 70fb6608..ab7eff71 100644 --- a/src/test/java/com/thealgorithms/datastructures/buffers/CircularBufferTest.java +++ b/src/test/java/com/thealgorithms/datastructures/buffers/CircularBufferTest.java @@ -1,16 +1,15 @@ package com.thealgorithms.datastructures.buffers; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.RepeatedTest; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicIntegerArray; - -import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.RepeatedTest; +import org.junit.jupiter.api.Test; class CircularBufferTest { private static final int BUFFER_SIZE = 10; @@ -34,25 +33,21 @@ class CircularBufferTest { buffer.put(generateInt()); assertFalse(buffer.isFull()); - for (int i = 1; i < BUFFER_SIZE; i++) - buffer.put(generateInt()); + for (int i = 1; i < BUFFER_SIZE; i++) buffer.put(generateInt()); assertTrue(buffer.isFull()); } @Test void get() { assertNull(buffer.get()); - for (int i = 0; i < 100; i++) - buffer.put(i); - for (int i = 0; i < BUFFER_SIZE; i++) - assertEquals(i, buffer.get()); + for (int i = 0; i < 100; i++) buffer.put(i); + for (int i = 0; i < BUFFER_SIZE; i++) assertEquals(i, buffer.get()); assertNull(buffer.get()); } @Test void put() { - for (int i = 0; i < BUFFER_SIZE; i++) - assertTrue(buffer.put(generateInt())); + for (int i = 0; i < BUFFER_SIZE; i++) assertTrue(buffer.put(generateInt())); assertFalse(buffer.put(generateInt())); } @@ -119,8 +114,7 @@ class CircularBufferTest { public List getSortedListFrom(AtomicIntegerArray atomicArray) { int length = atomicArray.length(); ArrayList result = new ArrayList<>(length); - for (int i = 0; i < length; i++) - result.add(atomicArray.get(i)); + for (int i = 0; i < length; i++) result.add(atomicArray.get(i)); result.sort(Comparator.comparingInt(o -> o)); return result; } diff --git a/src/test/java/com/thealgorithms/datastructures/caches/LFUCacheTest.java b/src/test/java/com/thealgorithms/datastructures/caches/LFUCacheTest.java index 6faf6da3..6a94345d 100644 --- a/src/test/java/com/thealgorithms/datastructures/caches/LFUCacheTest.java +++ b/src/test/java/com/thealgorithms/datastructures/caches/LFUCacheTest.java @@ -15,19 +15,19 @@ class LFUCacheTest { lfuCache.put(4, 40); lfuCache.put(5, 50); - //get method call will increase frequency of key 1 by 1 + // get method call will increase frequency of key 1 by 1 assertEquals(10, lfuCache.get(1)); - //this operation will remove value with key as 2 + // this operation will remove value with key as 2 lfuCache.put(6, 60); - //will return null as value with key 2 is now evicted + // will return null as value with key 2 is now evicted assertEquals(null, lfuCache.get(2)); - //should return 60 + // should return 60 assertEquals(60, lfuCache.get(6)); - //this operation will remove value with key as 3 + // this operation will remove value with key as 3 lfuCache.put(7, 70); assertEquals(null, lfuCache.get(2)); @@ -43,19 +43,19 @@ class LFUCacheTest { lfuCache.put(4, "Delta"); lfuCache.put(5, "Eplison"); - //get method call will increase frequency of key 1 by 1 + // get method call will increase frequency of key 1 by 1 assertEquals("Alpha", lfuCache.get(1)); - //this operation will remove value with key as 2 + // this operation will remove value with key as 2 lfuCache.put(6, "Digamma"); - //will return null as value with key 2 is now evicted + // will return null as value with key 2 is now evicted assertEquals(null, lfuCache.get(2)); - //should return string Digamma + // should return string Digamma assertEquals("Digamma", lfuCache.get(6)); - //this operation will remove value with key as 3 + // this operation will remove value with key as 3 lfuCache.put(7, "Zeta"); assertEquals(null, lfuCache.get(2)); diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/HamiltonianCycleTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/HamiltonianCycleTest.java index 3746753b..9890463d 100644 --- a/src/test/java/com/thealgorithms/datastructures/graphs/HamiltonianCycleTest.java +++ b/src/test/java/com/thealgorithms/datastructures/graphs/HamiltonianCycleTest.java @@ -10,36 +10,30 @@ class HamiltonianCycleTest { @Test void testFindHamiltonianCycleShouldReturnHamiltonianCycle() { - int[] expectedArray = { 0, 1, 2, 4, 3, 0 }; + int[] expectedArray = {0, 1, 2, 4, 3, 0}; int[][] inputArray = { - { 0, 1, 0, 1, 0 }, - { 1, 0, 1, 1, 1 }, - { 0, 1, 0, 0, 1 }, - { 1, 1, 0, 0, 1 }, - { 0, 1, 1, 1, 0 }, + {0, 1, 0, 1, 0}, + {1, 0, 1, 1, 1}, + {0, 1, 0, 0, 1}, + {1, 1, 0, 0, 1}, + {0, 1, 1, 1, 0}, }; - assertArrayEquals( - expectedArray, - hamiltonianCycle.findHamiltonianCycle(inputArray) - ); + assertArrayEquals(expectedArray, hamiltonianCycle.findHamiltonianCycle(inputArray)); } @Test void testFindHamiltonianCycleShouldReturnInfinityArray() { - int[] expectedArray = { -1, -1, -1, -1, -1, -1 }; + int[] expectedArray = {-1, -1, -1, -1, -1, -1}; int[][] inputArray = { - { 0, 1, 0, 1, 0 }, - { 1, 0, 1, 1, 1 }, - { 0, 1, 0, 0, 1 }, - { 1, 1, 0, 0, 0 }, - { 0, 1, 1, 0, 0 }, + {0, 1, 0, 1, 0}, + {1, 0, 1, 1, 1}, + {0, 1, 0, 0, 1}, + {1, 1, 0, 0, 0}, + {0, 1, 1, 0, 0}, }; - assertArrayEquals( - expectedArray, - hamiltonianCycle.findHamiltonianCycle(inputArray) - ); + assertArrayEquals(expectedArray, hamiltonianCycle.findHamiltonianCycle(inputArray)); } } diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/KosarajuTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/KosarajuTest.java index 5395b04e..c1e68aca 100644 --- a/src/test/java/com/thealgorithms/datastructures/graphs/KosarajuTest.java +++ b/src/test/java/com/thealgorithms/datastructures/graphs/KosarajuTest.java @@ -5,7 +5,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.List; - import org.junit.jupiter.api.Test; public class KosarajuTest { @@ -14,7 +13,7 @@ public class KosarajuTest { @Test public void findStronglyConnectedComps() { - //Create a adjacency list of graph + // Create a adjacency list of graph var n = 8; var adjList = new ArrayList>(n); @@ -36,10 +35,10 @@ public class KosarajuTest { List> actualResult = kosaraju.kosaraju(n, adjList); List> expectedResult = new ArrayList<>(); /* - Expected result: + Expected result: 0, 1, 2 3 - 5, 4, 6 + 5, 4, 6 7 */ expectedResult.add(Arrays.asList(1, 2, 0)); @@ -51,7 +50,7 @@ public class KosarajuTest { @Test public void findStronglyConnectedCompsShouldGetSingleNodes() { - //Create a adjacency list of graph + // Create a adjacency list of graph var n = 8; var adjList = new ArrayList>(n); @@ -71,11 +70,10 @@ public class KosarajuTest { List> actualResult = kosaraju.kosaraju(n, adjList); List> expectedResult = new ArrayList<>(); /* - Expected result: + Expected result: 0, 1, 2, 3, 4, 5, 6, 7 */ expectedResult.add(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 0)); assertTrue(expectedResult.equals(actualResult)); } - } diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithmTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithmTest.java index 2166b2ef..dc81d99d 100644 --- a/src/test/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithmTest.java +++ b/src/test/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithmTest.java @@ -5,15 +5,14 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.List; - import org.junit.jupiter.api.Test; public class TarjansAlgorithmTest { - + TarjansAlgorithm tarjansAlgo = new TarjansAlgorithm(); @Test - public void findStronglyConnectedComps(){ + public void findStronglyConnectedComps() { var v = 5; var graph = new ArrayList>(); for (int i = 0; i < v; i++) { @@ -27,10 +26,10 @@ public class TarjansAlgorithmTest { var actualResult = tarjansAlgo.stronglyConnectedComponents(v, graph); /* - Expected result: + Expected result: 0, 1, 2 3 - 4 + 4 */ List> expectedResult = new ArrayList<>(); @@ -42,7 +41,7 @@ public class TarjansAlgorithmTest { @Test public void findStronglyConnectedCompsShouldGetSingleNodes() { - //Create a adjacency list of graph + // Create a adjacency list of graph var n = 8; var adjList = new ArrayList>(n); @@ -62,11 +61,10 @@ public class TarjansAlgorithmTest { List> actualResult = tarjansAlgo.stronglyConnectedComponents(n, adjList); List> expectedResult = new ArrayList<>(); /* - Expected result: + Expected result: 7, 6, 5, 4, 3, 2, 1, 0 */ expectedResult.add(Arrays.asList(7, 6, 5, 4, 3, 2, 1, 0)); assertTrue(expectedResult.equals(actualResult)); } - } diff --git a/src/test/java/com/thealgorithms/datastructures/hashmap/HashMapCuckooHashingTest.java b/src/test/java/com/thealgorithms/datastructures/hashmap/HashMapCuckooHashingTest.java index fc6655fa..c7391c3a 100644 --- a/src/test/java/com/thealgorithms/datastructures/hashmap/HashMapCuckooHashingTest.java +++ b/src/test/java/com/thealgorithms/datastructures/hashmap/HashMapCuckooHashingTest.java @@ -93,7 +93,7 @@ class HashMapCuckooHashingTest { private HashMapCuckooHashing createHashMapCuckooHashing() { HashMapCuckooHashing hashTable = new HashMapCuckooHashing(10); - int[] values = { 11, 22, 33, 44, 55, 66, 77, 88, 99, 111, 222 }; + int[] values = {11, 22, 33, 44, 55, 66, 77, 88, 99, 111, 222}; Arrays.stream(values).forEach(hashTable::insertKey2HashTable); return hashTable; } diff --git a/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElementTest.java b/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElementTest.java index 45c7b6c5..7f7c3601 100644 --- a/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElementTest.java +++ b/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElementTest.java @@ -1,17 +1,14 @@ package com.thealgorithms.datastructures.hashmap.hashing; -import com.thealgorithms.datastructures.hashmap.hashing.MajorityElement; - import static org.junit.jupiter.api.Assertions.*; -import org.junit.jupiter.api.Test; - +import com.thealgorithms.datastructures.hashmap.hashing.MajorityElement; +import java.util.ArrayList; import java.util.Collections; import java.util.List; +import org.junit.jupiter.api.Test; -import java.util.ArrayList; - -public class MajorityElementTest{ +public class MajorityElementTest { @Test void testMajorityWithSingleMajorityElement() { int[] nums = {1, 2, 3, 9, 9, 6, 7, 8, 9, 9, 9, 9}; @@ -42,7 +39,7 @@ public class MajorityElementTest{ @Test void testMajorityWithEmptyArray() { int[] nums = {}; - List expected = Collections.emptyList(); + List expected = Collections.emptyList(); List actual = MajorityElement.majority(nums); assertEquals(expected, actual); } diff --git a/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MapTest.java b/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MapTest.java index 5ccbcc30..ea6595cc 100644 --- a/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MapTest.java +++ b/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MapTest.java @@ -1,10 +1,9 @@ package com.thealgorithms.datastructures.hashmap.hashing; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; import java.util.Random; - -import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; abstract class MapTest { abstract , Value> Map getMap(); diff --git a/src/test/java/com/thealgorithms/datastructures/heaps/LeftistHeapTest.java b/src/test/java/com/thealgorithms/datastructures/heaps/LeftistHeapTest.java index b0cb0d19..983444eb 100644 --- a/src/test/java/com/thealgorithms/datastructures/heaps/LeftistHeapTest.java +++ b/src/test/java/com/thealgorithms/datastructures/heaps/LeftistHeapTest.java @@ -4,25 +4,25 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class LeftistHeapTest { - - @Test - void testLeftistHeap() { - LeftistHeap heap = new LeftistHeap(); - Assertions.assertTrue(heap.isEmpty()); - heap.insert(6); - Assertions.assertTrue(!heap.isEmpty()); - heap.insert(2); - heap.insert(3); - heap.insert(1); - heap.in_order(); - Assertions.assertTrue(heap.in_order().toString().equals("[6, 2, 3, 1]")); - Assertions.assertTrue(heap.extract_min() == 1); - Assertions.assertTrue(heap.in_order().toString().equals("[6, 2, 3]")); - heap.insert(8); - heap.insert(12); - heap.insert(4); - Assertions.assertTrue(heap.in_order().toString().equals("[8, 3, 12, 2, 6, 4]")); - heap.clear(); - Assertions.assertTrue(heap.isEmpty()); - } + + @Test + void testLeftistHeap() { + LeftistHeap heap = new LeftistHeap(); + Assertions.assertTrue(heap.isEmpty()); + heap.insert(6); + Assertions.assertTrue(!heap.isEmpty()); + heap.insert(2); + heap.insert(3); + heap.insert(1); + heap.in_order(); + Assertions.assertTrue(heap.in_order().toString().equals("[6, 2, 3, 1]")); + Assertions.assertTrue(heap.extract_min() == 1); + Assertions.assertTrue(heap.in_order().toString().equals("[6, 2, 3]")); + heap.insert(8); + heap.insert(12); + heap.insert(4); + Assertions.assertTrue(heap.in_order().toString().equals("[8, 3, 12, 2, 6, 4]")); + heap.clear(); + Assertions.assertTrue(heap.isEmpty()); + } } \ No newline at end of file diff --git a/src/test/java/com/thealgorithms/datastructures/lists/SinglyLinkedListTest.java b/src/test/java/com/thealgorithms/datastructures/lists/SinglyLinkedListTest.java index 94896132..57eedb97 100644 --- a/src/test/java/com/thealgorithms/datastructures/lists/SinglyLinkedListTest.java +++ b/src/test/java/com/thealgorithms/datastructures/lists/SinglyLinkedListTest.java @@ -1,12 +1,10 @@ package com.thealgorithms.datastructures.lists; - -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; import java.util.ArrayList; import java.util.List; - -import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; public class SinglyLinkedListTest { @@ -23,7 +21,7 @@ public class SinglyLinkedListTest { } for (int i = 0; i < length - 1; i++) { - nodeList.get(i).next = nodeList.get(i+1); + nodeList.get(i).next = nodeList.get(i + 1); } return new SinglyLinkedList(nodeList.get(0), length); @@ -31,7 +29,7 @@ public class SinglyLinkedListTest { @Test void detectLoop() { - //List has cycle + // List has cycle Node firstNode = new Node(1); Node secondNode = new Node(2); Node thirdNode = new Node(3); @@ -53,16 +51,16 @@ public class SinglyLinkedListTest { void middle() { int oddNumberOfNode = 7; SinglyLinkedList list = createSampleList(oddNumberOfNode); - assertEquals(oddNumberOfNode/2 + 1, list.middle().value); + assertEquals(oddNumberOfNode / 2 + 1, list.middle().value); int evenNumberOfNode = 8; list = createSampleList(evenNumberOfNode); - assertEquals(evenNumberOfNode/2, list.middle().value); + assertEquals(evenNumberOfNode / 2, list.middle().value); - //return null if empty + // return null if empty list = new SinglyLinkedList(); assertNull(list.middle()); - //return head if there is only one node + // return head if there is only one node list = createSampleList(1); assertEquals(list.getHead(), list.middle()); } @@ -72,7 +70,7 @@ public class SinglyLinkedListTest { SinglyLinkedList list = createSampleList(5); assertEquals(1, list.getHead().value); assertEquals(5, list.getNth(4)); - list.swapNodes(1,5); + list.swapNodes(1, 5); assertEquals(5, list.getHead().value); assertEquals(1, list.getNth(4)); } @@ -97,67 +95,69 @@ public class SinglyLinkedListTest { void deleteNth() { SinglyLinkedList list = createSampleList(10); assertTrue(list.search(7)); - list.deleteNth(6); //Index 6 has value 7 + list.deleteNth(6); // Index 6 has value 7 assertFalse(list.search(7)); } - //Test to check whether the method reverseList() works fine + // Test to check whether the method reverseList() works fine @Test - void reverseList(){ + void reverseList() { - //Creating a new LinkedList of size:4 - //The linkedlist will be 1->2->3->4->null + // Creating a new LinkedList of size:4 + // The linkedlist will be 1->2->3->4->null SinglyLinkedList list = createSampleList(4); - - //Reversing the LinkedList using reverseList() method and storing the head of the reversed linkedlist in a head node - //The reversed linkedlist will be 4->3->2->1->null - Node head=list.reverseList(list.getHead()); - //Recording the Nodes after reversing the LinkedList - Node firstNode = head; //4 - Node secondNode = firstNode.next; //3 - Node thirdNode = secondNode.next; //2 - Node fourthNode = thirdNode.next; //1 - - //Checking whether the LinkedList is reversed or not by comparing the original list and reversed list nodes - assertEquals(1,fourthNode.value); - assertEquals(2,thirdNode.value); - assertEquals(3,secondNode.value); - assertEquals(4,firstNode.value); - } - - //Test to check whether implemented reverseList() method handles NullPointer Exception for TestCase where head==null - @Test - void reverseListNullPointer(){ - //Creating a linkedlist with first node assigned to null - SinglyLinkedList list=new SinglyLinkedList(); - Node first=list.getHead(); - - //Reversing the linkedlist - Node head=list.reverseList(first); + // Reversing the LinkedList using reverseList() method and storing the head of the reversed + // linkedlist in a head node The reversed linkedlist will be 4->3->2->1->null + Node head = list.reverseList(list.getHead()); - //checking whether the method works fine if the input is null - assertEquals(head,first); + // Recording the Nodes after reversing the LinkedList + Node firstNode = head; // 4 + Node secondNode = firstNode.next; // 3 + Node thirdNode = secondNode.next; // 2 + Node fourthNode = thirdNode.next; // 1 + + // Checking whether the LinkedList is reversed or not by comparing the original list and + // reversed list nodes + assertEquals(1, fourthNode.value); + assertEquals(2, thirdNode.value); + assertEquals(3, secondNode.value); + assertEquals(4, firstNode.value); } - //Testing reverseList() method for a linkedlist of size: 20 + // Test to check whether implemented reverseList() method handles NullPointer Exception for + // TestCase where head==null @Test - void reverseListTest(){ - //Creating a new linkedlist + void reverseListNullPointer() { + // Creating a linkedlist with first node assigned to null + SinglyLinkedList list = new SinglyLinkedList(); + Node first = list.getHead(); + + // Reversing the linkedlist + Node head = list.reverseList(first); + + // checking whether the method works fine if the input is null + assertEquals(head, first); + } + + // Testing reverseList() method for a linkedlist of size: 20 + @Test + void reverseListTest() { + // Creating a new linkedlist SinglyLinkedList list = createSampleList(20); - //Reversing the LinkedList using reverseList() method and storing the head of the reversed linkedlist in a head node - Node head=list.reverseList(list.getHead()); - - //Storing the head in a temp variable, so that we cannot loose the track of head - Node temp=head; + // Reversing the LinkedList using reverseList() method and storing the head of the reversed + // linkedlist in a head node + Node head = list.reverseList(list.getHead()); - int i=20; //This is for the comparison of values of nodes of the reversed linkedlist - //Checking whether the reverseList() method performed its task - while(temp!=null && i>0){ - assertEquals(i,temp.value); - temp=temp.next; - i--; + // Storing the head in a temp variable, so that we cannot loose the track of head + Node temp = head; + + int i = 20; // This is for the comparison of values of nodes of the reversed linkedlist + // Checking whether the reverseList() method performed its task + while (temp != null && i > 0) { + assertEquals(i, temp.value); + temp = temp.next; + i--; } } - } \ No newline at end of file diff --git a/src/test/java/com/thealgorithms/datastructures/lists/SkipListTest.java b/src/test/java/com/thealgorithms/datastructures/lists/SkipListTest.java index 9214b613..fb45fa56 100644 --- a/src/test/java/com/thealgorithms/datastructures/lists/SkipListTest.java +++ b/src/test/java/com/thealgorithms/datastructures/lists/SkipListTest.java @@ -69,16 +69,14 @@ class SkipListTest { @Test void checkSortedOnLowestLayer() { SkipList skipList = new SkipList<>(); - String[] values = { "d", "b", "a", "c" }; + String[] values = {"d", "b", "a", "c"}; Arrays.stream(values).forEach(skipList::add); print(skipList); - String[] actualOrder = IntStream - .range(0, values.length) - .mapToObj(skipList::get) - .toArray(String[]::new); + String[] actualOrder + = IntStream.range(0, values.length).mapToObj(skipList::get).toArray(String[] ::new); - assertArrayEquals(new String[] { "a", "b", "c", "d" }, actualOrder); + assertArrayEquals(new String[] {"a", "b", "c", "d"}, actualOrder); } private SkipList createSkipList() { diff --git a/src/test/java/com/thealgorithms/datastructures/queues/LinkedQueueTest.java b/src/test/java/com/thealgorithms/datastructures/queues/LinkedQueueTest.java index e153890e..5bc90fc0 100644 --- a/src/test/java/com/thealgorithms/datastructures/queues/LinkedQueueTest.java +++ b/src/test/java/com/thealgorithms/datastructures/queues/LinkedQueueTest.java @@ -1,29 +1,26 @@ package com.thealgorithms.datastructures.queues; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; class LinkedQueueTest { - @Test - public void testQue() { - LinkedQueue queue = new LinkedQueue<>(); - for (int i = 1; i < 5; i++) - queue.enqueue(i); + @Test + public void testQue() { + LinkedQueue queue = new LinkedQueue<>(); + for (int i = 1; i < 5; i++) queue.enqueue(i); - assertEquals(queue.peekRear(), 4); - assertEquals(queue.peek(2), 2); + assertEquals(queue.peekRear(), 4); + assertEquals(queue.peek(2), 2); - assertEquals(queue.peek(4), 4); + assertEquals(queue.peek(4), 4); - final int[] element = { 1 }; + final int[] element = {1}; - // iterates over all the elements present - // as in the form of nodes - queue.forEach(integer -> { - if (element[0]++ != integer) - throw new AssertionError(); - }); - } + // iterates over all the elements present + // as in the form of nodes + queue.forEach(integer -> { + if (element[0]++ != integer) throw new AssertionError(); + }); + } } \ No newline at end of file diff --git a/src/test/java/com/thealgorithms/datastructures/queues/PriorityQueuesTest.java b/src/test/java/com/thealgorithms/datastructures/queues/PriorityQueuesTest.java index e5af3026..1a3b5aad 100644 --- a/src/test/java/com/thealgorithms/datastructures/queues/PriorityQueuesTest.java +++ b/src/test/java/com/thealgorithms/datastructures/queues/PriorityQueuesTest.java @@ -26,7 +26,7 @@ class PriorityQueuesTest { myQueue.insert(5); myQueue.insert(3); myQueue.insert(10); - + myQueue.remove(); Assertions.assertEquals(myQueue.peek(), 5); myQueue.remove(); @@ -46,7 +46,7 @@ class PriorityQueuesTest { myQueue.insert(10); Assertions.assertEquals(myQueue.isEmpty(), false); Assertions.assertEquals(myQueue.isFull(), true); - + myQueue.remove(); Assertions.assertEquals(myQueue.getSize(), 3); Assertions.assertEquals(myQueue.peek(), 5); diff --git a/src/test/java/com/thealgorithms/datastructures/trees/BSTFromSortedArrayTest.java b/src/test/java/com/thealgorithms/datastructures/trees/BSTFromSortedArrayTest.java index 83458f6f..aab3b82c 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/BSTFromSortedArrayTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/BSTFromSortedArrayTest.java @@ -15,19 +15,19 @@ public class BSTFromSortedArrayTest { @Test public void testEmptyArray() { - BinaryTree.Node actualBST = BSTFromSortedArray.createBST(new int[]{}); + BinaryTree.Node actualBST = BSTFromSortedArray.createBST(new int[] {}); Assertions.assertNull(actualBST); } @Test public void testSingleElementArray() { - BinaryTree.Node actualBST = BSTFromSortedArray.createBST(new int[]{Integer.MIN_VALUE}); + BinaryTree.Node actualBST = BSTFromSortedArray.createBST(new int[] {Integer.MIN_VALUE}); Assertions.assertTrue(CheckBinaryTreeIsValidBST.isBST(actualBST)); } @Test public void testCreateBSTFromSmallArray() { - BinaryTree.Node actualBST = BSTFromSortedArray.createBST(new int[]{1, 2, 3}); + BinaryTree.Node actualBST = BSTFromSortedArray.createBST(new int[] {1, 2, 3}); Assertions.assertTrue(CheckBinaryTreeIsValidBST.isBST(actualBST)); } diff --git a/src/test/java/com/thealgorithms/datastructures/trees/BinaryTreeTest.java b/src/test/java/com/thealgorithms/datastructures/trees/BinaryTreeTest.java index 2ed3b534..b153c5d6 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/BinaryTreeTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/BinaryTreeTest.java @@ -6,73 +6,71 @@ import org.junit.jupiter.api.Test; public class BinaryTreeTest { - //checks that adding populating the tree and searching for data - //retrieves the expected data -@Test -void test1(){ - BinaryTree t = new BinaryTree(); - t.put(3); - t.put(5); - t.put(7); - t.put(9); - t.put(12); - + // checks that adding populating the tree and searching for data + // retrieves the expected data + @Test + void test1() { + BinaryTree t = new BinaryTree(); + t.put(3); + t.put(5); + t.put(7); + t.put(9); + t.put(12); - assertEquals(t.find(5).data, 5); - assertEquals(t.find(7).data, 7); -} - - //checks that removing data from the tree - //properly removes and makes the new root the expected new root -@Test -void test2(){ - BinaryTree t = new BinaryTree(); - t.put(3); - t.put(5); - t.put(7); - t.put(9); - t.put(12); - t.remove(3); - t.remove(5); - t.remove(7); - - - assertEquals(t.getRoot().data, 9); -} - -//checks that removing an unexistend node returns false -// as specified by the documentation of the function -@Test -void test3(){ - BinaryTree t = new BinaryTree(); - t.put(3); - t.put(5); - t.put(7); - t.put(9); - t.put(12); - - assertEquals(t.remove(9), true); - assertEquals(t.remove(398745987), false); -} - -//check if the bfs, inOrder, preOrder and postOrder functions -//worg as expected, also increases the coverage measures in -//JaCoCo -@Test -void test4(){ - BinaryTree t = new BinaryTree(); - t.put(3); - t.put(5); - t.put(7); - t.put(9); - t.put(12); - - t.bfs(t.find(12)); - t.inOrder(t.getRoot()); - t.preOrder(t.getRoot()); - t.postOrder(t.getRoot()); - - assertEquals(t.remove(9), true); - assertEquals(t.remove(398745987), false); -} + assertEquals(t.find(5).data, 5); + assertEquals(t.find(7).data, 7); + } + + // checks that removing data from the tree + // properly removes and makes the new root the expected new root + @Test + void test2() { + BinaryTree t = new BinaryTree(); + t.put(3); + t.put(5); + t.put(7); + t.put(9); + t.put(12); + t.remove(3); + t.remove(5); + t.remove(7); + + assertEquals(t.getRoot().data, 9); + } + + // checks that removing an unexistend node returns false + // as specified by the documentation of the function + @Test + void test3() { + BinaryTree t = new BinaryTree(); + t.put(3); + t.put(5); + t.put(7); + t.put(9); + t.put(12); + + assertEquals(t.remove(9), true); + assertEquals(t.remove(398745987), false); + } + + // check if the bfs, inOrder, preOrder and postOrder functions + // worg as expected, also increases the coverage measures in + // JaCoCo + @Test + void test4() { + BinaryTree t = new BinaryTree(); + t.put(3); + t.put(5); + t.put(7); + t.put(9); + t.put(12); + + t.bfs(t.find(12)); + t.inOrder(t.getRoot()); + t.preOrder(t.getRoot()); + t.postOrder(t.getRoot()); + + assertEquals(t.remove(9), true); + assertEquals(t.remove(398745987), false); + } } diff --git a/src/test/java/com/thealgorithms/datastructures/trees/CeilInBinarySearchTreeTest.java b/src/test/java/com/thealgorithms/datastructures/trees/CeilInBinarySearchTreeTest.java index ab865ff6..779c6813 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/CeilInBinarySearchTreeTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/CeilInBinarySearchTreeTest.java @@ -1,11 +1,11 @@ package com.thealgorithms.datastructures.trees; -import com.thealgorithms.datastructures.trees.BinaryTree.Node; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; +import com.thealgorithms.datastructures.trees.BinaryTree.Node; +import org.junit.jupiter.api.Test; + public class CeilInBinarySearchTreeTest { @Test @@ -15,37 +15,37 @@ public class CeilInBinarySearchTreeTest { @Test public void testKeyPresentRootIsCeil() { - final Node root = TreeTestUtils.createTree(new Integer[]{100, 10, 200}); + final Node root = TreeTestUtils.createTree(new Integer[] {100, 10, 200}); assertEquals(100, CeilInBinarySearchTree.getCeil(root, 100).data); } @Test public void testKeyPresentLeafIsCeil() { - final Node root = TreeTestUtils.createTree(new Integer[]{100, 10, 200}); + final Node root = TreeTestUtils.createTree(new Integer[] {100, 10, 200}); assertEquals(10, CeilInBinarySearchTree.getCeil(root, 10).data); } @Test public void testKeyAbsentRootIsCeil() { - final Node root = TreeTestUtils.createTree(new Integer[]{100, 10, 200, 5, 50, 150, 300}); + final Node root = TreeTestUtils.createTree(new Integer[] {100, 10, 200, 5, 50, 150, 300}); assertEquals(100, CeilInBinarySearchTree.getCeil(root, 75).data); } @Test public void testKeyAbsentLeafIsCeil() { - final Node root = TreeTestUtils.createTree(new Integer[]{100, 10, 200, 5, 50, 150, 300}); + final Node root = TreeTestUtils.createTree(new Integer[] {100, 10, 200, 5, 50, 150, 300}); assertEquals(50, CeilInBinarySearchTree.getCeil(root, 40).data); } @Test public void testKeyAbsentLeftMostNodeIsCeil() { - final Node root = TreeTestUtils.createTree(new Integer[]{100, 10, 200, 5, 50, 150, 300}); + final Node root = TreeTestUtils.createTree(new Integer[] {100, 10, 200, 5, 50, 150, 300}); assertEquals(5, CeilInBinarySearchTree.getCeil(root, 1).data); } @Test public void testKeyAbsentCeilIsNull() { - final Node root = TreeTestUtils.createTree(new Integer[]{100, 10, 200, 5, 50, 150, 300}); + final Node root = TreeTestUtils.createTree(new Integer[] {100, 10, 200, 5, 50, 150, 300}); assertNull(CeilInBinarySearchTree.getCeil(root, 400)); } } diff --git a/src/test/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBSTTest.java b/src/test/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBSTTest.java index 041b2eea..db444e7d 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBSTTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBSTTest.java @@ -1,10 +1,10 @@ package com.thealgorithms.datastructures.trees; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; + /** * @author Albina Gimaletdinova on 17/02/2023 */ @@ -16,7 +16,7 @@ public class CheckBinaryTreeIsValidBSTTest { @Test public void testOneNode() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{Integer.MIN_VALUE}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {Integer.MIN_VALUE}); assertTrue(CheckBinaryTreeIsValidBST.isBST(root)); } @@ -29,7 +29,8 @@ public class CheckBinaryTreeIsValidBSTTest { */ @Test public void testBinaryTreeIsBST() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{9, 7, 13, 3, 8, 10, 20}); + final BinaryTree.Node root + = TreeTestUtils.createTree(new Integer[] {9, 7, 13, 3, 8, 10, 20}); assertTrue(CheckBinaryTreeIsValidBST.isBST(root)); } @@ -42,7 +43,8 @@ public class CheckBinaryTreeIsValidBSTTest { */ @Test public void testBinaryTreeWithDuplicatedNodesIsNotBST() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{9, 7, 13, 3, 8, 10, 13}); + final BinaryTree.Node root + = TreeTestUtils.createTree(new Integer[] {9, 7, 13, 3, 8, 10, 13}); assertFalse(CheckBinaryTreeIsValidBST.isBST(root)); } @@ -55,7 +57,8 @@ public class CheckBinaryTreeIsValidBSTTest { */ @Test public void testBinaryTreeIsNotBST() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{9, 7, 13, 3, 8, 10, 12}); + final BinaryTree.Node root + = TreeTestUtils.createTree(new Integer[] {9, 7, 13, 3, 8, 10, 12}); assertFalse(CheckBinaryTreeIsValidBST.isBST(root)); } } diff --git a/src/test/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetricTest.java b/src/test/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetricTest.java index 932d5b88..a610a32a 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetricTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetricTest.java @@ -1,10 +1,10 @@ package com.thealgorithms.datastructures.trees; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; + /** * @author kumanoit on 10/10/22 IST 1:02 AM */ @@ -17,20 +17,19 @@ public class CheckTreeIsSymmetricTest { @Test public void testSingleNodeTree() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{100}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {100}); assertTrue(CheckTreeIsSymmetric.isSymmetric(root)); } @Test public void testSymmetricTree() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{1,2,2,3,4,4,3}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 2, 3, 4, 4, 3}); assertTrue(CheckTreeIsSymmetric.isSymmetric(root)); } @Test public void testNonSymmetricTree() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{1,2,2,3,5,4,3}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 2, 3, 5, 4, 3}); assertFalse(CheckTreeIsSymmetric.isSymmetric(root)); } - } diff --git a/src/test/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorderTest.java b/src/test/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorderTest.java index 59352f54..53297768 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorderTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorderTest.java @@ -1,10 +1,9 @@ package com.thealgorithms.datastructures.trees; +import java.util.Arrays; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.util.Arrays; - /** * @author Albina Gimaletdinova on 14/05/2023 */ @@ -13,7 +12,8 @@ public class CreateBinaryTreeFromInorderPreorderTest { public void testOnNullArraysShouldReturnNullTree() { // when BinaryTree.Node root = CreateBinaryTreeFromInorderPreorder.createTree(null, null); - BinaryTree.Node rootOpt = CreateBinaryTreeFromInorderPreorder.createTreeOptimized(null, null); + BinaryTree.Node rootOpt + = CreateBinaryTreeFromInorderPreorder.createTreeOptimized(null, null); // then Assertions.assertNull(root); @@ -28,7 +28,8 @@ public class CreateBinaryTreeFromInorderPreorderTest { // when BinaryTree.Node root = CreateBinaryTreeFromInorderPreorder.createTree(preorder, inorder); - BinaryTree.Node rootOpt = CreateBinaryTreeFromInorderPreorder.createTreeOptimized(preorder, inorder); + BinaryTree.Node rootOpt + = CreateBinaryTreeFromInorderPreorder.createTreeOptimized(preorder, inorder); // then Assertions.assertNull(root); @@ -43,7 +44,8 @@ public class CreateBinaryTreeFromInorderPreorderTest { // when BinaryTree.Node root = CreateBinaryTreeFromInorderPreorder.createTree(preorder, inorder); - BinaryTree.Node rootOpt = CreateBinaryTreeFromInorderPreorder.createTreeOptimized(preorder, inorder); + BinaryTree.Node rootOpt + = CreateBinaryTreeFromInorderPreorder.createTreeOptimized(preorder, inorder); // then checkTree(preorder, inorder, root); @@ -58,7 +60,8 @@ public class CreateBinaryTreeFromInorderPreorderTest { // when BinaryTree.Node root = CreateBinaryTreeFromInorderPreorder.createTree(preorder, inorder); - BinaryTree.Node rootOpt = CreateBinaryTreeFromInorderPreorder.createTreeOptimized(preorder, inorder); + BinaryTree.Node rootOpt + = CreateBinaryTreeFromInorderPreorder.createTreeOptimized(preorder, inorder); // then checkTree(preorder, inorder, root); @@ -73,7 +76,8 @@ public class CreateBinaryTreeFromInorderPreorderTest { // when BinaryTree.Node root = CreateBinaryTreeFromInorderPreorder.createTree(preorder, inorder); - BinaryTree.Node rootOpt = CreateBinaryTreeFromInorderPreorder.createTreeOptimized(preorder, inorder); + BinaryTree.Node rootOpt + = CreateBinaryTreeFromInorderPreorder.createTreeOptimized(preorder, inorder); // then checkTree(preorder, inorder, root); @@ -88,7 +92,8 @@ public class CreateBinaryTreeFromInorderPreorderTest { // when BinaryTree.Node root = CreateBinaryTreeFromInorderPreorder.createTree(preorder, inorder); - BinaryTree.Node rootOpt = CreateBinaryTreeFromInorderPreorder.createTreeOptimized(preorder, inorder); + BinaryTree.Node rootOpt + = CreateBinaryTreeFromInorderPreorder.createTreeOptimized(preorder, inorder); // then checkTree(preorder, inorder, root); diff --git a/src/test/java/com/thealgorithms/datastructures/trees/InorderTraversalTest.java b/src/test/java/com/thealgorithms/datastructures/trees/InorderTraversalTest.java index 6b882cae..2b85cf0c 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/InorderTraversalTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/InorderTraversalTest.java @@ -1,11 +1,10 @@ package com.thealgorithms.datastructures.trees; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Collections; import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; /** * @author Albina Gimaletdinova on 21/02/2023 @@ -26,7 +25,7 @@ public class InorderTraversalTest { */ @Test public void testRecursiveInorder() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{1, 2, 3, 4, 5, 6, 7}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7}); List expected = List.of(4, 2, 5, 1, 6, 3, 7); assertEquals(expected, InorderTraversal.recursiveInorder(root)); @@ -44,7 +43,8 @@ public class InorderTraversalTest { */ @Test public void testRecursiveInorderNonBalanced() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{5, null, 6, null, 7, null, 8}); + final BinaryTree.Node root + = TreeTestUtils.createTree(new Integer[] {5, null, 6, null, 7, null, 8}); List expected = List.of(5, 6, 7, 8); assertEquals(expected, InorderTraversal.recursiveInorder(root)); diff --git a/src/test/java/com/thealgorithms/datastructures/trees/KDTreeTest.java b/src/test/java/com/thealgorithms/datastructures/trees/KDTreeTest.java index e4080373..49babb03 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/KDTreeTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/KDTreeTest.java @@ -7,18 +7,18 @@ import org.junit.jupiter.api.Test; public class KDTreeTest { KDTree.Point pointOf(int x, int y) { - return new KDTree.Point(new int[] { x, y }); + return new KDTree.Point(new int[] {x, y}); } @Test void findMin() { int[][] coordinates = { - { 30, 40 }, - { 5, 25 }, - { 70, 70 }, - { 10, 12 }, - { 50, 30 }, - { 35, 45 }, + {30, 40}, + {5, 25}, + {70, 70}, + {10, 12}, + {50, 30}, + {35, 45}, }; KDTree kdTree = new KDTree(coordinates); @@ -29,12 +29,12 @@ public class KDTreeTest { @Test void delete() { int[][] coordinates = { - { 30, 40 }, - { 5, 25 }, - { 70, 70 }, - { 10, 12 }, - { 50, 30 }, - { 35, 45 }, + {30, 40}, + {5, 25}, + {70, 70}, + {10, 12}, + {50, 30}, + {35, 45}, }; KDTree kdTree = new KDTree(coordinates); @@ -46,12 +46,12 @@ public class KDTreeTest { @Test void findNearest() { int[][] coordinates = { - { 2, 3 }, - { 5, 4 }, - { 9, 6 }, - { 4, 7 }, - { 8, 1 }, - { 7, 2 }, + {2, 3}, + {5, 4}, + {9, 6}, + {4, 7}, + {8, 1}, + {7, 2}, }; KDTree kdTree = new KDTree(coordinates); diff --git a/src/test/java/com/thealgorithms/datastructures/trees/LazySegmentTreeTest.java b/src/test/java/com/thealgorithms/datastructures/trees/LazySegmentTreeTest.java index bbec32a7..6df22128 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/LazySegmentTreeTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/LazySegmentTreeTest.java @@ -8,7 +8,7 @@ public class LazySegmentTreeTest { @Test void build() { - int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; LazySegmentTree lazySegmentTree = new LazySegmentTree(arr); assertEquals(55, lazySegmentTree.getRoot().getValue()); assertEquals(15, lazySegmentTree.getRoot().getLeft().getValue()); @@ -17,7 +17,7 @@ public class LazySegmentTreeTest { @Test void update() { - int[] arr = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; + int[] arr = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; LazySegmentTree lazySegmentTree = new LazySegmentTree(arr); assertEquals(10, lazySegmentTree.getRoot().getValue()); @@ -36,7 +36,7 @@ public class LazySegmentTreeTest { @Test void get() { - int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; LazySegmentTree lazySegmentTree = new LazySegmentTree(arr); assertEquals(55, lazySegmentTree.getRange(0, 10)); assertEquals(3, lazySegmentTree.getRange(0, 2)); @@ -46,14 +46,15 @@ public class LazySegmentTreeTest { @Test void updateAndGet() { - int[] arr = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + int[] arr = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; LazySegmentTree lazySegmentTree = new LazySegmentTree(arr); - for (int i = 0; i < 10; i++) for (int j = i + 1; j < 10; j++) { - lazySegmentTree.updateRange(i, j, 1); - assertEquals(j - i, lazySegmentTree.getRange(i, j)); - lazySegmentTree.updateRange(i, j, -1); - assertEquals(0, lazySegmentTree.getRange(i, j)); - } + for (int i = 0; i < 10; i++) + for (int j = i + 1; j < 10; j++) { + lazySegmentTree.updateRange(i, j, 1); + assertEquals(j - i, lazySegmentTree.getRange(i, j)); + lazySegmentTree.updateRange(i, j, -1); + assertEquals(0, lazySegmentTree.getRange(i, j)); + } } } diff --git a/src/test/java/com/thealgorithms/datastructures/trees/LevelOrderTraversalTest.java b/src/test/java/com/thealgorithms/datastructures/trees/LevelOrderTraversalTest.java index 8b0a6b65..d8f5ed92 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/LevelOrderTraversalTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/LevelOrderTraversalTest.java @@ -1,11 +1,10 @@ package com.thealgorithms.datastructures.trees; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Collections; import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; /** * @author Albina Gimaletdinova on 08/02/2023 @@ -18,7 +17,7 @@ public class LevelOrderTraversalTest { @Test public void testSingleNodeTree() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{50}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {50}); assertEquals(List.of(List.of(50)), LevelOrderTraversal.traverse(root)); } @@ -31,8 +30,9 @@ public class LevelOrderTraversalTest { */ @Test public void testLevelOrderTraversalCompleteTree() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{1, 2, 3, 4, 5, 6, 7}); - assertEquals(List.of(List.of(1), List.of(2, 3), List.of(4, 5, 6, 7)), LevelOrderTraversal.traverse(root)); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7}); + assertEquals(List.of(List.of(1), List.of(2, 3), List.of(4, 5, 6, 7)), + LevelOrderTraversal.traverse(root)); } /* @@ -47,8 +47,8 @@ public class LevelOrderTraversalTest { @Test public void testLevelOrderTraversalDifferentHeight() { final BinaryTree.Node root = TreeTestUtils.createTree( - new Integer[]{1, 2, 3, 4, 5, 6, 7, null, null, 8, null, null, 9}); + new Integer[] {1, 2, 3, 4, 5, 6, 7, null, null, 8, null, null, 9}); assertEquals(List.of(List.of(1), List.of(2, 3), List.of(4, 5, 6, 7), List.of(8, 9)), - LevelOrderTraversal.traverse(root)); + LevelOrderTraversal.traverse(root)); } } diff --git a/src/test/java/com/thealgorithms/datastructures/trees/PostOrderTraversalTest.java b/src/test/java/com/thealgorithms/datastructures/trees/PostOrderTraversalTest.java index 2774dc09..1104aa24 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/PostOrderTraversalTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/PostOrderTraversalTest.java @@ -1,11 +1,10 @@ package com.thealgorithms.datastructures.trees; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Collections; import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; /** * Given tree is traversed in a 'post-order' way: LEFT -> RIGHT -> ROOT. @@ -28,7 +27,7 @@ public class PostOrderTraversalTest { */ @Test public void testPostOrder() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{1, 2, 3, 4, 5, 6, 7}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7}); List expected = List.of(4, 5, 2, 6, 7, 3, 1); assertEquals(expected, PostOrderTraversal.recursivePostOrder(root)); @@ -46,7 +45,8 @@ public class PostOrderTraversalTest { */ @Test public void testPostOrderNonBalanced() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{5, null, 6, null, 7, null, 8}); + final BinaryTree.Node root + = TreeTestUtils.createTree(new Integer[] {5, null, 6, null, 7, null, 8}); List expected = List.of(8, 7, 6, 5); assertEquals(expected, PostOrderTraversal.recursivePostOrder(root)); diff --git a/src/test/java/com/thealgorithms/datastructures/trees/PreOrderTraversalTest.java b/src/test/java/com/thealgorithms/datastructures/trees/PreOrderTraversalTest.java index 6f410697..4e1f7102 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/PreOrderTraversalTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/PreOrderTraversalTest.java @@ -1,11 +1,10 @@ package com.thealgorithms.datastructures.trees; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Collections; import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; /** * @author Albina Gimaletdinova on 17/02/2023 @@ -26,7 +25,7 @@ public class PreOrderTraversalTest { */ @Test public void testRecursivePreOrder() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{1, 2, 3, 4, 5, 6, 7}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7}); List expected = List.of(1, 2, 4, 5, 3, 6, 7); assertEquals(expected, PreOrderTraversal.recursivePreOrder(root)); @@ -44,7 +43,8 @@ public class PreOrderTraversalTest { */ @Test public void testRecursivePreOrderNonBalanced() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{5, null, 6, null, 7, null, 8}); + final BinaryTree.Node root + = TreeTestUtils.createTree(new Integer[] {5, null, 6, null, 7, null, 8}); List expected = List.of(5, 6, 7, 8); assertEquals(expected, PreOrderTraversal.recursivePreOrder(root)); diff --git a/src/test/java/com/thealgorithms/datastructures/trees/SameTreesCheckTest.java b/src/test/java/com/thealgorithms/datastructures/trees/SameTreesCheckTest.java index 365ee99f..44022288 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/SameTreesCheckTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/SameTreesCheckTest.java @@ -1,10 +1,10 @@ package com.thealgorithms.datastructures.trees; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; + /** * @author Albina Gimaletdinova on 12/01/2023 */ @@ -16,14 +16,14 @@ public class SameTreesCheckTest { @Test public void testOneRootIsNull() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{100}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {100}); assertFalse(SameTreesCheck.check(root, null)); } @Test public void testSingleNodeTreesAreSame() { - final BinaryTree.Node p = TreeTestUtils.createTree(new Integer[]{100}); - final BinaryTree.Node q = TreeTestUtils.createTree(new Integer[]{100}); + final BinaryTree.Node p = TreeTestUtils.createTree(new Integer[] {100}); + final BinaryTree.Node q = TreeTestUtils.createTree(new Integer[] {100}); assertTrue(SameTreesCheck.check(p, q)); } @@ -36,12 +36,11 @@ public class SameTreesCheckTest { */ @Test public void testSameTreesIsSuccessful() { - final BinaryTree.Node p = TreeTestUtils.createTree(new Integer[]{1, 2, 3, 4, 5, 6, 7}); - final BinaryTree.Node q = TreeTestUtils.createTree(new Integer[]{1, 2, 3, 4, 5, 6, 7}); + final BinaryTree.Node p = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7}); + final BinaryTree.Node q = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7}); assertTrue(SameTreesCheck.check(p, q)); } - /* 1 1 / \ / \ @@ -51,8 +50,8 @@ public class SameTreesCheckTest { */ @Test public void testSameTreesFails() { - final BinaryTree.Node p = TreeTestUtils.createTree(new Integer[]{1, 2, 3, 4, 5, 6, 7}); - final BinaryTree.Node q = TreeTestUtils.createTree(new Integer[]{1, 2, 3, 4, 5, 6}); + final BinaryTree.Node p = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7}); + final BinaryTree.Node q = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6}); assertFalse(SameTreesCheck.check(p, q)); } @@ -63,9 +62,8 @@ public class SameTreesCheckTest { */ @Test public void testTreesWithDifferentStructure() { - final BinaryTree.Node p = TreeTestUtils.createTree(new Integer[]{1, 2}); - final BinaryTree.Node q = TreeTestUtils.createTree(new Integer[]{1, null, 2}); + final BinaryTree.Node p = TreeTestUtils.createTree(new Integer[] {1, 2}); + final BinaryTree.Node q = TreeTestUtils.createTree(new Integer[] {1, null, 2}); assertFalse(SameTreesCheck.check(p, q)); } } - diff --git a/src/test/java/com/thealgorithms/datastructures/trees/TreeTestUtils.java b/src/test/java/com/thealgorithms/datastructures/trees/TreeTestUtils.java index 454aaae0..3bd197bf 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/TreeTestUtils.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/TreeTestUtils.java @@ -1,8 +1,8 @@ package com.thealgorithms.datastructures.trees; +import com.thealgorithms.datastructures.trees.BinaryTree.Node; import java.util.LinkedList; import java.util.Queue; -import com.thealgorithms.datastructures.trees.BinaryTree.Node; public class TreeTestUtils { diff --git a/src/test/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversalTest.java b/src/test/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversalTest.java index 74b036d1..4b80a308 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversalTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversalTest.java @@ -1,11 +1,10 @@ package com.thealgorithms.datastructures.trees; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Collections; import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; /** * @author Albina Gimaletdinova on 13/01/2023 @@ -18,7 +17,7 @@ public class VerticalOrderTraversalTest { @Test public void testSingleNodeTree() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{50}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {50}); assertEquals(List.of(50), VerticalOrderTraversal.verticalTraversal(root)); } @@ -31,7 +30,7 @@ public class VerticalOrderTraversalTest { */ @Test public void testVerticalTraversalCompleteTree() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{1, 2, 3, 4, 5, 6, 7}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7}); assertEquals(List.of(4, 2, 1, 5, 6, 3, 7), VerticalOrderTraversal.verticalTraversal(root)); } @@ -47,7 +46,8 @@ public class VerticalOrderTraversalTest { @Test public void testVerticalTraversalDifferentHeight() { final BinaryTree.Node root = TreeTestUtils.createTree( - new Integer[]{1, 2, 3, 4, 5, 6, 7, null, null, 8, null, null, 9}); - assertEquals(List.of(4, 2, 8, 1, 5, 6, 3, 9, 7), VerticalOrderTraversal.verticalTraversal(root)); + new Integer[] {1, 2, 3, 4, 5, 6, 7, null, null, 8, null, null, 9}); + assertEquals( + List.of(4, 2, 8, 1, 5, 6, 3, 9, 7), VerticalOrderTraversal.verticalTraversal(root)); } } diff --git a/src/test/java/com/thealgorithms/datastructures/trees/ZigzagTraversalTest.java b/src/test/java/com/thealgorithms/datastructures/trees/ZigzagTraversalTest.java index 6b89fcff..5ac0012b 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/ZigzagTraversalTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/ZigzagTraversalTest.java @@ -1,11 +1,10 @@ package com.thealgorithms.datastructures.trees; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Collections; import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; /** * @author Albina Gimaletdinova on 11/01/2023 @@ -18,7 +17,7 @@ public class ZigzagTraversalTest { @Test public void testSingleNodeTree() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{50}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {50}); assertEquals(List.of(List.of(50)), ZigzagTraversal.traverse(root)); } @@ -31,8 +30,9 @@ public class ZigzagTraversalTest { */ @Test public void testZigzagTraversalCompleteTree() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{1, 2, 3, 4, 5, 6, 7}); - assertEquals(List.of(List.of(1), List.of(3, 2), List.of(4, 5, 6, 7)), ZigzagTraversal.traverse(root)); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7}); + assertEquals(List.of(List.of(1), List.of(3, 2), List.of(4, 5, 6, 7)), + ZigzagTraversal.traverse(root)); } /* @@ -47,8 +47,8 @@ public class ZigzagTraversalTest { @Test public void testZigzagTraversalDifferentHeight() { final BinaryTree.Node root = TreeTestUtils.createTree( - new Integer[]{1, 2, 3, 4, 5, 6, 7, null, null, 8, null, null, 9}); + new Integer[] {1, 2, 3, 4, 5, 6, 7, null, null, 8, null, null, 9}); assertEquals(List.of(List.of(1), List.of(3, 2), List.of(4, 5, 6, 7), List.of(9, 8)), - ZigzagTraversal.traverse(root)); + ZigzagTraversal.traverse(root)); } } diff --git a/src/test/java/com/thealgorithms/divideandconquer/BinaryExponentiationTest.java b/src/test/java/com/thealgorithms/divideandconquer/BinaryExponentiationTest.java index df9cce34..bf1a60e8 100644 --- a/src/test/java/com/thealgorithms/divideandconquer/BinaryExponentiationTest.java +++ b/src/test/java/com/thealgorithms/divideandconquer/BinaryExponentiationTest.java @@ -35,5 +35,4 @@ public class BinaryExponentiationTest { assertEquals(1, new BinaryExponentiation().power(1, 10000000000000000L)); assertEquals(1, new BinaryExponentiation().power(1, 100000000000000000L)); } - } diff --git a/src/test/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplicationTest.java b/src/test/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplicationTest.java index adc6871b..7fb4f178 100644 --- a/src/test/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplicationTest.java +++ b/src/test/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplicationTest.java @@ -13,30 +13,29 @@ class StrassenMatrixMultiplicationTest { @Test public void StrassenMatrixMultiplicationTest2x2() { - int[][] A = { { 1, 2 }, { 3, 4 } }; - int[][] B = { { 5, 6 }, { 7, 8 } }; - int[][] expResult = { { 19, 22 }, { 43, 50 } }; + int[][] A = {{1, 2}, {3, 4}}; + int[][] B = {{5, 6}, {7, 8}}; + int[][] expResult = {{19, 22}, {43, 50}}; int[][] actResult = SMM.multiply(A, B); assertArrayEquals(expResult, actResult); } @Test void StrassenMatrixMultiplicationTest4x4() { - int[][] A = { { 1, 2, 5, 4 }, { 9, 3, 0, 6 }, { 4, 6, 3, 1 }, { 0, 2, 0, 6 } }; - int[][] B = { { 1, 0, 4, 1 }, { 1, 2, 0, 2 }, { 0, 3, 1, 3 }, { 1, 8, 1, 2 } }; - int[][] expResult = { { 7, 51, 13, 28 }, { 18, 54, 42, 27 }, { 11, 29, 20, 27 }, { 8, 52, 6, 16 } }; + int[][] A = {{1, 2, 5, 4}, {9, 3, 0, 6}, {4, 6, 3, 1}, {0, 2, 0, 6}}; + int[][] B = {{1, 0, 4, 1}, {1, 2, 0, 2}, {0, 3, 1, 3}, {1, 8, 1, 2}}; + int[][] expResult = {{7, 51, 13, 28}, {18, 54, 42, 27}, {11, 29, 20, 27}, {8, 52, 6, 16}}; int[][] actResult = SMM.multiply(A, B); assertArrayEquals(expResult, actResult); } @Test void StrassenMatrixMultiplicationTestNegetiveNumber4x4() { - int[][] A = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; - int[][] B = { { 1, -2, -3, 4 }, { 4, -3, -2, 1 }, { 5, -6, -7, 8 }, { 8, -7, -6, -5 } }; - int[][] expResult = { { 56, -54, -52, 10 }, { 128, -126, -124, 42 }, { 200, -198, -196, 74 }, - { 272, -270, -268, 106 } }; + int[][] A = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; + int[][] B = {{1, -2, -3, 4}, {4, -3, -2, 1}, {5, -6, -7, 8}, {8, -7, -6, -5}}; + int[][] expResult = {{56, -54, -52, 10}, {128, -126, -124, 42}, {200, -198, -196, 74}, + {272, -270, -268, 106}}; int[][] actResult = SMM.multiply(A, B); assertArrayEquals(expResult, actResult); } - } \ No newline at end of file diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/EggDroppingTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/EggDroppingTest.java index 7d13caab..bc569cc2 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/EggDroppingTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/EggDroppingTest.java @@ -1,28 +1,28 @@ package com.thealgorithms.dynamicprogramming; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + public class EggDroppingTest { @Test - void hasMultipleEggSingleFloor(){ - assertEquals(1,EggDropping.minTrials(3,1)); + void hasMultipleEggSingleFloor() { + assertEquals(1, EggDropping.minTrials(3, 1)); } @Test - void hasSingleEggSingleFloor(){ - assertEquals(1,EggDropping.minTrials(1,1)); + void hasSingleEggSingleFloor() { + assertEquals(1, EggDropping.minTrials(1, 1)); } @Test - void hasSingleEggMultipleFloor(){ - assertEquals(3,EggDropping.minTrials(1,3)); + void hasSingleEggMultipleFloor() { + assertEquals(3, EggDropping.minTrials(1, 3)); } @Test - void hasMultipleEggMultipleFloor(){ - assertEquals(7,EggDropping.minTrials(100,101)); + void hasMultipleEggMultipleFloor() { + assertEquals(7, EggDropping.minTrials(100, 101)); } } diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/KnapsackMemoizationTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/KnapsackMemoizationTest.java index 7d06618c..0a15144f 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/KnapsackMemoizationTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/KnapsackMemoizationTest.java @@ -1,34 +1,34 @@ package com.thealgorithms.dynamicprogramming; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + public class KnapsackMemoizationTest { KnapsackMemoization knapsackMemoization = new KnapsackMemoization(); @Test void Test1() { - int[] weight = { 1, 3, 4, 5 }; - int[] value = { 1, 4, 5, 7 }; + int[] weight = {1, 3, 4, 5}; + int[] value = {1, 4, 5, 7}; int capacity = 10; assertEquals(13, knapsackMemoization.knapSack(capacity, weight, value, weight.length)); } @Test void Test2() { - int[] weight = { 95, 4, 60, 32, 23, 72, 80, 62, 65, 46 }; - int[] value = { 55, 10, 47, 5, 4, 50, 8, 61, 85, 87 }; + int[] weight = {95, 4, 60, 32, 23, 72, 80, 62, 65, 46}; + int[] value = {55, 10, 47, 5, 4, 50, 8, 61, 85, 87}; int capacity = 269; assertEquals(295, knapsackMemoization.knapSack(capacity, weight, value, weight.length)); } @Test void Test3() { - int[] weight = { 10, 20, 30 }; - int[] value = { 60, 100, 120 }; + int[] weight = {10, 20, 30}; + int[] value = {60, 100, 120}; int capacity = 50; assertEquals(220, knapsackMemoization.knapSack(capacity, weight, value, weight.length)); } - } \ No newline at end of file diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/LevenshteinDistanceTests.java b/src/test/java/com/thealgorithms/dynamicprogramming/LevenshteinDistanceTests.java index 4e3cfa3c..a22bf3fe 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/LevenshteinDistanceTests.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/LevenshteinDistanceTests.java @@ -1,10 +1,10 @@ package com.thealgorithms.dynamicprogramming; +import static org.junit.jupiter.api.Assertions.assertEquals; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; -import static org.junit.jupiter.api.Assertions.assertEquals; - public class LevenshteinDistanceTests { @ParameterizedTest @@ -13,5 +13,4 @@ public class LevenshteinDistanceTests { int result = LevenshteinDistance.calculateLevenshteinDistance(str1, str2); assertEquals(distance, result); } - } diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/OptimalJobSchedulingTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/OptimalJobSchedulingTest.java index 9b1afc6d..7e673ed7 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/OptimalJobSchedulingTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/OptimalJobSchedulingTest.java @@ -1,127 +1,101 @@ package com.thealgorithms.dynamicprogramming; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + /** * @author georgioct@csd.auth.gr */ public class OptimalJobSchedulingTest { @Test - public void testOptimalJobScheduling1(){ + public void testOptimalJobScheduling1() { int numberProcesses = 5; int numberMachines = 4; - int[][] Run = { - {5, 1, 3, 2}, - {4, 2, 1, 3}, - {1, 5, 2, 1}, - {2, 3, 4, 2}, - {1, 1, 3, 1}}; + int[][] Run = {{5, 1, 3, 2}, {4, 2, 1, 3}, {1, 5, 2, 1}, {2, 3, 4, 2}, {1, 1, 3, 1}}; - int[][] Transfer = { - {0, 1, 2, 4}, - {1, 0, 2, 3}, - {2, 2, 0, 1}, - {4, 3, 1, 0}}; + int[][] Transfer = {{0, 1, 2, 4}, {1, 0, 2, 3}, {2, 2, 0, 1}, {4, 3, 1, 0}}; - OptimalJobScheduling opt = new OptimalJobScheduling(numberProcesses,numberMachines,Run,Transfer); + OptimalJobScheduling opt + = new OptimalJobScheduling(numberProcesses, numberMachines, Run, Transfer); opt.execute(); + int[][] costs = {{5, 1, 3, 2}, {6, 3, 4, 5}, {5, 8, 6, 6}, {7, 9, 10, 8}, {8, 9, 12, 9}}; - int[][] costs = { - {5, 1, 3, 2}, - {6, 3, 4, 5}, - {5, 8, 6, 6}, - {7, 9, 10, 8}, - {8, 9, 12, 9}}; + for (int i = 0; i < numberProcesses; i++) { - for (int i=0; i < numberProcesses; i++){ + for (int j = 0; j < numberMachines; j++) { - for (int j=0; j < numberMachines; j++){ - - assertEquals(costs[i][j],opt.getCost(i,j)); + assertEquals(costs[i][j], opt.getCost(i, j)); } } } @Test - public void testOptimalJobScheduling2(){ + public void testOptimalJobScheduling2() { int numberProcesses = 3; int numberMachines = 3; - int[][] Run = { - {5, 1, 3}, - {4, 2, 1}, - {1, 5, 2}}; + int[][] Run = {{5, 1, 3}, {4, 2, 1}, {1, 5, 2}}; - int[][] Transfer = { - {0, 1, 2}, - {1, 0, 2}, - {2, 2, 0}}; + int[][] Transfer = {{0, 1, 2}, {1, 0, 2}, {2, 2, 0}}; - OptimalJobScheduling opt = new OptimalJobScheduling(numberProcesses,numberMachines,Run,Transfer); + OptimalJobScheduling opt + = new OptimalJobScheduling(numberProcesses, numberMachines, Run, Transfer); opt.execute(); - int[][] costs = { - {5, 1, 3}, - {6, 3, 4}, - {5, 8, 6}}; + int[][] costs = {{5, 1, 3}, {6, 3, 4}, {5, 8, 6}}; - for (int i=0; i < numberProcesses; i++){ + for (int i = 0; i < numberProcesses; i++) { - for (int j=0; j < numberMachines; j++){ + for (int j = 0; j < numberMachines; j++) { - assertEquals(costs[i][j],opt.getCost(i,j)); + assertEquals(costs[i][j], opt.getCost(i, j)); } } } @Test - public void testOptimalJobScheduling3(){ + public void testOptimalJobScheduling3() { int numberProcesses = 6; int numberMachines = 4; int[][] Run = { - {5, 1, 3, 2}, - {4, 2, 1, 1}, - {1, 5, 2, 6}, - {1, 1, 2, 3}, - {2, 1, 4, 6}, - {3, 2, 2, 3}, + {5, 1, 3, 2}, + {4, 2, 1, 1}, + {1, 5, 2, 6}, + {1, 1, 2, 3}, + {2, 1, 4, 6}, + {3, 2, 2, 3}, }; int[][] Transfer = { - {0, 1, 2, 1}, - {1, 0, 2, 3}, - {2, 2, 0, 2}, - {1, 3, 2, 0}, + {0, 1, 2, 1}, + {1, 0, 2, 3}, + {2, 2, 0, 2}, + {1, 3, 2, 0}, }; - OptimalJobScheduling opt = new OptimalJobScheduling(numberProcesses,numberMachines,Run,Transfer); + OptimalJobScheduling opt + = new OptimalJobScheduling(numberProcesses, numberMachines, Run, Transfer); opt.execute(); - int[][] costs = { - {5, 1, 3, 2}, - {6, 3, 4, 3}, - {5, 8, 6, 9}, - {6, 7, 8, 9}, - {8, 8, 12, 13}, - {11, 10, 12, 12}}; + int[][] costs = {{5, 1, 3, 2}, {6, 3, 4, 3}, {5, 8, 6, 9}, {6, 7, 8, 9}, {8, 8, 12, 13}, + {11, 10, 12, 12}}; - for (int i=0; i < numberProcesses; i++){ + for (int i = 0; i < numberProcesses; i++) { - for (int j=0; j < numberMachines; j++){ + for (int j = 0; j < numberMachines; j++) { - assertEquals(costs[i][j],opt.getCost(i,j)); + assertEquals(costs[i][j], opt.getCost(i, j)); } } } diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/PartitionProblemTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/PartitionProblemTest.java index ad0aac26..ebd6ba12 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/PartitionProblemTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/PartitionProblemTest.java @@ -1,24 +1,24 @@ package com.thealgorithms.dynamicprogramming; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + class PartitionProblemTest { @Test - public void testIfSumOfTheArrayIsOdd(){ - assertFalse(PartitionProblem.partition(new int[]{1, 2, 2})); + public void testIfSumOfTheArrayIsOdd() { + assertFalse(PartitionProblem.partition(new int[] {1, 2, 2})); } @Test - public void testIfSizeOfTheArrayIsOne(){ - assertFalse(PartitionProblem.partition(new int[]{2})); + public void testIfSizeOfTheArrayIsOne() { + assertFalse(PartitionProblem.partition(new int[] {2})); } @Test - public void testIfSumOfTheArrayIsEven1(){ - assertTrue(PartitionProblem.partition(new int[]{1, 2, 3, 6})); + public void testIfSumOfTheArrayIsEven1() { + assertTrue(PartitionProblem.partition(new int[] {1, 2, 3, 6})); } @Test - public void testIfSumOfTheArrayIsEven2(){ - assertFalse(PartitionProblem.partition(new int[]{1, 2, 3, 8})); + public void testIfSumOfTheArrayIsEven2() { + assertFalse(PartitionProblem.partition(new int[] {1, 2, 3, 8})); } } \ No newline at end of file diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/SubsetCountTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/SubsetCountTest.java index 5a532067..13f7b6f9 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/SubsetCountTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/SubsetCountTest.java @@ -1,30 +1,31 @@ package com.thealgorithms.dynamicprogramming; import static org.junit.jupiter.api.Assertions.assertEquals; + import org.junit.jupiter.api.Test; public class SubsetCountTest { public static SubsetCount obj = new SubsetCount(); @Test - void hasMultipleSubset(){ - int[] arr = new int[]{1,2,3,3}; + void hasMultipleSubset() { + int[] arr = new int[] {1, 2, 3, 3}; assertEquals(3, obj.getCount(arr, 6)); } @Test - void singleElementSubset(){ - int[] arr = new int[]{1,1,1,1}; + void singleElementSubset() { + int[] arr = new int[] {1, 1, 1, 1}; assertEquals(4, obj.getCount(arr, 1)); } @Test - void hasMultipleSubsetSO(){ - int[] arr = new int[]{1,2,3,3}; + void hasMultipleSubsetSO() { + int[] arr = new int[] {1, 2, 3, 3}; assertEquals(3, obj.getCountSO(arr, 6)); } @Test - void singleSubsetSO(){ - int[] arr = new int[]{1,1,1,1}; - assertEquals(1,obj.getCountSO(arr, 4)); + void singleSubsetSO() { + int[] arr = new int[] {1, 1, 1, 1}; + assertEquals(1, obj.getCountSO(arr, 4)); } } diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/climbStairsTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/climbStairsTest.java index bc6b4adb..7df3127e 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/climbStairsTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/climbStairsTest.java @@ -1,24 +1,33 @@ package com.thealgorithms.dynamicprogramming; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; public class climbStairsTest { @Test - void climbStairsTestForTwo(){assertEquals(2, ClimbingStairs.numberOfWays(2));} + void climbStairsTestForTwo() { + assertEquals(2, ClimbingStairs.numberOfWays(2)); + } @Test - void climbStairsTestForZero(){assertEquals(0, ClimbingStairs.numberOfWays(0));} + void climbStairsTestForZero() { + assertEquals(0, ClimbingStairs.numberOfWays(0)); + } @Test - void climbStairsTestForOne(){assertEquals(1, ClimbingStairs.numberOfWays(1));} + void climbStairsTestForOne() { + assertEquals(1, ClimbingStairs.numberOfWays(1)); + } @Test - void climbStairsTestForFive(){assertEquals(8, ClimbingStairs.numberOfWays(5));} + void climbStairsTestForFive() { + assertEquals(8, ClimbingStairs.numberOfWays(5)); + } @Test - void climbStairsTestForThree(){assertEquals(3, ClimbingStairs.numberOfWays(3));} + void climbStairsTestForThree() { + assertEquals(3, ClimbingStairs.numberOfWays(3)); + } } diff --git a/src/test/java/com/thealgorithms/geometry/GrahamScanTest.java b/src/test/java/com/thealgorithms/geometry/GrahamScanTest.java index c31802f9..8d52f2b9 100644 --- a/src/test/java/com/thealgorithms/geometry/GrahamScanTest.java +++ b/src/test/java/com/thealgorithms/geometry/GrahamScanTest.java @@ -1,16 +1,15 @@ package com.thealgorithms.geometry; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + public class GrahamScanTest { @Test void testGrahamScan() { GrahamScan.Point[] points = {new GrahamScan.Point(0, 3), new GrahamScan.Point(1, 1), - new GrahamScan.Point(2, 2), new GrahamScan.Point(4, 4), - new GrahamScan.Point(0, 0), new GrahamScan.Point(1, 2), - new GrahamScan.Point(3, 1), new GrahamScan.Point(3, 3)}; + new GrahamScan.Point(2, 2), new GrahamScan.Point(4, 4), new GrahamScan.Point(0, 0), + new GrahamScan.Point(1, 2), new GrahamScan.Point(3, 1), new GrahamScan.Point(3, 3)}; String expectedResult = "[(0, 0), (3, 1), (4, 4), (0, 3)]"; GrahamScan graham = new GrahamScan(points); diff --git a/src/test/java/com/thealgorithms/io/BufferedReaderTest.java b/src/test/java/com/thealgorithms/io/BufferedReaderTest.java index 5d0c3b06..5d4c0f84 100644 --- a/src/test/java/com/thealgorithms/io/BufferedReaderTest.java +++ b/src/test/java/com/thealgorithms/io/BufferedReaderTest.java @@ -1,102 +1,99 @@ package com.thealgorithms.io; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.*; - -import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; class BufferedReaderTest { - @Test - public void testPeeks() throws IOException { - String text = "Hello!\nWorld!"; - int len = text.length(); - byte[] bytes = text.getBytes(); + @Test + public void testPeeks() throws IOException { + String text = "Hello!\nWorld!"; + int len = text.length(); + byte[] bytes = text.getBytes(); - ByteArrayInputStream input = new ByteArrayInputStream(bytes); - BufferedReader reader = new BufferedReader(input); + ByteArrayInputStream input = new ByteArrayInputStream(bytes); + BufferedReader reader = new BufferedReader(input); - // read the first letter - assertEquals(reader.read(), 'H'); - len--; - assertEquals(reader.available(), len); + // read the first letter + assertEquals(reader.read(), 'H'); + len--; + assertEquals(reader.available(), len); - // position: H[e]llo!\nWorld! - // reader.read() will be == 'e' - assertEquals(reader.peek(1), 'l'); - assertEquals(reader.peek(2), 'l'); // second l - assertEquals(reader.peek(3), 'o'); - } - - @Test - public void testMixes() throws IOException { - String text = "Hello!\nWorld!"; - int len = text.length(); - byte[] bytes = text.getBytes(); - - ByteArrayInputStream input = new ByteArrayInputStream(bytes); - BufferedReader reader = new BufferedReader(input); - - // read the first letter - assertEquals(reader.read(), 'H'); // first letter - len--; - - assertEquals(reader.peek(1), 'l'); // third later (second letter after 'H') - assertEquals(reader.read(), 'e'); // second letter - len--; - assertEquals(reader.available(), len); - - // position: H[e]llo!\nWorld! - assertEquals(reader.peek(2), 'o'); // second l - assertEquals(reader.peek(3), '!'); - assertEquals(reader.peek(4), '\n'); - - assertEquals(reader.read(), 'l'); // third letter - assertEquals(reader.peek(1), 'o'); // fourth letter - - for (int i = 0; i < 6; i++) - reader.read(); - try { - System.out.println((char) reader.peek(4)); - } catch (Exception ignored) { - System.out.println("[cached intentional error]"); - // intentional, for testing purpose + // position: H[e]llo!\nWorld! + // reader.read() will be == 'e' + assertEquals(reader.peek(1), 'l'); + assertEquals(reader.peek(2), 'l'); // second l + assertEquals(reader.peek(3), 'o'); } - } - @Test - public void testBlockPractical() throws IOException { - String text = "!Hello\nWorld!"; - byte[] bytes = text.getBytes(); - int len = bytes.length; + @Test + public void testMixes() throws IOException { + String text = "Hello!\nWorld!"; + int len = text.length(); + byte[] bytes = text.getBytes(); - ByteArrayInputStream input = new ByteArrayInputStream(bytes); - BufferedReader reader = new BufferedReader(input); + ByteArrayInputStream input = new ByteArrayInputStream(bytes); + BufferedReader reader = new BufferedReader(input); + // read the first letter + assertEquals(reader.read(), 'H'); // first letter + len--; - assertEquals(reader.peek(), 'H'); - assertEquals(reader.read(), '!'); // read the first letter - len--; + assertEquals(reader.peek(1), 'l'); // third later (second letter after 'H') + assertEquals(reader.read(), 'e'); // second letter + len--; + assertEquals(reader.available(), len); - // this only reads the next 5 bytes (Hello) because - // the default buffer size = 5 - assertEquals(new String(reader.readBlock()), "Hello"); - len -= 5; - assertEquals(reader.available(), len); + // position: H[e]llo!\nWorld! + assertEquals(reader.peek(2), 'o'); // second l + assertEquals(reader.peek(3), '!'); + assertEquals(reader.peek(4), '\n'); - // maybe kind of a practical demonstration / use case - if (reader.read() == '\n') { - assertEquals(reader.read(), 'W'); - assertEquals(reader.read(), 'o'); + assertEquals(reader.read(), 'l'); // third letter + assertEquals(reader.peek(1), 'o'); // fourth letter - // the rest of the blocks - assertEquals(new String(reader.readBlock()), "rld!"); - } else { - // should not reach - throw new IOException("Something not right"); + for (int i = 0; i < 6; i++) reader.read(); + try { + System.out.println((char) reader.peek(4)); + } catch (Exception ignored) { + System.out.println("[cached intentional error]"); + // intentional, for testing purpose + } + } + + @Test + public void testBlockPractical() throws IOException { + String text = "!Hello\nWorld!"; + byte[] bytes = text.getBytes(); + int len = bytes.length; + + ByteArrayInputStream input = new ByteArrayInputStream(bytes); + BufferedReader reader = new BufferedReader(input); + + assertEquals(reader.peek(), 'H'); + assertEquals(reader.read(), '!'); // read the first letter + len--; + + // this only reads the next 5 bytes (Hello) because + // the default buffer size = 5 + assertEquals(new String(reader.readBlock()), "Hello"); + len -= 5; + assertEquals(reader.available(), len); + + // maybe kind of a practical demonstration / use case + if (reader.read() == '\n') { + assertEquals(reader.read(), 'W'); + assertEquals(reader.read(), 'o'); + + // the rest of the blocks + assertEquals(new String(reader.readBlock()), "rld!"); + } else { + // should not reach + throw new IOException("Something not right"); + } } - } } diff --git a/src/test/java/com/thealgorithms/maths/ADTFractionTest.java b/src/test/java/com/thealgorithms/maths/ADTFractionTest.java index 2da961d7..eba7f2b4 100644 --- a/src/test/java/com/thealgorithms/maths/ADTFractionTest.java +++ b/src/test/java/com/thealgorithms/maths/ADTFractionTest.java @@ -13,10 +13,8 @@ public class ADTFractionTest { @Test void testConstructorWithDenominatorEqualToZero() { - Exception exception = assertThrows( - IllegalArgumentException.class, - () -> new ADTFraction(1, 0) - ); + Exception exception + = assertThrows(IllegalArgumentException.class, () -> new ADTFraction(1, 0)); assertEquals("Denominator cannot be 0", exception.getMessage()); } diff --git a/src/test/java/com/thealgorithms/maths/AbsoluteMinTest.java b/src/test/java/com/thealgorithms/maths/AbsoluteMinTest.java index 6322341d..c1dae574 100644 --- a/src/test/java/com/thealgorithms/maths/AbsoluteMinTest.java +++ b/src/test/java/com/thealgorithms/maths/AbsoluteMinTest.java @@ -15,10 +15,8 @@ public class AbsoluteMinTest { @Test void testGetMinValueWithNoArguments() { - Exception exception = assertThrows( - IllegalArgumentException.class, - () -> AbsoluteMin.getMinValue() - ); + Exception exception + = assertThrows(IllegalArgumentException.class, () -> AbsoluteMin.getMinValue()); assertEquals("Numbers array cannot be empty", exception.getMessage()); } } diff --git a/src/test/java/com/thealgorithms/maths/AbsoluteValueTest.java b/src/test/java/com/thealgorithms/maths/AbsoluteValueTest.java index 9f5a3730..3d1b58a5 100644 --- a/src/test/java/com/thealgorithms/maths/AbsoluteValueTest.java +++ b/src/test/java/com/thealgorithms/maths/AbsoluteValueTest.java @@ -10,14 +10,8 @@ public class AbsoluteValueTest { @Test void testGetAbsValue() { - Stream - .generate(() -> ThreadLocalRandom.current().nextInt()) + Stream.generate(() -> ThreadLocalRandom.current().nextInt()) .limit(1000) - .forEach(number -> - assertEquals( - Math.abs(number), - AbsoluteValue.getAbsValue(number) - ) - ); + .forEach(number -> assertEquals(Math.abs(number), AbsoluteValue.getAbsValue(number))); } } diff --git a/src/test/java/com/thealgorithms/maths/AreaTest.java b/src/test/java/com/thealgorithms/maths/AreaTest.java index 6020054c..3e4485e1 100644 --- a/src/test/java/com/thealgorithms/maths/AreaTest.java +++ b/src/test/java/com/thealgorithms/maths/AreaTest.java @@ -1,9 +1,9 @@ package com.thealgorithms.maths; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + /** * @author Amarildo Aliaj */ @@ -67,24 +67,52 @@ class AreaTest { @Test void testAllIllegalInput() { assertAll( - () -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaCube(0)), - () -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaSphere(0)), - () -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaRectangle(0, 10)), - () -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaRectangle(10, 0)), - () -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaCylinder(0, 1)), - () -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaCylinder(1, 0)), - () -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaSquare(0)), - () -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaTriangleRectangle(0, 1)), - () -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaTriangleRectangle(1, 0)), - () -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaParallelogram(0, 1)), - () -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaParallelogram(1, 0)), - () -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaTrapezium(0, 1, 1)), - () -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaTrapezium(1, 0, 1)), - () -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaTrapezium(1, 1, 0)), - () -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaCircle(0)), - () -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaHemisphere(0)), - () -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaCone(1, 0)), - () -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaCone(0, 1)) - ); + () + -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaCube(0)), + () + -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaSphere(0)), + () + -> assertThrows( + IllegalArgumentException.class, () -> Area.surfaceAreaRectangle(0, 10)), + () + -> assertThrows( + IllegalArgumentException.class, () -> Area.surfaceAreaRectangle(10, 0)), + () + -> assertThrows( + IllegalArgumentException.class, () -> Area.surfaceAreaCylinder(0, 1)), + () + -> assertThrows( + IllegalArgumentException.class, () -> Area.surfaceAreaCylinder(1, 0)), + () + -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaSquare(0)), + () + -> assertThrows( + IllegalArgumentException.class, () -> Area.surfaceAreaTriangleRectangle(0, 1)), + () + -> assertThrows( + IllegalArgumentException.class, () -> Area.surfaceAreaTriangleRectangle(1, 0)), + () + -> assertThrows( + IllegalArgumentException.class, () -> Area.surfaceAreaParallelogram(0, 1)), + () + -> assertThrows( + IllegalArgumentException.class, () -> Area.surfaceAreaParallelogram(1, 0)), + () + -> assertThrows( + IllegalArgumentException.class, () -> Area.surfaceAreaTrapezium(0, 1, 1)), + () + -> assertThrows( + IllegalArgumentException.class, () -> Area.surfaceAreaTrapezium(1, 0, 1)), + () + -> assertThrows( + IllegalArgumentException.class, () -> Area.surfaceAreaTrapezium(1, 1, 0)), + () + -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaCircle(0)), + () + -> assertThrows( + IllegalArgumentException.class, () -> Area.surfaceAreaHemisphere(0)), + () + -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaCone(1, 0)), + () -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaCone(0, 1))); } } \ No newline at end of file diff --git a/src/test/java/com/thealgorithms/maths/AutomorphicNumberTest.java b/src/test/java/com/thealgorithms/maths/AutomorphicNumberTest.java index 29125efe..c322cdc6 100644 --- a/src/test/java/com/thealgorithms/maths/AutomorphicNumberTest.java +++ b/src/test/java/com/thealgorithms/maths/AutomorphicNumberTest.java @@ -1,14 +1,15 @@ package com.thealgorithms.maths; import static org.junit.jupiter.api.Assertions.*; + import org.junit.jupiter.api.Test; public class AutomorphicNumberTest { @Test void testAutomorphicNumber() { - int[] trueTestCases = { 0, 1, 25, 625, 12890625}; - int[] falseTestCases = { -5, 2, 26, 1234 }; + int[] trueTestCases = {0, 1, 25, 625, 12890625}; + int[] falseTestCases = {-5, 2, 26, 1234}; for (Integer n : trueTestCases) { assertTrue(AutomorphicNumber.isAutomorphic(n)); assertTrue(AutomorphicNumber.isAutomorphic2(n)); @@ -19,7 +20,9 @@ public class AutomorphicNumberTest { assertFalse(AutomorphicNumber.isAutomorphic2(n)); assertFalse(AutomorphicNumber.isAutomorphic3(String.valueOf(n))); } - assertTrue(AutomorphicNumber.isAutomorphic3("59918212890625")); // Special case for BigInteger - assertFalse(AutomorphicNumber.isAutomorphic3("12345678912345")); // Special case for BigInteger + assertTrue( + AutomorphicNumber.isAutomorphic3("59918212890625")); // Special case for BigInteger + assertFalse( + AutomorphicNumber.isAutomorphic3("12345678912345")); // Special case for BigInteger } } diff --git a/src/test/java/com/thealgorithms/maths/AverageTest.java b/src/test/java/com/thealgorithms/maths/AverageTest.java index 3069c163..2008232c 100644 --- a/src/test/java/com/thealgorithms/maths/AverageTest.java +++ b/src/test/java/com/thealgorithms/maths/AverageTest.java @@ -30,5 +30,4 @@ public class AverageTest { int[] numbers = {2, 4, 10}; Assertions.assertEquals(5, Average.average(numbers)); } - } diff --git a/src/test/java/com/thealgorithms/maths/CollatzConjectureTest.java b/src/test/java/com/thealgorithms/maths/CollatzConjectureTest.java index 504435ae..118e8db8 100644 --- a/src/test/java/com/thealgorithms/maths/CollatzConjectureTest.java +++ b/src/test/java/com/thealgorithms/maths/CollatzConjectureTest.java @@ -27,34 +27,13 @@ class CollatzConjectureTest { @Test void collatzConjecture() { - final List expected = List.of( - 35, - 106, - 53, - 160, - 80, - 40, - 20, - 10, - 5, - 16, - 8, - 4, - 2, - 1 - ); + final List expected = List.of(35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1); assertIterableEquals(expected, cConjecture.collatzConjecture(35)); } @Test void sequenceOfNotNaturalFirstNumber() { - assertThrows( - IllegalArgumentException.class, - () -> cConjecture.collatzConjecture(0) - ); - assertThrows( - IllegalArgumentException.class, - () -> cConjecture.collatzConjecture(-1) - ); + assertThrows(IllegalArgumentException.class, () -> cConjecture.collatzConjecture(0)); + assertThrows(IllegalArgumentException.class, () -> cConjecture.collatzConjecture(-1)); } } diff --git a/src/test/java/com/thealgorithms/maths/DistanceFormulaTest.java b/src/test/java/com/thealgorithms/maths/DistanceFormulaTest.java index 1dfb92d0..de9f561b 100644 --- a/src/test/java/com/thealgorithms/maths/DistanceFormulaTest.java +++ b/src/test/java/com/thealgorithms/maths/DistanceFormulaTest.java @@ -9,34 +9,24 @@ public class DistanceFormulaTest { @Test void euclideanTest1() { - Assertions.assertEquals( - DistanceFormula.euclideanDistance(1, 1, 2, 2), - 1.4142135623730951 - ); + Assertions.assertEquals(DistanceFormula.euclideanDistance(1, 1, 2, 2), 1.4142135623730951); } @Test void euclideanTest2() { - Assertions.assertEquals( - DistanceFormula.euclideanDistance(1, 3, 8, 0), - 7.0710678118654755 - ); + Assertions.assertEquals(DistanceFormula.euclideanDistance(1, 3, 8, 0), 7.0710678118654755); } @Test void euclideanTest3() { Assertions.assertEquals( - DistanceFormula.euclideanDistance(2.4, 9.1, 55.1, 100), - 110.91911467371168 - ); + DistanceFormula.euclideanDistance(2.4, 9.1, 55.1, 100), 110.91911467371168); } @Test void euclideanTest4() { Assertions.assertEquals( - DistanceFormula.euclideanDistance(1000, 13, 20000, 84), - 19022.067605809836 - ); + DistanceFormula.euclideanDistance(1000, 13, 20000, 84), 19022.067605809836); } @Test @@ -46,65 +36,53 @@ public class DistanceFormulaTest { @Test public void manhattantest2() { - assertEquals( - DistanceFormula.manhattanDistance(6.5, 8.4, 20.1, 13.6), - 18.8 - ); + assertEquals(DistanceFormula.manhattanDistance(6.5, 8.4, 20.1, 13.6), 18.8); } @Test public void manhattanTest3() { - assertEquals( - DistanceFormula.manhattanDistance(10.112, 50, 8, 25.67), - 26.442 - ); + assertEquals(DistanceFormula.manhattanDistance(10.112, 50, 8, 25.67), 26.442); } @Test public void hammingTest1() { - int[] array1 = { 1, 1, 1, 1 }; - int[] array2 = { 0, 0, 0, 0 }; + int[] array1 = {1, 1, 1, 1}; + int[] array2 = {0, 0, 0, 0}; assertEquals(DistanceFormula.hammingDistance(array1, array2), 4); } @Test public void hammingTest2() { - int[] array1 = { 1, 1, 1, 1 }; - int[] array2 = { 1, 1, 1, 1 }; + int[] array1 = {1, 1, 1, 1}; + int[] array2 = {1, 1, 1, 1}; assertEquals(DistanceFormula.hammingDistance(array1, array2), 0); } @Test public void hammingTest3() { - int[] array1 = { 1, 0, 0, 1, 1, 0, 1, 1, 0 }; - int[] array2 = { 0, 1, 0, 0, 1, 1, 1, 0, 0 }; + int[] array1 = {1, 0, 0, 1, 1, 0, 1, 1, 0}; + int[] array2 = {0, 1, 0, 0, 1, 1, 1, 0, 0}; assertEquals(DistanceFormula.hammingDistance(array1, array2), 5); } @Test public void minkowskiTest1() { - double[] array1 = { 1, 3, 8, 5 }; - double[] array2 = { 4, 2, 6, 9 }; + double[] array1 = {1, 3, 8, 5}; + double[] array2 = {4, 2, 6, 9}; assertEquals(DistanceFormula.minkowskiDistance(array1, array2, 1), 10); } @Test public void minkowskiTest2() { - double[] array1 = { 1, 3, 8, 5 }; - double[] array2 = { 4, 2, 6, 9 }; - assertEquals( - DistanceFormula.minkowskiDistance(array1, array2, 2), - 5.477225575051661 - ); + double[] array1 = {1, 3, 8, 5}; + double[] array2 = {4, 2, 6, 9}; + assertEquals(DistanceFormula.minkowskiDistance(array1, array2, 2), 5.477225575051661); } @Test public void minkowskiTest3() { - double[] array1 = { 1, 3, 8, 5 }; - double[] array2 = { 4, 2, 6, 9 }; - assertEquals( - DistanceFormula.minkowskiDistance(array1, array2, 3), - 4.641588833612778 - ); + double[] array1 = {1, 3, 8, 5}; + double[] array2 = {4, 2, 6, 9}; + assertEquals(DistanceFormula.minkowskiDistance(array1, array2, 3), 4.641588833612778); } } diff --git a/src/test/java/com/thealgorithms/maths/DudeneyNumberTest.java b/src/test/java/com/thealgorithms/maths/DudeneyNumberTest.java index 24bdc864..e15ab0a5 100644 --- a/src/test/java/com/thealgorithms/maths/DudeneyNumberTest.java +++ b/src/test/java/com/thealgorithms/maths/DudeneyNumberTest.java @@ -1,9 +1,9 @@ package com.thealgorithms.maths; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + class DudeneyNumberTest { @Test @@ -13,6 +13,5 @@ class DudeneyNumberTest { assertTrue(() -> DudeneyNumber.isDudeney(validDudeneyNumber)); assertFalse(() -> DudeneyNumber.isDudeney(invalidDudeneyNumber)); - } } \ No newline at end of file diff --git a/src/test/java/com/thealgorithms/maths/FindMaxTest.java b/src/test/java/com/thealgorithms/maths/FindMaxTest.java index a7a18fe1..17f8d454 100644 --- a/src/test/java/com/thealgorithms/maths/FindMaxTest.java +++ b/src/test/java/com/thealgorithms/maths/FindMaxTest.java @@ -9,33 +9,21 @@ public class FindMaxTest { @Test public void testFindMax0() { - assertEquals( - 10, - FindMax.findMax(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }) - ); + assertEquals(10, FindMax.findMax(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10})); } @Test public void testFindMax1() { - assertEquals( - 7, - FindMax.findMax(new int[] { 6, 3, 5, 1, 7, 4, 1 }) - ); + assertEquals(7, FindMax.findMax(new int[] {6, 3, 5, 1, 7, 4, 1})); } @Test public void testFindMax2() { - assertEquals( - 10, - FindMax.findMax(new int[] { 10, 0 }) - ); + assertEquals(10, FindMax.findMax(new int[] {10, 0})); } @Test public void testFindMaxThrowsExceptionForEmptyInput() { - assertThrows( - IllegalArgumentException.class, - () -> FindMax.findMax(new int[]{}) - ); + assertThrows(IllegalArgumentException.class, () -> FindMax.findMax(new int[] {})); } } diff --git a/src/test/java/com/thealgorithms/maths/FindMinTest.java b/src/test/java/com/thealgorithms/maths/FindMinTest.java index dc983547..7599b902 100644 --- a/src/test/java/com/thealgorithms/maths/FindMinTest.java +++ b/src/test/java/com/thealgorithms/maths/FindMinTest.java @@ -9,32 +9,26 @@ public class FindMinTest { @Test public void testFindMinValue() { - assertEquals( - 1, - FindMin.findMin(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }) - ); + assertEquals(1, FindMin.findMin(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10})); } @Test public void test1() { - assertEquals(1, FindMin.findMin(new int[] { 1, 3, 5, 7, 9 })); + assertEquals(1, FindMin.findMin(new int[] {1, 3, 5, 7, 9})); } @Test public void test2() { - assertEquals(0, FindMin.findMin(new int[] { 0, 192, 384, 576 })); + assertEquals(0, FindMin.findMin(new int[] {0, 192, 384, 576})); } @Test public void test3() { - assertEquals(0, FindMin.findMin(new int[] { 10, 10, 0, 10 })); + assertEquals(0, FindMin.findMin(new int[] {10, 10, 0, 10})); } @Test public void testFindMinThrowsExceptionForEmptyInput() { - assertThrows( - IllegalArgumentException.class, - () -> FindMin.findMin(new int[]{}) - ); + assertThrows(IllegalArgumentException.class, () -> FindMin.findMin(new int[] {})); } } diff --git a/src/test/java/com/thealgorithms/maths/FrizzyNumberTest.java b/src/test/java/com/thealgorithms/maths/FrizzyNumberTest.java index 1a8501ea..a5fd867e 100644 --- a/src/test/java/com/thealgorithms/maths/FrizzyNumberTest.java +++ b/src/test/java/com/thealgorithms/maths/FrizzyNumberTest.java @@ -6,43 +6,23 @@ import org.junit.jupiter.api.Test; public class FrizzyNumberTest { @Test public void testFrizziesForBase2() { - assertEquals( - 1, - FrizzyNumber.getNthFrizzy(2, 1)); - assertEquals( - 3, - FrizzyNumber.getNthFrizzy(2, 3)); - assertEquals( - 1000, - FrizzyNumber.getNthFrizzy(2, 1000)); + assertEquals(1, FrizzyNumber.getNthFrizzy(2, 1)); + assertEquals(3, FrizzyNumber.getNthFrizzy(2, 3)); + assertEquals(1000, FrizzyNumber.getNthFrizzy(2, 1000)); } @Test public void testFrizziesForBase3() { - assertEquals( - 1, - FrizzyNumber.getNthFrizzy(3, 1)); - assertEquals( - 3, - FrizzyNumber.getNthFrizzy(3, 2)); - assertEquals( - 29430, - FrizzyNumber.getNthFrizzy(3, 1000)); + assertEquals(1, FrizzyNumber.getNthFrizzy(3, 1)); + assertEquals(3, FrizzyNumber.getNthFrizzy(3, 2)); + assertEquals(29430, FrizzyNumber.getNthFrizzy(3, 1000)); } @Test public void testFrizziesForBase69() { - assertEquals( - 1, - FrizzyNumber.getNthFrizzy(69, 1)); - assertEquals( - 69, - FrizzyNumber.getNthFrizzy(69, 2)); - assertEquals( - 328510, - FrizzyNumber.getNthFrizzy(69, 9)); - assertEquals( - 333340, - FrizzyNumber.getNthFrizzy(69, 15)); + assertEquals(1, FrizzyNumber.getNthFrizzy(69, 1)); + assertEquals(69, FrizzyNumber.getNthFrizzy(69, 2)); + assertEquals(328510, FrizzyNumber.getNthFrizzy(69, 9)); + assertEquals(333340, FrizzyNumber.getNthFrizzy(69, 15)); } } diff --git a/src/test/java/com/thealgorithms/maths/GCDTest.java b/src/test/java/com/thealgorithms/maths/GCDTest.java index bbf10cad..49a90232 100644 --- a/src/test/java/com/thealgorithms/maths/GCDTest.java +++ b/src/test/java/com/thealgorithms/maths/GCDTest.java @@ -7,26 +7,17 @@ public class GCDTest { @Test void test1() { - Assertions.assertThrows( - ArithmeticException.class, - () -> GCD.gcd(-1, 0) - ); + Assertions.assertThrows(ArithmeticException.class, () -> GCD.gcd(-1, 0)); } @Test void test2() { - Assertions.assertThrows( - ArithmeticException.class, - () -> GCD.gcd(10, -2) - ); + Assertions.assertThrows(ArithmeticException.class, () -> GCD.gcd(10, -2)); } @Test void test3() { - Assertions.assertThrows( - ArithmeticException.class, - () -> GCD.gcd(-5, -3) - ); + Assertions.assertThrows(ArithmeticException.class, () -> GCD.gcd(-5, -3)); } @Test @@ -48,19 +39,20 @@ public class GCDTest { void test7() { Assertions.assertEquals(GCD.gcd(9, 6), 3); } - + @Test void testArrayGcd1() { - Assertions.assertEquals(GCD.gcd(new int[]{9, 6}), 3); + Assertions.assertEquals(GCD.gcd(new int[] {9, 6}), 3); } @Test void testArrayGcd2() { - Assertions.assertEquals(GCD.gcd(new int[]{2*3*5*7, 2*5*5*5, 2*5*11, 5*5*5*13}), 5); + Assertions.assertEquals( + GCD.gcd(new int[] {2 * 3 * 5 * 7, 2 * 5 * 5 * 5, 2 * 5 * 11, 5 * 5 * 5 * 13}), 5); } - + @Test void testArrayGcdForEmptyInput() { - Assertions.assertEquals(GCD.gcd(new int[]{}), 0); - } + Assertions.assertEquals(GCD.gcd(new int[] {}), 0); + } } diff --git a/src/test/java/com/thealgorithms/maths/HarshadNumberTest.java b/src/test/java/com/thealgorithms/maths/HarshadNumberTest.java index f9176961..bea4e0a6 100644 --- a/src/test/java/com/thealgorithms/maths/HarshadNumberTest.java +++ b/src/test/java/com/thealgorithms/maths/HarshadNumberTest.java @@ -1,13 +1,14 @@ package com.thealgorithms.maths; import static org.junit.jupiter.api.Assertions.*; + import org.junit.jupiter.api.Test; public class HarshadNumberTest { @Test public void harshadNumber() { - + assertTrue(HarshadNumber.isHarshad(18)); assertFalse(HarshadNumber.isHarshad(-18)); assertFalse(HarshadNumber.isHarshad(19)); diff --git a/src/test/java/com/thealgorithms/maths/HeronsFormulaTest.java b/src/test/java/com/thealgorithms/maths/HeronsFormulaTest.java index c3ccde86..32feeacd 100644 --- a/src/test/java/com/thealgorithms/maths/HeronsFormulaTest.java +++ b/src/test/java/com/thealgorithms/maths/HeronsFormulaTest.java @@ -17,17 +17,11 @@ public class HeronsFormulaTest { @Test void test3() { - Assertions.assertEquals( - HeronsFormula.Herons(1, 1, 1), - 0.4330127018922193 - ); + Assertions.assertEquals(HeronsFormula.Herons(1, 1, 1), 0.4330127018922193); } @Test void test4() { - Assertions.assertEquals( - HeronsFormula.Herons(4, 5, 8), - 8.181534085976786 - ); + Assertions.assertEquals(HeronsFormula.Herons(4, 5, 8), 8.181534085976786); } } diff --git a/src/test/java/com/thealgorithms/maths/KaprekarNumbersTest.java b/src/test/java/com/thealgorithms/maths/KaprekarNumbersTest.java index 326c1a9a..52322e55 100644 --- a/src/test/java/com/thealgorithms/maths/KaprekarNumbersTest.java +++ b/src/test/java/com/thealgorithms/maths/KaprekarNumbersTest.java @@ -3,7 +3,6 @@ package com.thealgorithms.maths; import static org.junit.jupiter.api.Assertions.*; import java.util.List; - import org.junit.jupiter.api.Test; public class KaprekarNumbersTest { @@ -51,10 +50,7 @@ public class KaprekarNumbersTest { @Test void testForRangeOfNumber() { try { - List rangedNumbers = KaprekarNumbers.kaprekarNumberInRange( - 1, - 100000 - ); + List rangedNumbers = KaprekarNumbers.kaprekarNumberInRange(1, 100000); long[] allTheNumbers = { 1, 9, diff --git a/src/test/java/com/thealgorithms/maths/LeonardoNumberTest.java b/src/test/java/com/thealgorithms/maths/LeonardoNumberTest.java index 7af452e1..705f1a10 100644 --- a/src/test/java/com/thealgorithms/maths/LeonardoNumberTest.java +++ b/src/test/java/com/thealgorithms/maths/LeonardoNumberTest.java @@ -1,13 +1,14 @@ package com.thealgorithms.maths; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import org.junit.jupiter.api.Test; + public class LeonardoNumberTest { @Test void leonardoNumberNegative() { - assertThrows(ArithmeticException.class, ()-> LeonardoNumber.leonardoNumber(-1)); + assertThrows(ArithmeticException.class, () -> LeonardoNumber.leonardoNumber(-1)); } @Test void leonardoNumberZero() { @@ -23,6 +24,6 @@ public class LeonardoNumberTest { } @Test void leonardoNumberTwenty() { - assertEquals(21891 , LeonardoNumber.leonardoNumber(20)); + assertEquals(21891, LeonardoNumber.leonardoNumber(20)); } } diff --git a/src/test/java/com/thealgorithms/maths/LiouvilleLambdaFunctionTest.java b/src/test/java/com/thealgorithms/maths/LiouvilleLambdaFunctionTest.java index d8fd39d9..526b6aa2 100644 --- a/src/test/java/com/thealgorithms/maths/LiouvilleLambdaFunctionTest.java +++ b/src/test/java/com/thealgorithms/maths/LiouvilleLambdaFunctionTest.java @@ -8,65 +8,57 @@ class LiouvilleLambdaFunctionTest { @Test void testLiouvilleLambdaMustThrowExceptionIfNumberIsZero() { - //given + // given int number = 0; String expectedMessage = "Number must be greater than zero."; - //when - Exception exception = assertThrows( - IllegalArgumentException.class, - () -> { - LiouvilleLambdaFunction.liouvilleLambda(number); - } - ); + // when + Exception exception = assertThrows(IllegalArgumentException.class, + () -> { LiouvilleLambdaFunction.liouvilleLambda(number); }); String actualMessage = exception.getMessage(); - //then + // then assertEquals(expectedMessage, actualMessage); } @Test void testLiouvilleLambdaMustThrowExceptionIfNumberIsNegative() { - //given + // given int number = -1; String expectedMessage = "Number must be greater than zero."; - //when - Exception exception = assertThrows( - IllegalArgumentException.class, - () -> { - LiouvilleLambdaFunction.liouvilleLambda(number); - } - ); + // when + Exception exception = assertThrows(IllegalArgumentException.class, + () -> { LiouvilleLambdaFunction.liouvilleLambda(number); }); String actualMessage = exception.getMessage(); - //then + // then assertEquals(expectedMessage, actualMessage); } @Test void testLiouvilleLambdaMustReturnNegativeOne() { - //given + // given int number = 11; int expectedOutput = -1; - //when + // when int actualOutput = LiouvilleLambdaFunction.liouvilleLambda(number); - //then + // then assertEquals(expectedOutput, actualOutput); } @Test void testLiouvilleLambdaMustReturnPositiveOne() { - //given + // given int number = 10; int expectedOutput = 1; - //when + // when int actualOutput = LiouvilleLambdaFunction.liouvilleLambda(number); - //then + // then assertEquals(expectedOutput, actualOutput); } } diff --git a/src/test/java/com/thealgorithms/maths/LongDivisionTest.java b/src/test/java/com/thealgorithms/maths/LongDivisionTest.java index 65ee328c..f0d702ef 100644 --- a/src/test/java/com/thealgorithms/maths/LongDivisionTest.java +++ b/src/test/java/com/thealgorithms/maths/LongDivisionTest.java @@ -1,55 +1,58 @@ package com.thealgorithms.maths; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + public class LongDivisionTest { - // Requirement: Dividend (positive) is greater than divisor (positive), returns correct integer after division + // Requirement: Dividend (positive) is greater than divisor (positive), returns correct integer + // after division @Test void testOne() { - assertEquals(3, LongDivision.divide(10,3)); + assertEquals(3, LongDivision.divide(10, 3)); } - // Requirement: Dividend (positive) is greater than divisor (negative), returns correct integer after division + // Requirement: Dividend (positive) is greater than divisor (negative), returns correct integer + // after division @Test void testTwo() { - assertEquals(-2, LongDivision.divide(7,-3)); + assertEquals(-2, LongDivision.divide(7, -3)); } - - // Requirement: Dividend (positive) is greater than divisor (negative), returns correct integer after division - // Basically the same as in the first test + + // Requirement: Dividend (positive) is greater than divisor (negative), returns correct integer + // after division Basically the same as in the first test @Test void testThree() { - assertEquals(10, LongDivision.divide(105,10)); + assertEquals(10, LongDivision.divide(105, 10)); } // Requirement: Dividend (negative), divisor (positive), returns correct integer after division // Tests the case where the dividend is less than 0. @Test void testNegativeDividend() { - assertEquals(-1, LongDivision.divide(-5,3)); + assertEquals(-1, LongDivision.divide(-5, 3)); } - + // Requirement: Dividend (positive), divisor (positive), returns correct integer after division - // Tests the case where the dividend is less than the divisor. The test should return 0 in this case. + // Tests the case where the dividend is less than the divisor. The test should return 0 in this + // case. @Test void testDividendLessThanDivisor() { - assertEquals(0, LongDivision.divide(3,5)); + assertEquals(0, LongDivision.divide(3, 5)); } // Requirement: Dividend (neither), divisor (positive), returns correct integer after division // Tests the case where the dividend is 0. This should return a 0. @Test void testDividendIsZero() { - assertEquals(0, LongDivision.divide(0,5)); + assertEquals(0, LongDivision.divide(0, 5)); } // Requirement: Dividend (positive), divisor (neither), returns correct integer after division // Tests the case where the divisor is 0. This should return a 0. @Test void testDivisionByZero() { - assertEquals(0, LongDivision.divide(5,0)); + assertEquals(0, LongDivision.divide(5, 0)); } } diff --git a/src/test/java/com/thealgorithms/maths/LucasSeriesTest.java b/src/test/java/com/thealgorithms/maths/LucasSeriesTest.java index e5ac6224..3576268c 100644 --- a/src/test/java/com/thealgorithms/maths/LucasSeriesTest.java +++ b/src/test/java/com/thealgorithms/maths/LucasSeriesTest.java @@ -1,8 +1,9 @@ package com.thealgorithms.maths; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + public class LucasSeriesTest { @Test void lucasSeriesTwo() { diff --git a/src/test/java/com/thealgorithms/maths/MedianTest.java b/src/test/java/com/thealgorithms/maths/MedianTest.java index f3825b7f..d2b637ab 100644 --- a/src/test/java/com/thealgorithms/maths/MedianTest.java +++ b/src/test/java/com/thealgorithms/maths/MedianTest.java @@ -1,8 +1,9 @@ package com.thealgorithms.maths; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + public class MedianTest { @Test void medianSingleValue() { diff --git a/src/test/java/com/thealgorithms/maths/MobiusFunctionTest.java b/src/test/java/com/thealgorithms/maths/MobiusFunctionTest.java index f5897c2b..b4f51bf5 100644 --- a/src/test/java/com/thealgorithms/maths/MobiusFunctionTest.java +++ b/src/test/java/com/thealgorithms/maths/MobiusFunctionTest.java @@ -8,39 +8,31 @@ class MobiusFunctionTest { @Test void testMobiusForZero() { - //given + // given int number = 0; String expectedMessage = "Number must be greater than zero."; - //when + // when Exception exception = assertThrows( - IllegalArgumentException.class, - () -> { - MobiusFunction.mobius(number); - } - ); + IllegalArgumentException.class, () -> { MobiusFunction.mobius(number); }); String actualMessage = exception.getMessage(); - //then + // then assertEquals(expectedMessage, actualMessage); } @Test void testMobiusForNegativeNumber() { - //given + // given int number = -1; String expectedMessage = "Number must be greater than zero."; - //when + // when Exception exception = assertThrows( - IllegalArgumentException.class, - () -> { - MobiusFunction.mobius(number); - } - ); + IllegalArgumentException.class, () -> { MobiusFunction.mobius(number); }); String actualMessage = exception.getMessage(); - //then + // then assertEquals(expectedMessage, actualMessage); } @@ -150,13 +142,13 @@ class MobiusFunctionTest { }; for (int i = 1; i <= 100; i++) { - //given + // given int expectedValue = expectedResultArray[i - 1]; - //when + // when int actualValue = MobiusFunction.mobius(i); - //then + // then assertEquals(expectedValue, actualValue); } } diff --git a/src/test/java/com/thealgorithms/maths/NthUglyNumberTest.java b/src/test/java/com/thealgorithms/maths/NthUglyNumberTest.java index 597d0892..3fe58dad 100644 --- a/src/test/java/com/thealgorithms/maths/NthUglyNumberTest.java +++ b/src/test/java/com/thealgorithms/maths/NthUglyNumberTest.java @@ -4,7 +4,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.HashMap; - import org.junit.jupiter.api.Test; public class NthUglyNumberTest { @@ -51,7 +50,7 @@ public class NthUglyNumberTest { for (final var tc : testCases.entrySet()) { assertEquals(uglyNumbers.get(tc.getKey()), tc.getValue()); } - + assertEquals(uglyNumbers.get(999), 385875); } @@ -67,21 +66,14 @@ public class NthUglyNumberTest { assertEquals(uglyNumbers.get(5), 32); } - @Test public void testGetThrowsAnErrorForNegativeInput() { var uglyNumbers = new NthUglyNumber(new int[] {1, 2}); - assertThrows( - IllegalArgumentException.class, - () -> uglyNumbers.get(-1) - ); + assertThrows(IllegalArgumentException.class, () -> uglyNumbers.get(-1)); } @Test public void testConstructorThrowsAnErrorForEmptyInput() { - assertThrows( - IllegalArgumentException.class, - () -> new NthUglyNumber(new int[] {}) - ); + assertThrows(IllegalArgumentException.class, () -> new NthUglyNumber(new int[] {})); } } diff --git a/src/test/java/com/thealgorithms/maths/PascalTriangleTest.java b/src/test/java/com/thealgorithms/maths/PascalTriangleTest.java index a01c1103..4f5ec4ce 100644 --- a/src/test/java/com/thealgorithms/maths/PascalTriangleTest.java +++ b/src/test/java/com/thealgorithms/maths/PascalTriangleTest.java @@ -9,14 +9,14 @@ class PascalTriangleTest { @Test void testForOne() { int[][] result = PascalTriangle.pascal(1); - int[][] expected = { { 1 } }; + int[][] expected = {{1}}; assertArrayEquals(result, expected); } @Test void testForTwo() { int[][] result = PascalTriangle.pascal(2); - int[][] expected = { { 1, 0 }, { 1, 1 } }; + int[][] expected = {{1, 0}, {1, 1}}; assertArrayEquals(result, expected); } @@ -24,11 +24,11 @@ class PascalTriangleTest { void testForFive() { int[][] result = PascalTriangle.pascal(5); int[][] expected = { - { 1, 0, 0, 0, 0 }, - { 1, 1, 0, 0, 0 }, - { 1, 2, 1, 0, 0 }, - { 1, 3, 3, 1, 0 }, - { 1, 4, 6, 4, 1 }, + {1, 0, 0, 0, 0}, + {1, 1, 0, 0, 0}, + {1, 2, 1, 0, 0}, + {1, 3, 3, 1, 0}, + {1, 4, 6, 4, 1}, }; assertArrayEquals(result, expected); } @@ -37,14 +37,14 @@ class PascalTriangleTest { void testForEight() { int[][] result = PascalTriangle.pascal(8); int[][] expected = { - { 1, 0, 0, 0, 0, 0, 0, 0 }, - { 1, 1, 0, 0, 0, 0, 0, 0 }, - { 1, 2, 1, 0, 0, 0, 0, 0 }, - { 1, 3, 3, 1, 0, 0, 0, 0 }, - { 1, 4, 6, 4, 1, 0, 0, 0 }, - { 1, 5, 10, 10, 5, 1, 0, 0 }, - { 1, 6, 15, 20, 15, 6, 1, 0 }, - { 1, 7, 21, 35, 35, 21, 7, 1 }, + {1, 0, 0, 0, 0, 0, 0, 0}, + {1, 1, 0, 0, 0, 0, 0, 0}, + {1, 2, 1, 0, 0, 0, 0, 0}, + {1, 3, 3, 1, 0, 0, 0, 0}, + {1, 4, 6, 4, 1, 0, 0, 0}, + {1, 5, 10, 10, 5, 1, 0, 0}, + {1, 6, 15, 20, 15, 6, 1, 0}, + {1, 7, 21, 35, 35, 21, 7, 1}, }; assertArrayEquals(expected, result); } diff --git a/src/test/java/com/thealgorithms/maths/PerfectNumberTest.java b/src/test/java/com/thealgorithms/maths/PerfectNumberTest.java index adaccff0..4dc7c8ce 100644 --- a/src/test/java/com/thealgorithms/maths/PerfectNumberTest.java +++ b/src/test/java/com/thealgorithms/maths/PerfectNumberTest.java @@ -1,14 +1,15 @@ package com.thealgorithms.maths; import static org.junit.jupiter.api.Assertions.*; + import org.junit.jupiter.api.Test; class PerfectNumberTest { @Test public void perfectNumber() { - int[] trueTestCases = { 6, 28, 496, 8128, 33550336 }; - int[] falseTestCases = { -6, 0, 1, 9, 123 }; + int[] trueTestCases = {6, 28, 496, 8128, 33550336}; + int[] falseTestCases = {-6, 0, 1, 9, 123}; for (Integer n : trueTestCases) { assertTrue(PerfectNumber.isPerfectNumber(n)); assertTrue(PerfectNumber.isPerfectNumber2(n)); diff --git a/src/test/java/com/thealgorithms/maths/PerfectSquareTest.java b/src/test/java/com/thealgorithms/maths/PerfectSquareTest.java index 481260c9..487b4778 100644 --- a/src/test/java/com/thealgorithms/maths/PerfectSquareTest.java +++ b/src/test/java/com/thealgorithms/maths/PerfectSquareTest.java @@ -8,7 +8,7 @@ public class PerfectSquareTest { @Test public void TestPerfectSquareifiscorrect() { - //Valid Partition + // Valid Partition int number = 9; boolean result = PerfectSquare.isPerfectSquare(number); @@ -18,7 +18,7 @@ public class PerfectSquareTest { @Test public void TestPerfectSquareifisnotcorrect() { - //Invalid Partition 1 + // Invalid Partition 1 int number = 3; boolean result = PerfectSquare.isPerfectSquare(number); @@ -28,7 +28,7 @@ public class PerfectSquareTest { @Test public void TestPerfectSquareifisNegativeNumber() { - //Invalid Partition 2 + // Invalid Partition 2 int number = -10; boolean result = PerfectSquare.isPerfectSquare(number); diff --git a/src/test/java/com/thealgorithms/maths/PerimeterTest.java b/src/test/java/com/thealgorithms/maths/PerimeterTest.java index 5af109d5..94d3d3ae 100644 --- a/src/test/java/com/thealgorithms/maths/PerimeterTest.java +++ b/src/test/java/com/thealgorithms/maths/PerimeterTest.java @@ -37,7 +37,7 @@ public class PerimeterTest { void testcase6() { Assertions.assertEquals(43.982297150257104, Perimeter.perimeterCircle(7)); } - + // Perimeter of Irregular polygon @Test void testcase7() { diff --git a/src/test/java/com/thealgorithms/maths/PollardRhoTest.java b/src/test/java/com/thealgorithms/maths/PollardRhoTest.java index d5d51600..83a52355 100644 --- a/src/test/java/com/thealgorithms/maths/PollardRhoTest.java +++ b/src/test/java/com/thealgorithms/maths/PollardRhoTest.java @@ -9,46 +9,42 @@ class PollardRhoTest { @Test void testPollardRhoForNumber315MustReturn5() { - //given + // given int number = 315; int expectedResult = 5; - //when + // when int actualResult = PollardRho.pollardRho(number); - //then + // then assertEquals(expectedResult, actualResult); } @Test void testPollardRhoForNumber187MustReturn11() { - //given + // given int number = 187; int expectedResult = 11; - //when + // when int actualResult = PollardRho.pollardRho(number); - //then + // then assertEquals(expectedResult, actualResult); } @Test void testPollardRhoForNumber239MustThrowException() { - //given + // given int number = 239; String expectedMessage = "GCD cannot be found."; - //when - Exception exception = assertThrows( - RuntimeException.class, - () -> { - PollardRho.pollardRho(number); - } - ); + // when + Exception exception + = assertThrows(RuntimeException.class, () -> { PollardRho.pollardRho(number); }); String actualMessage = exception.getMessage(); - //then + // then assertEquals(expectedMessage, actualMessage); } } diff --git a/src/test/java/com/thealgorithms/maths/PrimeFactorizationTest.java b/src/test/java/com/thealgorithms/maths/PrimeFactorizationTest.java index 2a1f6f6e..edc68448 100644 --- a/src/test/java/com/thealgorithms/maths/PrimeFactorizationTest.java +++ b/src/test/java/com/thealgorithms/maths/PrimeFactorizationTest.java @@ -9,23 +9,23 @@ class PrimeFactorizationTest { @Test void testpFactorsMustReturnEmptyList() { - //given + // given int n = 0; - //then + // then assertTrue(PrimeFactorization.pfactors(n).isEmpty()); } @Test void testpFactorsMustReturnNonEmptyList() { - //given + // given int n = 198; int expectedListSize = 4; - //when + // when List actualResultList = PrimeFactorization.pfactors(n); - //then + // then assertEquals(expectedListSize, actualResultList.size()); assertEquals(2, actualResultList.get(0)); assertEquals(3, actualResultList.get(1)); diff --git a/src/test/java/com/thealgorithms/maths/PronicNumberTest.java b/src/test/java/com/thealgorithms/maths/PronicNumberTest.java index 36a72c7e..e4ca04fd 100644 --- a/src/test/java/com/thealgorithms/maths/PronicNumberTest.java +++ b/src/test/java/com/thealgorithms/maths/PronicNumberTest.java @@ -8,25 +8,25 @@ public class PronicNumberTest { @Test void testForPronicNumber() { - //given + // given int number = 30; - //when + // when boolean result = PronicNumber.isPronic(number); - //then + // then assertTrue(result); } @Test void testForNonPronicNumber() { - //given + // given int number = 21; - //when + // when boolean result = PronicNumber.isPronic(number); - //then + // then assertFalse(result); } } diff --git a/src/test/java/com/thealgorithms/maths/ReverseNumberTest.java b/src/test/java/com/thealgorithms/maths/ReverseNumberTest.java index a6c25df5..e870962b 100644 --- a/src/test/java/com/thealgorithms/maths/ReverseNumberTest.java +++ b/src/test/java/com/thealgorithms/maths/ReverseNumberTest.java @@ -4,7 +4,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.HashMap; - import org.junit.jupiter.api.Test; public class ReverseNumberTest { @@ -25,9 +24,6 @@ public class ReverseNumberTest { @Test public void testReverseNumberThrowsExceptionForNegativeInput() { - assertThrows( - IllegalArgumentException.class, - () -> ReverseNumber.reverseNumber(-1) - ); + assertThrows(IllegalArgumentException.class, () -> ReverseNumber.reverseNumber(-1)); } } diff --git a/src/test/java/com/thealgorithms/maths/SquareFreeIntegerTest.java b/src/test/java/com/thealgorithms/maths/SquareFreeIntegerTest.java index 88e670bf..a59c0583 100644 --- a/src/test/java/com/thealgorithms/maths/SquareFreeIntegerTest.java +++ b/src/test/java/com/thealgorithms/maths/SquareFreeIntegerTest.java @@ -4,62 +4,153 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.List; - import org.junit.jupiter.api.Test; class SquareFreeIntegerTest { - @Test - void testIsSquareFreeInteger() { + @Test + void testIsSquareFreeInteger() { - //given - List listOfSquareFreeIntegers = List.of(1, 2, 3, 5, 6, 7, 10, 11, 13, 14, 15, 17, 19, 21, 22, 23, 26, 29, 30, 31, 33, 34, 35, 37, 38, 39, 41, 42, 43, 46, 47, 51, 53, 55, 57, 58, 59, 61, 62, 65, 66, 67, 69, 70, 71, 73, 74, 77, 78, 79, 82, 83, 85, 86, 87, 89, 91, 93, 94, 95, 97, 101, 102, 103, 105, 106, 107, 109, 110, 111, 113, 114, 115, 118, 119, 122, 123, 127, 129, 130, 131, 133, 134, 137, 138, 139, 141, 142, 143, 145, 146, 149, 151, 154, 155, 157, 158, 159, 161, 163, 165, 166, 167, 170, 173, 174, 177, 178, 179, 181, 182, 183, 185, 186, 187, 190, 191, 193, 194, 195, 197, 199, 201, 202, 203, 205, 206, 209, 210, 211, 213, 214, 215, 217, 218, 219, 221, 222, 223, 226, 227, 229, 230, 231, 233, 235, 237, 238, 239, 241, 246, 247, 249, 251, 253, 254, 255, 257, 258, 259, 262, 263, 265, 266, 267, 269, 271, 273, 274, 277, 278, 281, 282, 283, 285, 286, 287, 290, 291, 293, 295, 298, 299, 301, 302, 303, 305, 307, 309, 310, 311, 313, 314, 317, 318, 319, 321, 322, 323, 326, 327, 329, 330, 331, 334, 335, 337, 339, 341, 345, 346, 347, 349, 353, 354, 355, 357, 358, 359, 362, 365, 366, 367, 370, 371, 373, 374, 377, 379, 381, 382, 383, 385, 386, 389, 390, 391, 393, 394, 395, 397, 398, 399, 401, 402, 403, 406, 407, 409, 410, 411, 413, 415, 417, 418, 419, 421, 422, 426, 427, 429, 430, 431, 433, 434, 435, 437, 438, 439, 442, 443, 445, 446, 447, 449, 451, 453, 454, 455, 457, 458, 461, 462, 463, 465, 466, 467, 469, 470, 471, 473, 474, 478, 479, 481, 482, 483, 485, 487, 489, 491, 493, 494, 497, 498, 499, 501, 502, 503, 505, 506, 509, 510, 511, 514, 515, 517, 518, 519, 521, 523, 526, 527, 530, 533, 534, 535, 537, 538, 541, 542, 543, 545, 546, 547, 551, 553, 554, 555, 557, 559, 561, 562, 563, 565, 566, 569, 570, 571, 573, 574, 577, 579, 581, 582, 583, 586, 587, 589, 590, 591, 593, 595, 597, 598, 599, 601, 602, 606, 607, 609, 610, 611, 613, 614, 615, 617, 618, 619, 622, 623, 626, 627, 629, 631, 633, 634, 635, 638, 641, 642, 643, 645, 646, 647, 649, 651, 653, 654, 655, 658, 659, 661, 662, 663, 665, 667, 669, 670, 671, 673, 674, 677, 678, 679, 681, 682, 683, 685, 687, 689, 690, 691, 694, 695, 697, 698, 699, 701, 703, 705, 706, 707, 709, 710, 713, 714, 715, 717, 718, 719, 721, 723, 727, 730, 731, 733, 734, 737, 739, 741, 742, 743, 745, 746, 749, 751, 753, 754, 755, 757, 758, 759, 761, 762, 763, 766, 767, 769, 770, 771, 773, 777, 778, 779, 781, 782, 785, 786, 787, 789, 790, 791, 793, 794, 795, 797, 798, 799, 802, 803, 805, 806, 807, 809, 811, 813, 814, 815, 817, 818, 821, 822, 823, 826, 827, 829, 830, 831, 834, 835, 838, 839, 842, 843, 849, 851, 853, 854, 857, 858, 859, 861, 862, 863, 865, 866, 869, 870, 871, 874, 877, 878, 879, 881, 883, 885, 886, 887, 889, 890, 893, 894, 895, 897, 898, 899, 901, 902, 903, 905, 906, 907, 910, 911, 913, 914, 915, 917, 919, 921, 922, 923, 926, 929, 930, 933, 934, 935, 937, 938, 939, 941, 942, 943, 946, 947, 949, 951, 953, 955, 957, 958, 959, 962, 965, 966, 967, 969, 970, 971, 973, 974, 977, 978, 979, 982, 983, 985, 986, 987, 989, 991, 993, 994, 995, 997, 998, 1001, 1002, 1003, 1005, 1006, 1007, 1009, 1010, 1011, 1013, 1015, 1018, 1019, 1021, 1022, 1023, 1027, 1030, 1031, 1033, 1034, 1037, 1038, 1039, 1041, 1042, 1043, 1045, 1046, 1047, 1049, 1051, 1054, 1055, 1057, 1059, 1061, 1063, 1065, 1066, 1067, 1069, 1070, 1073, 1074, 1077, 1079, 1081, 1082, 1085, 1086, 1087, 1090, 1091, 1093, 1094, 1095, 1097, 1099, 1101, 1102, 1103, 1105, 1106, 1109, 1110, 1111, 1113, 1114, 1115, 1117, 1118, 1119, 1121, 1122, 1123, 1126, 1129, 1130, 1131, 1133, 1135, 1137, 1138, 1139, 1141, 1142, 1145, 1146, 1147, 1149, 1151, 1153, 1154, 1155, 1157, 1158, 1159, 1162, 1163, 1165, 1166, 1167, 1169, 1171, 1173, 1174, 1177, 1178, 1181, 1182, 1185, 1186, 1187, 1189, 1190, 1191, 1193, 1194, 1195, 1198, 1199, 1201, 1202, 1203, 1205, 1207, 1209, 1211, 1213, 1214, 1217, 1218, 1219, 1221, 1222, 1223, 1226, 1227, 1229, 1230, 1231, 1234, 1235, 1237, 1238, 1239, 1241, 1243, 1245, 1246, 1247, 1249, 1253, 1254, 1255, 1257, 1258, 1259, 1261, 1262, 1263, 1265, 1266, 1267, 1270, 1271, 1273, 1277, 1279, 1281, 1282, 1283, 1285, 1286, 1289, 1290, 1291, 1293, 1294, 1295, 1297, 1298, 1299, 1301, 1302, 1303, 1306, 1307, 1309, 1310, 1311, 1313, 1315, 1317, 1318, 1319, 1321, 1322, 1326, 1327, 1329, 1330, 1333, 1334, 1335, 1337, 1338, 1339, 1342, 1343, 1345, 1346, 1347, 1349, 1351, 1353, 1354, 1355, 1357, 1358, 1361, 1362, 1363, 1365, 1366, 1367, 1370, 1371, 1373, 1374, 1378, 1379, 1381, 1382, 1383, 1385, 1387, 1389, 1390, 1391, 1393, 1394, 1397, 1398, 1399, 1401, 1402, 1403, 1405, 1406, 1407, 1409, 1410, 1411, 1414, 1415, 1417, 1418, 1419, 1423, 1426, 1427, 1429, 1430, 1433, 1434, 1435, 1437, 1438, 1439, 1441, 1442, 1443, 1446, 1447, 1451, 1453, 1454, 1455, 1457, 1459, 1461, 1462, 1463, 1465, 1466, 1469, 1471, 1473, 1474, 1477, 1478, 1479, 1481, 1482, 1483, 1486, 1487, 1489, 1490, 1491, 1493, 1495, 1497, 1498, 1499, 1501, 1502, 1505, 1506, 1507, 1509, 1510, 1511, 1513, 1514, 1515, 1517, 1518, 1522, 1523, 1526, 1527, 1529, 1531, 1533, 1534, 1535, 1537, 1538, 1541, 1542, 1543, 1545, 1546, 1547, 1549, 1551, 1553, 1554, 1555, 1558, 1559, 1561, 1562, 1563, 1565, 1567, 1569, 1570, 1571, 1574, 1577, 1578, 1579, 1581, 1582, 1583, 1585, 1586, 1589, 1590, 1591, 1594, 1595, 1597, 1598, 1599, 1601, 1603, 1605, 1606, 1607, 1609, 1610, 1613, 1614, 1615, 1618, 1619, 1621, 1622, 1623, 1626, 1627, 1630, 1631, 1633, 1634, 1635, 1637, 1639, 1641, 1642, 1643, 1645, 1646, 1649, 1651, 1653, 1654, 1655, 1657, 1658, 1659, 1661, 1662, 1663, 1667, 1669, 1670, 1671, 1673, 1677, 1678, 1679, 1685, 1686, 1687, 1689, 1691, 1693, 1695, 1697, 1698, 1699, 1702, 1703, 1705, 1706, 1707, 1709, 1711, 1713, 1714, 1717, 1718, 1721, 1722, 1723, 1726, 1727, 1729, 1730, 1731, 1733, 1735, 1738, 1739, 1741, 1742, 1743, 1745, 1747, 1749, 1751, 1753, 1754, 1757, 1758, 1759, 1761, 1762, 1763, 1765, 1766, 1767, 1769, 1770, 1771, 1774, 1777, 1778, 1779, 1781, 1783, 1785, 1786, 1787, 1789, 1790, 1793, 1794, 1795, 1797, 1798, 1799, 1801, 1802, 1803, 1806, 1807, 1810, 1811, 1814, 1817, 1819, 1821, 1822, 1823, 1826, 1829, 1830, 1831, 1833, 1834, 1835, 1837, 1838, 1839, 1841, 1842, 1843, 1846, 1847, 1851, 1853, 1855, 1857, 1858, 1861, 1865, 1866, 1867, 1869, 1870, 1871, 1873, 1874, 1877, 1878, 1879, 1882, 1883, 1885, 1886, 1887, 1889, 1891, 1893, 1894, 1895, 1897, 1898, 1901, 1902, 1903, 1905, 1906, 1907, 1909, 1910, 1913, 1914, 1915, 1918, 1919, 1921, 1923, 1927, 1929, 1930, 1931, 1933, 1934, 1937, 1938, 1939, 1941, 1942, 1943, 1945, 1946, 1947, 1949, 1951, 1954, 1955, 1957, 1958, 1959, 1961, 1963, 1965, 1966, 1967, 1969, 1970, 1973, 1974, 1977, 1978, 1979, 1981, 1982, 1983, 1985, 1986, 1987, 1990, 1991, 1993, 1994, 1995, 1997, 1999, 2001, 2002, 2003, 2005, 2006, 2010, 2011, 2013, 2014, 2015, 2017, 2018, 2019, 2021, 2022, 2026, 2027, 2029, 2030, 2031, 2033, 2035, 2037, 2038, 2039, 2041, 2042, 2045, 2046, 2047, 2049, 2051, 2053, 2054, 2055, 2059, 2062, 2063, 2065, 2066, 2067, 2069, 2071, 2073, 2074, 2077, 2078, 2081, 2082, 2083, 2085, 2086, 2087, 2089, 2090, 2091, 2093, 2094, 2095, 2098, 2099, 2101, 2102, 2103, 2105, 2109, 2110, 2111, 2113, 2114, 2117, 2118, 2119, 2121, 2122, 2123, 2126, 2127, 2129, 2130, 2131, 2134, 2135, 2137, 2138, 2139, 2141, 2143, 2145, 2146, 2147, 2149, 2153, 2154, 2155, 2157, 2158, 2159, 2161, 2162, 2163, 2165, 2167, 2170, 2171, 2173, 2174, 2177, 2179, 2181, 2182, 2183, 2185, 2186, 2189, 2190, 2191, 2193, 2194, 2195, 2198, 2199, 2201, 2202, 2203, 2206, 2207, 2210, 2211, 2213, 2215, 2217, 2218, 2219, 2221, 2222, 2226, 2227, 2229, 2230, 2231, 2233, 2234, 2235, 2237, 2238, 2239, 2242, 2243, 2245, 2246, 2247, 2249, 2251, 2253, 2255, 2257, 2258, 2261, 2262, 2263, 2265, 2266, 2267, 2269, 2270, 2271, 2273, 2274, 2278, 2279, 2281, 2282, 2283, 2285, 2287, 2289, 2290, 2291, 2293, 2294, 2297, 2298, 2301, 2302, 2305, 2306, 2307, 2309, 2310, 2311, 2314, 2315, 2317, 2318, 2319, 2321, 2323, 2326, 2327, 2329, 2330, 2333, 2334, 2335, 2337, 2338, 2339, 2341, 2342, 2343, 2345, 2346, 2347, 2351, 2353, 2354, 2355, 2357, 2359, 2361, 2362, 2363, 2365, 2369, 2370, 2371, 2373, 2374, 2377, 2378, 2379, 2381, 2382, 2383, 2386, 2387, 2389, 2390, 2391, 2393, 2395, 2397, 2398, 2399, 2402, 2405, 2406, 2407, 2409, 2410, 2411, 2413, 2414, 2415, 2417, 2418, 2419, 2422, 2423, 2426, 2427, 2429, 2431, 2433, 2434, 2435, 2437, 2438, 2441, 2442, 2443, 2445, 2446, 2447, 2449, 2451, 2453, 2454, 2455, 2458, 2459, 2461, 2462, 2463, 2465, 2467, 2469, 2470, 2471, 2473, 2474, 2477, 2478, 2479, 2481, 2482, 2483, 2485, 2486, 2487, 2489, 2490, 2491, 2494, 2495, 2497, 2498); + // given + List listOfSquareFreeIntegers = List.of(1, 2, 3, 5, 6, 7, 10, 11, 13, 14, 15, 17, + 19, 21, 22, 23, 26, 29, 30, 31, 33, 34, 35, 37, 38, 39, 41, 42, 43, 46, 47, 51, 53, 55, + 57, 58, 59, 61, 62, 65, 66, 67, 69, 70, 71, 73, 74, 77, 78, 79, 82, 83, 85, 86, 87, 89, + 91, 93, 94, 95, 97, 101, 102, 103, 105, 106, 107, 109, 110, 111, 113, 114, 115, 118, + 119, 122, 123, 127, 129, 130, 131, 133, 134, 137, 138, 139, 141, 142, 143, 145, 146, + 149, 151, 154, 155, 157, 158, 159, 161, 163, 165, 166, 167, 170, 173, 174, 177, 178, + 179, 181, 182, 183, 185, 186, 187, 190, 191, 193, 194, 195, 197, 199, 201, 202, 203, + 205, 206, 209, 210, 211, 213, 214, 215, 217, 218, 219, 221, 222, 223, 226, 227, 229, + 230, 231, 233, 235, 237, 238, 239, 241, 246, 247, 249, 251, 253, 254, 255, 257, 258, + 259, 262, 263, 265, 266, 267, 269, 271, 273, 274, 277, 278, 281, 282, 283, 285, 286, + 287, 290, 291, 293, 295, 298, 299, 301, 302, 303, 305, 307, 309, 310, 311, 313, 314, + 317, 318, 319, 321, 322, 323, 326, 327, 329, 330, 331, 334, 335, 337, 339, 341, 345, + 346, 347, 349, 353, 354, 355, 357, 358, 359, 362, 365, 366, 367, 370, 371, 373, 374, + 377, 379, 381, 382, 383, 385, 386, 389, 390, 391, 393, 394, 395, 397, 398, 399, 401, + 402, 403, 406, 407, 409, 410, 411, 413, 415, 417, 418, 419, 421, 422, 426, 427, 429, + 430, 431, 433, 434, 435, 437, 438, 439, 442, 443, 445, 446, 447, 449, 451, 453, 454, + 455, 457, 458, 461, 462, 463, 465, 466, 467, 469, 470, 471, 473, 474, 478, 479, 481, + 482, 483, 485, 487, 489, 491, 493, 494, 497, 498, 499, 501, 502, 503, 505, 506, 509, + 510, 511, 514, 515, 517, 518, 519, 521, 523, 526, 527, 530, 533, 534, 535, 537, 538, + 541, 542, 543, 545, 546, 547, 551, 553, 554, 555, 557, 559, 561, 562, 563, 565, 566, + 569, 570, 571, 573, 574, 577, 579, 581, 582, 583, 586, 587, 589, 590, 591, 593, 595, + 597, 598, 599, 601, 602, 606, 607, 609, 610, 611, 613, 614, 615, 617, 618, 619, 622, + 623, 626, 627, 629, 631, 633, 634, 635, 638, 641, 642, 643, 645, 646, 647, 649, 651, + 653, 654, 655, 658, 659, 661, 662, 663, 665, 667, 669, 670, 671, 673, 674, 677, 678, + 679, 681, 682, 683, 685, 687, 689, 690, 691, 694, 695, 697, 698, 699, 701, 703, 705, + 706, 707, 709, 710, 713, 714, 715, 717, 718, 719, 721, 723, 727, 730, 731, 733, 734, + 737, 739, 741, 742, 743, 745, 746, 749, 751, 753, 754, 755, 757, 758, 759, 761, 762, + 763, 766, 767, 769, 770, 771, 773, 777, 778, 779, 781, 782, 785, 786, 787, 789, 790, + 791, 793, 794, 795, 797, 798, 799, 802, 803, 805, 806, 807, 809, 811, 813, 814, 815, + 817, 818, 821, 822, 823, 826, 827, 829, 830, 831, 834, 835, 838, 839, 842, 843, 849, + 851, 853, 854, 857, 858, 859, 861, 862, 863, 865, 866, 869, 870, 871, 874, 877, 878, + 879, 881, 883, 885, 886, 887, 889, 890, 893, 894, 895, 897, 898, 899, 901, 902, 903, + 905, 906, 907, 910, 911, 913, 914, 915, 917, 919, 921, 922, 923, 926, 929, 930, 933, + 934, 935, 937, 938, 939, 941, 942, 943, 946, 947, 949, 951, 953, 955, 957, 958, 959, + 962, 965, 966, 967, 969, 970, 971, 973, 974, 977, 978, 979, 982, 983, 985, 986, 987, + 989, 991, 993, 994, 995, 997, 998, 1001, 1002, 1003, 1005, 1006, 1007, 1009, 1010, 1011, + 1013, 1015, 1018, 1019, 1021, 1022, 1023, 1027, 1030, 1031, 1033, 1034, 1037, 1038, + 1039, 1041, 1042, 1043, 1045, 1046, 1047, 1049, 1051, 1054, 1055, 1057, 1059, 1061, + 1063, 1065, 1066, 1067, 1069, 1070, 1073, 1074, 1077, 1079, 1081, 1082, 1085, 1086, + 1087, 1090, 1091, 1093, 1094, 1095, 1097, 1099, 1101, 1102, 1103, 1105, 1106, 1109, + 1110, 1111, 1113, 1114, 1115, 1117, 1118, 1119, 1121, 1122, 1123, 1126, 1129, 1130, + 1131, 1133, 1135, 1137, 1138, 1139, 1141, 1142, 1145, 1146, 1147, 1149, 1151, 1153, + 1154, 1155, 1157, 1158, 1159, 1162, 1163, 1165, 1166, 1167, 1169, 1171, 1173, 1174, + 1177, 1178, 1181, 1182, 1185, 1186, 1187, 1189, 1190, 1191, 1193, 1194, 1195, 1198, + 1199, 1201, 1202, 1203, 1205, 1207, 1209, 1211, 1213, 1214, 1217, 1218, 1219, 1221, + 1222, 1223, 1226, 1227, 1229, 1230, 1231, 1234, 1235, 1237, 1238, 1239, 1241, 1243, + 1245, 1246, 1247, 1249, 1253, 1254, 1255, 1257, 1258, 1259, 1261, 1262, 1263, 1265, + 1266, 1267, 1270, 1271, 1273, 1277, 1279, 1281, 1282, 1283, 1285, 1286, 1289, 1290, + 1291, 1293, 1294, 1295, 1297, 1298, 1299, 1301, 1302, 1303, 1306, 1307, 1309, 1310, + 1311, 1313, 1315, 1317, 1318, 1319, 1321, 1322, 1326, 1327, 1329, 1330, 1333, 1334, + 1335, 1337, 1338, 1339, 1342, 1343, 1345, 1346, 1347, 1349, 1351, 1353, 1354, 1355, + 1357, 1358, 1361, 1362, 1363, 1365, 1366, 1367, 1370, 1371, 1373, 1374, 1378, 1379, + 1381, 1382, 1383, 1385, 1387, 1389, 1390, 1391, 1393, 1394, 1397, 1398, 1399, 1401, + 1402, 1403, 1405, 1406, 1407, 1409, 1410, 1411, 1414, 1415, 1417, 1418, 1419, 1423, + 1426, 1427, 1429, 1430, 1433, 1434, 1435, 1437, 1438, 1439, 1441, 1442, 1443, 1446, + 1447, 1451, 1453, 1454, 1455, 1457, 1459, 1461, 1462, 1463, 1465, 1466, 1469, 1471, + 1473, 1474, 1477, 1478, 1479, 1481, 1482, 1483, 1486, 1487, 1489, 1490, 1491, 1493, + 1495, 1497, 1498, 1499, 1501, 1502, 1505, 1506, 1507, 1509, 1510, 1511, 1513, 1514, + 1515, 1517, 1518, 1522, 1523, 1526, 1527, 1529, 1531, 1533, 1534, 1535, 1537, 1538, + 1541, 1542, 1543, 1545, 1546, 1547, 1549, 1551, 1553, 1554, 1555, 1558, 1559, 1561, + 1562, 1563, 1565, 1567, 1569, 1570, 1571, 1574, 1577, 1578, 1579, 1581, 1582, 1583, + 1585, 1586, 1589, 1590, 1591, 1594, 1595, 1597, 1598, 1599, 1601, 1603, 1605, 1606, + 1607, 1609, 1610, 1613, 1614, 1615, 1618, 1619, 1621, 1622, 1623, 1626, 1627, 1630, + 1631, 1633, 1634, 1635, 1637, 1639, 1641, 1642, 1643, 1645, 1646, 1649, 1651, 1653, + 1654, 1655, 1657, 1658, 1659, 1661, 1662, 1663, 1667, 1669, 1670, 1671, 1673, 1677, + 1678, 1679, 1685, 1686, 1687, 1689, 1691, 1693, 1695, 1697, 1698, 1699, 1702, 1703, + 1705, 1706, 1707, 1709, 1711, 1713, 1714, 1717, 1718, 1721, 1722, 1723, 1726, 1727, + 1729, 1730, 1731, 1733, 1735, 1738, 1739, 1741, 1742, 1743, 1745, 1747, 1749, 1751, + 1753, 1754, 1757, 1758, 1759, 1761, 1762, 1763, 1765, 1766, 1767, 1769, 1770, 1771, + 1774, 1777, 1778, 1779, 1781, 1783, 1785, 1786, 1787, 1789, 1790, 1793, 1794, 1795, + 1797, 1798, 1799, 1801, 1802, 1803, 1806, 1807, 1810, 1811, 1814, 1817, 1819, 1821, + 1822, 1823, 1826, 1829, 1830, 1831, 1833, 1834, 1835, 1837, 1838, 1839, 1841, 1842, + 1843, 1846, 1847, 1851, 1853, 1855, 1857, 1858, 1861, 1865, 1866, 1867, 1869, 1870, + 1871, 1873, 1874, 1877, 1878, 1879, 1882, 1883, 1885, 1886, 1887, 1889, 1891, 1893, + 1894, 1895, 1897, 1898, 1901, 1902, 1903, 1905, 1906, 1907, 1909, 1910, 1913, 1914, + 1915, 1918, 1919, 1921, 1923, 1927, 1929, 1930, 1931, 1933, 1934, 1937, 1938, 1939, + 1941, 1942, 1943, 1945, 1946, 1947, 1949, 1951, 1954, 1955, 1957, 1958, 1959, 1961, + 1963, 1965, 1966, 1967, 1969, 1970, 1973, 1974, 1977, 1978, 1979, 1981, 1982, 1983, + 1985, 1986, 1987, 1990, 1991, 1993, 1994, 1995, 1997, 1999, 2001, 2002, 2003, 2005, + 2006, 2010, 2011, 2013, 2014, 2015, 2017, 2018, 2019, 2021, 2022, 2026, 2027, 2029, + 2030, 2031, 2033, 2035, 2037, 2038, 2039, 2041, 2042, 2045, 2046, 2047, 2049, 2051, + 2053, 2054, 2055, 2059, 2062, 2063, 2065, 2066, 2067, 2069, 2071, 2073, 2074, 2077, + 2078, 2081, 2082, 2083, 2085, 2086, 2087, 2089, 2090, 2091, 2093, 2094, 2095, 2098, + 2099, 2101, 2102, 2103, 2105, 2109, 2110, 2111, 2113, 2114, 2117, 2118, 2119, 2121, + 2122, 2123, 2126, 2127, 2129, 2130, 2131, 2134, 2135, 2137, 2138, 2139, 2141, 2143, + 2145, 2146, 2147, 2149, 2153, 2154, 2155, 2157, 2158, 2159, 2161, 2162, 2163, 2165, + 2167, 2170, 2171, 2173, 2174, 2177, 2179, 2181, 2182, 2183, 2185, 2186, 2189, 2190, + 2191, 2193, 2194, 2195, 2198, 2199, 2201, 2202, 2203, 2206, 2207, 2210, 2211, 2213, + 2215, 2217, 2218, 2219, 2221, 2222, 2226, 2227, 2229, 2230, 2231, 2233, 2234, 2235, + 2237, 2238, 2239, 2242, 2243, 2245, 2246, 2247, 2249, 2251, 2253, 2255, 2257, 2258, + 2261, 2262, 2263, 2265, 2266, 2267, 2269, 2270, 2271, 2273, 2274, 2278, 2279, 2281, + 2282, 2283, 2285, 2287, 2289, 2290, 2291, 2293, 2294, 2297, 2298, 2301, 2302, 2305, + 2306, 2307, 2309, 2310, 2311, 2314, 2315, 2317, 2318, 2319, 2321, 2323, 2326, 2327, + 2329, 2330, 2333, 2334, 2335, 2337, 2338, 2339, 2341, 2342, 2343, 2345, 2346, 2347, + 2351, 2353, 2354, 2355, 2357, 2359, 2361, 2362, 2363, 2365, 2369, 2370, 2371, 2373, + 2374, 2377, 2378, 2379, 2381, 2382, 2383, 2386, 2387, 2389, 2390, 2391, 2393, 2395, + 2397, 2398, 2399, 2402, 2405, 2406, 2407, 2409, 2410, 2411, 2413, 2414, 2415, 2417, + 2418, 2419, 2422, 2423, 2426, 2427, 2429, 2431, 2433, 2434, 2435, 2437, 2438, 2441, + 2442, 2443, 2445, 2446, 2447, 2449, 2451, 2453, 2454, 2455, 2458, 2459, 2461, 2462, + 2463, 2465, 2467, 2469, 2470, 2471, 2473, 2474, 2477, 2478, 2479, 2481, 2482, 2483, + 2485, 2486, 2487, 2489, 2490, 2491, 2494, 2495, 2497, 2498); - for(int i = 1; i <=2500; i++) { - //when - boolean isNumberSquareFree = SquareFreeInteger.isSquareFreeInteger(i); - boolean isNumberPresentInList = listOfSquareFreeIntegers.contains(i); + for (int i = 1; i <= 2500; i++) { + // when + boolean isNumberSquareFree = SquareFreeInteger.isSquareFreeInteger(i); + boolean isNumberPresentInList = listOfSquareFreeIntegers.contains(i); - //then - assertEquals(isNumberSquareFree,isNumberPresentInList); - } - } + // then + assertEquals(isNumberSquareFree, isNumberPresentInList); + } + } - @Test - void testIsSquareFreeIntegerThrowExceptionIfNumberIsZero() { - //given - int number = 0; - String expectedMessage = "Number must be greater than zero."; + @Test + void testIsSquareFreeIntegerThrowExceptionIfNumberIsZero() { + // given + int number = 0; + String expectedMessage = "Number must be greater than zero."; - //when - Exception exception = assertThrows( - IllegalArgumentException.class, - () -> { - SquareFreeInteger.isSquareFreeInteger(number); - } - ); - String actualMessage = exception.getMessage(); + // when + Exception exception = assertThrows(IllegalArgumentException.class, + () -> { SquareFreeInteger.isSquareFreeInteger(number); }); + String actualMessage = exception.getMessage(); - //then - assertEquals(expectedMessage, actualMessage); - } + // then + assertEquals(expectedMessage, actualMessage); + } - @Test - void testIsSquareFreeIntegerMustThrowExceptionIfNumberIsNegative() { - //given - int number = -1; - String expectedMessage = "Number must be greater than zero."; + @Test + void testIsSquareFreeIntegerMustThrowExceptionIfNumberIsNegative() { + // given + int number = -1; + String expectedMessage = "Number must be greater than zero."; - //when - Exception exception = assertThrows( - IllegalArgumentException.class, - () -> { - SquareFreeInteger.isSquareFreeInteger(number); - } - ); - String actualMessage = exception.getMessage(); + // when + Exception exception = assertThrows(IllegalArgumentException.class, + () -> { SquareFreeInteger.isSquareFreeInteger(number); }); + String actualMessage = exception.getMessage(); - //then - assertEquals(expectedMessage, actualMessage); - } + // then + assertEquals(expectedMessage, actualMessage); + } } diff --git a/src/test/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonTestMethod.java b/src/test/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonTestMethod.java index 36fbba37..067b6896 100644 --- a/src/test/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonTestMethod.java +++ b/src/test/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonTestMethod.java @@ -7,25 +7,16 @@ public class SquareRootWithNewtonRaphsonTestMethod { @Test void testfor1() { - Assertions.assertEquals( - 1, - SquareRootWithNewtonRaphsonMethod.squareRoot(1) - ); + Assertions.assertEquals(1, SquareRootWithNewtonRaphsonMethod.squareRoot(1)); } @Test void testfor2() { - Assertions.assertEquals( - 1.414213562373095, - SquareRootWithNewtonRaphsonMethod.squareRoot(2) - ); + Assertions.assertEquals(1.414213562373095, SquareRootWithNewtonRaphsonMethod.squareRoot(2)); } @Test void testfor625() { - Assertions.assertEquals( - 25.0, - SquareRootWithNewtonRaphsonMethod.squareRoot(625) - ); + Assertions.assertEquals(25.0, SquareRootWithNewtonRaphsonMethod.squareRoot(625)); } } diff --git a/src/test/java/com/thealgorithms/maths/SquareRootwithBabylonianMethodTest.java b/src/test/java/com/thealgorithms/maths/SquareRootwithBabylonianMethodTest.java index 7e8d916c..3d13e436 100644 --- a/src/test/java/com/thealgorithms/maths/SquareRootwithBabylonianMethodTest.java +++ b/src/test/java/com/thealgorithms/maths/SquareRootwithBabylonianMethodTest.java @@ -7,33 +7,21 @@ public class SquareRootwithBabylonianMethodTest { @Test void testfor4() { - Assertions.assertEquals( - 2, - SquareRootWithBabylonianMethod.square_Root(4) - ); + Assertions.assertEquals(2, SquareRootWithBabylonianMethod.square_Root(4)); } @Test void testfor1() { - Assertions.assertEquals( - 1, - SquareRootWithBabylonianMethod.square_Root(1) - ); + Assertions.assertEquals(1, SquareRootWithBabylonianMethod.square_Root(1)); } @Test void testfor2() { - Assertions.assertEquals( - 1.4142135381698608, - SquareRootWithBabylonianMethod.square_Root(2) - ); + Assertions.assertEquals(1.4142135381698608, SquareRootWithBabylonianMethod.square_Root(2)); } @Test void testfor625() { - Assertions.assertEquals( - 25, - SquareRootWithBabylonianMethod.square_Root(625) - ); + Assertions.assertEquals(25, SquareRootWithBabylonianMethod.square_Root(625)); } } diff --git a/src/test/java/com/thealgorithms/maths/StandardDeviationTest.java b/src/test/java/com/thealgorithms/maths/StandardDeviationTest.java index 192b686c..2c10d2d1 100644 --- a/src/test/java/com/thealgorithms/maths/StandardDeviationTest.java +++ b/src/test/java/com/thealgorithms/maths/StandardDeviationTest.java @@ -7,26 +7,20 @@ public class StandardDeviationTest { @Test void test1() { - double[] t1 = new double[] { 1, 1, 1, 1, 1 }; + double[] t1 = new double[] {1, 1, 1, 1, 1}; Assertions.assertEquals(StandardDeviation.stdDev(t1), 0.0); } @Test void test2() { - double[] t2 = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; - Assertions.assertEquals( - StandardDeviation.stdDev(t2), - 2.8722813232690143 - ); + double[] t2 = new double[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + Assertions.assertEquals(StandardDeviation.stdDev(t2), 2.8722813232690143); } @Test void test3() { - double[] t3 = new double[] { 1.1, 8.5, 20.3, 2.4, 6.2 }; - Assertions.assertEquals( - StandardDeviation.stdDev(t3), - 6.8308125431752265 - ); + double[] t3 = new double[] {1.1, 8.5, 20.3, 2.4, 6.2}; + Assertions.assertEquals(StandardDeviation.stdDev(t3), 6.8308125431752265); } @Test @@ -38,9 +32,6 @@ public class StandardDeviationTest { 100.00045, 56.7, }; - Assertions.assertEquals( - StandardDeviation.stdDev(t4), - 38.506117353865775 - ); + Assertions.assertEquals(StandardDeviation.stdDev(t4), 38.506117353865775); } } diff --git a/src/test/java/com/thealgorithms/maths/StandardScoreTest.java b/src/test/java/com/thealgorithms/maths/StandardScoreTest.java index b2a0dc60..436b1fd0 100644 --- a/src/test/java/com/thealgorithms/maths/StandardScoreTest.java +++ b/src/test/java/com/thealgorithms/maths/StandardScoreTest.java @@ -22,9 +22,6 @@ public class StandardScoreTest { @Test void test4() { - Assertions.assertEquals( - StandardScore.zScore(8.9, 3, 4.2), - 1.4047619047619049 - ); + Assertions.assertEquals(StandardScore.zScore(8.9, 3, 4.2), 1.4047619047619049); } } diff --git a/src/test/java/com/thealgorithms/maths/SumWithoutArithmeticOperatorsTest.java b/src/test/java/com/thealgorithms/maths/SumWithoutArithmeticOperatorsTest.java index ad2158ac..63f53bc6 100644 --- a/src/test/java/com/thealgorithms/maths/SumWithoutArithmeticOperatorsTest.java +++ b/src/test/java/com/thealgorithms/maths/SumWithoutArithmeticOperatorsTest.java @@ -1,39 +1,40 @@ package com.thealgorithms.maths; import static org.junit.jupiter.api.Assertions.*; + import org.junit.jupiter.api.Test; public class SumWithoutArithmeticOperatorsTest { SumWithoutArithmeticOperators obj = new SumWithoutArithmeticOperators(); @Test - void addZerotoZero(){ - assertEquals(0,obj.getSum(0, 0)); + void addZerotoZero() { + assertEquals(0, obj.getSum(0, 0)); } @Test - void addZerotoNumber(){ - assertEquals(5,obj.getSum(0, 5)); - assertEquals(28,obj.getSum(28, 0)); + void addZerotoNumber() { + assertEquals(5, obj.getSum(0, 5)); + assertEquals(28, obj.getSum(28, 0)); } @Test - void addOddtoEven(){ - assertEquals(13,obj.getSum(3, 10)); - assertEquals(55,obj.getSum(49, 6)); + void addOddtoEven() { + assertEquals(13, obj.getSum(3, 10)); + assertEquals(55, obj.getSum(49, 6)); } @Test - void addEventoOdd(){ - assertEquals(13,obj.getSum(10, 3)); - assertEquals(41,obj.getSum(40, 1)); + void addEventoOdd() { + assertEquals(13, obj.getSum(10, 3)); + assertEquals(41, obj.getSum(40, 1)); } @Test - void addRandoms(){ - assertEquals(88,obj.getSum(44, 44)); - assertEquals(370,obj.getSum(100, 270)); - assertEquals(3,obj.getSum(1, 2)); - assertEquals(5,obj.getSum(2, 3)); + void addRandoms() { + assertEquals(88, obj.getSum(44, 44)); + assertEquals(370, obj.getSum(100, 270)); + assertEquals(3, obj.getSum(1, 2)); + assertEquals(5, obj.getSum(2, 3)); } } diff --git a/src/test/java/com/thealgorithms/maths/TwinPrimeTest.java b/src/test/java/com/thealgorithms/maths/TwinPrimeTest.java index d1f00954..e214b0ad 100644 --- a/src/test/java/com/thealgorithms/maths/TwinPrimeTest.java +++ b/src/test/java/com/thealgorithms/maths/TwinPrimeTest.java @@ -6,55 +6,55 @@ import org.junit.jupiter.api.Test; class TwinPrimeTest { - @Test - void shouldReturn7() { - //given - int number = 5; - int expectedResult = 7; - - //when - int actualResult = TwinPrime.getTwinPrime(number); - - //then - assertEquals(expectedResult,actualResult); - } - - @Test - void shouldReturn5() { - //given - int number = 3; - int expectedResult = 5; - - //when - int actualResult = TwinPrime.getTwinPrime(number); - - //then - assertEquals(expectedResult,actualResult); - } - - @Test - void shouldReturnNegative1() { - //given - int number = 4; - int expectedResult = -1; - - //when - int actualResult = TwinPrime.getTwinPrime(number); - - //then - assertEquals(expectedResult,actualResult); - } - - @Test - void shouldReturn19() { - //given - int number = 17; - int expectedResult = 19; - - //when - int actualResult = TwinPrime.getTwinPrime(number); - - //then - assertEquals(expectedResult,actualResult); - } + @Test + void shouldReturn7() { + // given + int number = 5; + int expectedResult = 7; + + // when + int actualResult = TwinPrime.getTwinPrime(number); + + // then + assertEquals(expectedResult, actualResult); + } + + @Test + void shouldReturn5() { + // given + int number = 3; + int expectedResult = 5; + + // when + int actualResult = TwinPrime.getTwinPrime(number); + + // then + assertEquals(expectedResult, actualResult); + } + + @Test + void shouldReturnNegative1() { + // given + int number = 4; + int expectedResult = -1; + + // when + int actualResult = TwinPrime.getTwinPrime(number); + + // then + assertEquals(expectedResult, actualResult); + } + + @Test + void shouldReturn19() { + // given + int number = 17; + int expectedResult = 19; + + // when + int actualResult = TwinPrime.getTwinPrime(number); + + // then + assertEquals(expectedResult, actualResult); + } } diff --git a/src/test/java/com/thealgorithms/maths/VolumeTest.java b/src/test/java/com/thealgorithms/maths/VolumeTest.java index e9a80b4b..9692246b 100644 --- a/src/test/java/com/thealgorithms/maths/VolumeTest.java +++ b/src/test/java/com/thealgorithms/maths/VolumeTest.java @@ -1,6 +1,7 @@ package com.thealgorithms.maths; import static org.junit.jupiter.api.Assertions.*; + import org.junit.jupiter.api.Test; public class VolumeTest { diff --git a/src/test/java/com/thealgorithms/others/ArrayLeftRotationTest.java b/src/test/java/com/thealgorithms/others/ArrayLeftRotationTest.java index ef350ffb..431d8daa 100644 --- a/src/test/java/com/thealgorithms/others/ArrayLeftRotationTest.java +++ b/src/test/java/com/thealgorithms/others/ArrayLeftRotationTest.java @@ -8,39 +8,39 @@ class ArrayLeftRotationTest { @Test void testForOneElement() { - int[] arr = { 3 }; + int[] arr = {3}; int[] result = ArrayLeftRotation.rotateLeft(arr, 3); assertArrayEquals(arr, result); } @Test void testForZeroStep() { - int[] arr = { 3, 1, 5, 8, 6 }; + int[] arr = {3, 1, 5, 8, 6}; int[] result = ArrayLeftRotation.rotateLeft(arr, 0); assertArrayEquals(arr, result); } @Test void testForEqualSizeStep() { - int[] arr = { 3, 1, 5, 8, 6 }; + int[] arr = {3, 1, 5, 8, 6}; int[] result = ArrayLeftRotation.rotateLeft(arr, 5); assertArrayEquals(arr, result); } @Test void testForLowerSizeStep() { - int[] arr = { 3, 1, 5, 8, 6 }; + int[] arr = {3, 1, 5, 8, 6}; int n = 2; - int[] expected = { 5, 8, 6, 3, 1 }; + int[] expected = {5, 8, 6, 3, 1}; int[] result = ArrayLeftRotation.rotateLeft(arr, n); assertArrayEquals(expected, result); } @Test void testForHigherSizeStep() { - int[] arr = { 3, 1, 5, 8, 6 }; + int[] arr = {3, 1, 5, 8, 6}; int n = 7; - int[] expected = { 5, 8, 6, 3, 1 }; + int[] expected = {5, 8, 6, 3, 1}; int[] result = ArrayLeftRotation.rotateLeft(arr, n); assertArrayEquals(expected, result); } diff --git a/src/test/java/com/thealgorithms/others/BestFitCPUTest.java b/src/test/java/com/thealgorithms/others/BestFitCPUTest.java index 35f1ef7e..0a82ebdf 100644 --- a/src/test/java/com/thealgorithms/others/BestFitCPUTest.java +++ b/src/test/java/com/thealgorithms/others/BestFitCPUTest.java @@ -19,9 +19,9 @@ class BestFitCPUTest { @Test void testFitForUseOfOneBlock() { - //test1 - 2 processes shall fit to one block instead of using a different block each - sizeOfBlocks = new int[] { 5, 12, 17, 10 }; - sizeOfProcesses = new int[] { 10, 5, 15, 2 }; + // test1 - 2 processes shall fit to one block instead of using a different block each + sizeOfBlocks = new int[] {5, 12, 17, 10}; + sizeOfProcesses = new int[] {10, 5, 15, 2}; memAllocation = bestFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(3, 0, 2, 2)); assertEquals(testMemAllocation, memAllocation); @@ -29,9 +29,9 @@ class BestFitCPUTest { @Test void testFitForEqualProcecesses() { - //test2 - sizeOfBlocks = new int[] { 5, 12, 17, 10 }; - sizeOfProcesses = new int[] { 10, 10, 10, 10 }; + // test2 + sizeOfBlocks = new int[] {5, 12, 17, 10}; + sizeOfProcesses = new int[] {10, 10, 10, 10}; memAllocation = bestFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(3, 1, 2, -255)); assertEquals(testMemAllocation, memAllocation); @@ -39,9 +39,9 @@ class BestFitCPUTest { @Test void testFitForNoEmptyBlockCell() { - //test3 for more processes than blocks - no empty space left to none of the blocks - sizeOfBlocks = new int[] { 5, 12, 17 }; - sizeOfProcesses = new int[] { 5, 12, 10, 7 }; + // test3 for more processes than blocks - no empty space left to none of the blocks + sizeOfBlocks = new int[] {5, 12, 17}; + sizeOfProcesses = new int[] {5, 12, 10, 7}; memAllocation = bestFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(0, 1, 2, 2)); assertEquals(testMemAllocation, memAllocation); @@ -49,9 +49,9 @@ class BestFitCPUTest { @Test void testFitForSameInputDifferentQuery() { - //test4 for more processes than blocks - one element does not fit due to input series - sizeOfBlocks = new int[] { 5, 12, 17 }; - sizeOfProcesses = new int[] { 5, 7, 10, 12 }; + // test4 for more processes than blocks - one element does not fit due to input series + sizeOfBlocks = new int[] {5, 12, 17}; + sizeOfProcesses = new int[] {5, 7, 10, 12}; memAllocation = bestFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(0, 1, 2, -255)); assertEquals(testMemAllocation, memAllocation); @@ -59,9 +59,9 @@ class BestFitCPUTest { @Test void testFitForMoreBlocksNoFit() { - //test5 for more blocks than processes - sizeOfBlocks = new int[] { 5, 4, -1, 3, 6 }; - sizeOfProcesses = new int[] { 10, 11 }; + // test5 for more blocks than processes + sizeOfBlocks = new int[] {5, 4, -1, 3, 6}; + sizeOfProcesses = new int[] {10, 11}; memAllocation = bestFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(-255, -255)); assertEquals(testMemAllocation, memAllocation); diff --git a/src/test/java/com/thealgorithms/others/CRC16Test.java b/src/test/java/com/thealgorithms/others/CRC16Test.java index 057d5b7d..513ec989 100644 --- a/src/test/java/com/thealgorithms/others/CRC16Test.java +++ b/src/test/java/com/thealgorithms/others/CRC16Test.java @@ -1,9 +1,9 @@ package com.thealgorithms.others; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + class CRC16Test { CRC16 crc = new CRC16(); @@ -19,5 +19,4 @@ class CRC16Test { // then assertEquals("10FC", resultCRC16); } - } diff --git a/src/test/java/com/thealgorithms/others/CRCAlgorithmTest.java b/src/test/java/com/thealgorithms/others/CRCAlgorithmTest.java index 906ab829..a581a35b 100644 --- a/src/test/java/com/thealgorithms/others/CRCAlgorithmTest.java +++ b/src/test/java/com/thealgorithms/others/CRCAlgorithmTest.java @@ -1,27 +1,27 @@ package com.thealgorithms.others; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + public class CRCAlgorithmTest { @Test - void test1(){ + void test1() { CRCAlgorithm c = new CRCAlgorithm("10010101010100101010010000001010010101010", 10, 0.0); - //A bit-error rate of 0.0 should not provide any wrong messages + // A bit-error rate of 0.0 should not provide any wrong messages c.changeMess(); c.divideMessageWithP(false); assertEquals(c.getWrongMess(), 0); } @Test - void test2(){ + void test2() { CRCAlgorithm c = new CRCAlgorithm("10010101010100101010010000001010010101010", 10, 1.0); - //A bit error rate of 1.0 should not provide any correct messages + // A bit error rate of 1.0 should not provide any correct messages c.changeMess(); c.divideMessageWithP(false); assertEquals(c.getCorrectMess(), 0); diff --git a/src/test/java/com/thealgorithms/others/CalculateMaxOfMinTest.java b/src/test/java/com/thealgorithms/others/CalculateMaxOfMinTest.java index 89fc9b32..e80cf912 100644 --- a/src/test/java/com/thealgorithms/others/CalculateMaxOfMinTest.java +++ b/src/test/java/com/thealgorithms/others/CalculateMaxOfMinTest.java @@ -9,49 +9,49 @@ public class CalculateMaxOfMinTest { @Test void testForOneElement() { - int[] a = { 10, 20, 30, 50, 10, 70, 30 }; + int[] a = {10, 20, 30, 50, 10, 70, 30}; int k = CalculateMaxOfMin.calculateMaxOfMin(a); assertTrue(k == 70); } @Test void testForTwoElements() { - int[] a = { 5, 3, 2, 6, 3, 2, 6 }; + int[] a = {5, 3, 2, 6, 3, 2, 6}; int k = CalculateMaxOfMin.calculateMaxOfMin(a); assertTrue(k == 6); } @Test void testForThreeElements() { - int[] a = { 10, 10, 10, 10, 10, 10, 10 }; + int[] a = {10, 10, 10, 10, 10, 10, 10}; int k = CalculateMaxOfMin.calculateMaxOfMin(a); assertTrue(k == 10); } @Test void testForFourElements() { - int[] a = { 70, 60, 50, 40, 30, 20 }; + int[] a = {70, 60, 50, 40, 30, 20}; int k = CalculateMaxOfMin.calculateMaxOfMin(a); assertTrue(k == 70); } @Test void testForFiveElements() { - int[] a = { 50 }; + int[] a = {50}; int k = CalculateMaxOfMin.calculateMaxOfMin(a); assertTrue(k == 50); } @Test void testForSixElements() { - int[] a = { 1, 4, 7, 9, 2, 4, 6 }; + int[] a = {1, 4, 7, 9, 2, 4, 6}; int k = CalculateMaxOfMin.calculateMaxOfMin(a); assertTrue(k == 9); } @Test void testForSevenElements() { - int[] a = { -1, -5, -7, -9, -12, -14 }; + int[] a = {-1, -5, -7, -9, -12, -14}; int k = CalculateMaxOfMin.calculateMaxOfMin(a); assertTrue(k == -1); } diff --git a/src/test/java/com/thealgorithms/others/ConwayTest.java b/src/test/java/com/thealgorithms/others/ConwayTest.java index 04b35794..5e61836f 100644 --- a/src/test/java/com/thealgorithms/others/ConwayTest.java +++ b/src/test/java/com/thealgorithms/others/ConwayTest.java @@ -1,37 +1,42 @@ package com.thealgorithms.others; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + public class ConwayTest { @Test - public void testGenerateWith1(){ + public void testGenerateWith1() { assertEquals("31131211131221", Conway.generateList("1", 8).get(7)); } @Test - public void testGenerateWith123456(){ - assertEquals("13211321322113311213212312311211131122211213211331121321122112133221123113112221131112212211131221121321131211132221123113112221131112311332211211131221131211132211121312211231131112311211232221143113112221131112311332111213122112311311123112112322211531131122211311123113321112131221123113111231121123222116", Conway.generateList("123456", 20).get(11)); + public void testGenerateWith123456() { + assertEquals( + "13211321322113311213212312311211131122211213211331121321122112133221123113112221131112212211131221121321131211132221123113112221131112311332211211131221131211132211121312211231131112311211232221143113112221131112311332111213122112311311123112112322211531131122211311123113321112131221123113111231121123222116", + Conway.generateList("123456", 20).get(11)); } @Test - public void testGenerateWith1A1Z3E1R1T3G1F1D2E1S1C(){ - assertEquals("311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211A311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211Z111312211312111322212321121113121112131112132112311321322112111312212321121113122112131112131221121321132132211231131122111213122112311311222113111221131221221321132132211331121321231231121113112221121321133112132112211213322112311311222113111231133211121312211231131122211322311311222112111312211311123113322112132113212231121113112221121321132122211322212221121123222112111312211312111322212321121113121112131112132112311321322112111312212321121113122112131112131221121321132132211231131122211331121321232221121113122113121122132112311321322112111312211312113221133211322112211213322112132113213221133112132123123112111311222112132113311213211231232112311311222112111312211311123113322112132113213221133112132123222113221321132132211331121321232221123113112221131112311322311211131122211213211331121321122112133221121113122113121113222123112221221321132132211231131122211331121321232221121113122113121113222123113221231231121113213221231221132221222112112322211E311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211R311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211T111312211312111322212321121113121112131112132112311321322112111312212321121113122112131112131221121321132132211231131122111213122112311311222113111221131221221321132132211331121321231231121113112221121321133112132112211213322112311311222113111231133211121312211231131122211322311311222112111312211311123113322112132113212231121113112221121321132122211322212221121123222112111312211312111322212321121113121112131112132112311321322112111312212321121113122112131112131221121321132132211231131122211331121321232221121113122113121122132112311321322112111312211312113221133211322112211213322112132113213221133112132123123112111311222112132113311213211231232112311311222112111312211311123113322112132113213221133112132123222113221321132132211331121321232221123113112221131112311322311211131122211213211331121321122112133221121113122113121113222123112221221321132132211231131122211331121321232221121113122113121113222123113221231231121113213221231221132221222112112322211G311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211F311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211D111312211312111322212321121113121112131112132112311321322112111312212321121113122112131112131221121321132132211231131122211331121321232221121113122113121122132112311321322112111312211312111322211213111213122112132113121113222112132113213221133112132123222112311311222113111231132231121113112221121321133112132112211213322112111312211312111322212311222122132113213221123113112221133112132123222112111312211312111322212311322123123112111321322123122113222122211211232221121113122113121113222123211211131211121311121321123113213221121113122123211211131221121311121312211213211321322112311311222113311213212322211211131221131211221321123113213221121113122113121113222112131112131221121321131211132221121321132132211331121321232221123113112221131112311322311211131122211213211331121321122112133221121113122113121113222123112221221321132132211231131122211331121321232221121113122113121113222123113221231231121113213221231221132221222112112322211E311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211S311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211C", Conway.generateList("1A1Z3E1R1T3G1F1D2E1S1C", 20).get(19)); + public void testGenerateWith1A1Z3E1R1T3G1F1D2E1S1C() { + assertEquals( + "311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211A311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211Z111312211312111322212321121113121112131112132112311321322112111312212321121113122112131112131221121321132132211231131122111213122112311311222113111221131221221321132132211331121321231231121113112221121321133112132112211213322112311311222113111231133211121312211231131122211322311311222112111312211311123113322112132113212231121113112221121321132122211322212221121123222112111312211312111322212321121113121112131112132112311321322112111312212321121113122112131112131221121321132132211231131122211331121321232221121113122113121122132112311321322112111312211312113221133211322112211213322112132113213221133112132123123112111311222112132113311213211231232112311311222112111312211311123113322112132113213221133112132123222113221321132132211331121321232221123113112221131112311322311211131122211213211331121321122112133221121113122113121113222123112221221321132132211231131122211331121321232221121113122113121113222123113221231231121113213221231221132221222112112322211E311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211R311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211T111312211312111322212321121113121112131112132112311321322112111312212321121113122112131112131221121321132132211231131122111213122112311311222113111221131221221321132132211331121321231231121113112221121321133112132112211213322112311311222113111231133211121312211231131122211322311311222112111312211311123113322112132113212231121113112221121321132122211322212221121123222112111312211312111322212321121113121112131112132112311321322112111312212321121113122112131112131221121321132132211231131122211331121321232221121113122113121122132112311321322112111312211312113221133211322112211213322112132113213221133112132123123112111311222112132113311213211231232112311311222112111312211311123113322112132113213221133112132123222113221321132132211331121321232221123113112221131112311322311211131122211213211331121321122112133221121113122113121113222123112221221321132132211231131122211331121321232221121113122113121113222123113221231231121113213221231221132221222112112322211G311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211F311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211D111312211312111322212321121113121112131112132112311321322112111312212321121113122112131112131221121321132132211231131122211331121321232221121113122113121122132112311321322112111312211312111322211213111213122112132113121113222112132113213221133112132123222112311311222113111231132231121113112221121321133112132112211213322112111312211312111322212311222122132113213221123113112221133112132123222112111312211312111322212311322123123112111321322123122113222122211211232221121113122113121113222123211211131211121311121321123113213221121113122123211211131221121311121312211213211321322112311311222113311213212322211211131221131211221321123113213221121113122113121113222112131112131221121321131211132221121321132132211331121321232221123113112221131112311322311211131122211213211331121321122112133221121113122113121113222123112221221321132132211231131122211331121321232221121113122113121113222123113221231231121113213221231221132221222112112322211E311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211S311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211C", + Conway.generateList("1A1Z3E1R1T3G1F1D2E1S1C", 20).get(19)); } @Test - public void testGenerateNextElementWith1(){ + public void testGenerateNextElementWith1() { assertEquals("11", Conway.generateNextElement("1")); } @Test - public void testGenerateNextElementWith123456(){ + public void testGenerateNextElementWith123456() { assertEquals("111213141516", Conway.generateNextElement("123456")); } @Test - public void testGenerateNextElementWith1A1Z3E1R1T3G1F1D2E1S1C(){ - assertEquals("111A111Z131E111R111T131G111F111D121E111S111C", Conway.generateNextElement("1A1Z3E1R1T3G1F1D2E1S1C")); + public void testGenerateNextElementWith1A1Z3E1R1T3G1F1D2E1S1C() { + assertEquals("111A111Z131E111R111T131G111F111D121E111S111C", + Conway.generateNextElement("1A1Z3E1R1T3G1F1D2E1S1C")); } } diff --git a/src/test/java/com/thealgorithms/others/CountCharTest.java b/src/test/java/com/thealgorithms/others/CountCharTest.java index 9e9972c6..aae875b7 100644 --- a/src/test/java/com/thealgorithms/others/CountCharTest.java +++ b/src/test/java/com/thealgorithms/others/CountCharTest.java @@ -1,17 +1,16 @@ package com.thealgorithms.others; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + class CountCharTest { @Test - void testCountCharacters(){ + void testCountCharacters() { String input = "12345"; int expectedValue = 5; assertEquals(expectedValue, CountChar.CountCharacters(input)); } - } \ No newline at end of file diff --git a/src/test/java/com/thealgorithms/others/CountFriendsPairingTest.java b/src/test/java/com/thealgorithms/others/CountFriendsPairingTest.java index e30ffd42..070812f1 100644 --- a/src/test/java/com/thealgorithms/others/CountFriendsPairingTest.java +++ b/src/test/java/com/thealgorithms/others/CountFriendsPairingTest.java @@ -9,49 +9,49 @@ public class CountFriendsPairingTest { @Test void testForOneElement() { - int[] a = { 1, 2, 2 }; + int[] a = {1, 2, 2}; assertTrue(CountFriendsPairing.countFriendsPairing(3, a)); } @Test void testForTwoElements() { - int[] a = { 1, 2, 2, 3 }; + int[] a = {1, 2, 2, 3}; assertTrue(CountFriendsPairing.countFriendsPairing(4, a)); } @Test void testForThreeElements() { - int[] a = { 1, 2, 2, 3, 3 }; + int[] a = {1, 2, 2, 3, 3}; assertTrue(CountFriendsPairing.countFriendsPairing(5, a)); } @Test void testForFourElements() { - int[] a = { 1, 2, 2, 3, 3, 4 }; + int[] a = {1, 2, 2, 3, 3, 4}; assertTrue(CountFriendsPairing.countFriendsPairing(6, a)); } @Test void testForFiveElements() { - int[] a = { 1, 2, 2, 3, 3, 4, 4 }; + int[] a = {1, 2, 2, 3, 3, 4, 4}; assertTrue(CountFriendsPairing.countFriendsPairing(7, a)); } @Test void testForSixElements() { - int[] a = { 1, 2, 2, 3, 3, 4, 4, 4 }; + int[] a = {1, 2, 2, 3, 3, 4, 4, 4}; assertTrue(CountFriendsPairing.countFriendsPairing(8, a)); } @Test void testForSevenElements() { - int[] a = { 1, 2, 2, 3, 3, 4, 4, 4, 5 }; + int[] a = {1, 2, 2, 3, 3, 4, 4, 4, 5}; assertTrue(CountFriendsPairing.countFriendsPairing(9, a)); } @Test void testForEightElements() { - int[] a = { 1, 2, 2, 3, 3, 4, 4, 4, 5, 5 }; + int[] a = {1, 2, 2, 3, 3, 4, 4, 4, 5, 5}; assertTrue(CountFriendsPairing.countFriendsPairing(10, a)); } } diff --git a/src/test/java/com/thealgorithms/others/CountWordsTest.java b/src/test/java/com/thealgorithms/others/CountWordsTest.java index a2b0c03d..d5ebe654 100644 --- a/src/test/java/com/thealgorithms/others/CountWordsTest.java +++ b/src/test/java/com/thealgorithms/others/CountWordsTest.java @@ -5,7 +5,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.HashMap; import org.junit.jupiter.api.Test; - class CountWordsTest { @Test public void testWordCount() { diff --git a/src/test/java/com/thealgorithms/others/FirstFitCPUTest.java b/src/test/java/com/thealgorithms/others/FirstFitCPUTest.java index 33b77350..b726a746 100644 --- a/src/test/java/com/thealgorithms/others/FirstFitCPUTest.java +++ b/src/test/java/com/thealgorithms/others/FirstFitCPUTest.java @@ -19,9 +19,9 @@ class FirstFitCPUTest { @Test void testFitForUseOfOneBlock() { - //test1 - no use of one block for two processes - sizeOfBlocks = new int[] { 5, 12, 17, 10 }; - sizeOfProcesses = new int[] { 10, 5, 15, 2 }; + // test1 - no use of one block for two processes + sizeOfBlocks = new int[] {5, 12, 17, 10}; + sizeOfProcesses = new int[] {10, 5, 15, 2}; memAllocation = firstFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(1, 0, 2, 1)); assertEquals(testMemAllocation, memAllocation); @@ -29,9 +29,9 @@ class FirstFitCPUTest { @Test void testFitForEqualProcecesses() { - //test2 - sizeOfBlocks = new int[] { 5, 12, 17, 10 }; - sizeOfProcesses = new int[] { 10, 10, 10, 10 }; + // test2 + sizeOfBlocks = new int[] {5, 12, 17, 10}; + sizeOfProcesses = new int[] {10, 10, 10, 10}; memAllocation = firstFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(1, 2, 3, -255)); assertEquals(testMemAllocation, memAllocation); @@ -39,9 +39,9 @@ class FirstFitCPUTest { @Test void testFitForNoEmptyBlockCell() { - //test3 for more processes than blocks - no empty space left to none of the blocks - sizeOfBlocks = new int[] { 5, 12, 17 }; - sizeOfProcesses = new int[] { 5, 12, 10, 7 }; + // test3 for more processes than blocks - no empty space left to none of the blocks + sizeOfBlocks = new int[] {5, 12, 17}; + sizeOfProcesses = new int[] {5, 12, 10, 7}; memAllocation = firstFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(0, 1, 2, 2)); assertEquals(testMemAllocation, memAllocation); @@ -49,9 +49,9 @@ class FirstFitCPUTest { @Test void testFitForSameInputDifferentQuery() { - //test4 for more processes than blocks - one element does not fit due to input series - sizeOfBlocks = new int[] { 5, 12, 17 }; - sizeOfProcesses = new int[] { 5, 7, 10, 12 }; + // test4 for more processes than blocks - one element does not fit due to input series + sizeOfBlocks = new int[] {5, 12, 17}; + sizeOfProcesses = new int[] {5, 7, 10, 12}; memAllocation = firstFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(0, 1, 2, -255)); assertEquals(testMemAllocation, memAllocation); @@ -59,9 +59,9 @@ class FirstFitCPUTest { @Test void testFitForMoreBlocksNoFit() { - //test5 for more blocks than processes - sizeOfBlocks = new int[] { 5, 4, -1, 3, 6 }; - sizeOfProcesses = new int[] { 10, 11 }; + // test5 for more blocks than processes + sizeOfBlocks = new int[] {5, 4, -1, 3, 6}; + sizeOfProcesses = new int[] {10, 11}; memAllocation = firstFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(-255, -255)); assertEquals(testMemAllocation, memAllocation); diff --git a/src/test/java/com/thealgorithms/others/KadaneAlogrithmTest.java b/src/test/java/com/thealgorithms/others/KadaneAlogrithmTest.java index 74ca9a3e..ac2aa964 100644 --- a/src/test/java/com/thealgorithms/others/KadaneAlogrithmTest.java +++ b/src/test/java/com/thealgorithms/others/KadaneAlogrithmTest.java @@ -9,49 +9,49 @@ public class KadaneAlogrithmTest { @Test void testForOneElement() { - int[] a = { -1 }; + int[] a = {-1}; assertTrue(KadaneAlgorithm.max_Sum(a, -1)); } @Test void testForTwoElements() { - int[] a = { -2, 1 }; + int[] a = {-2, 1}; assertTrue(KadaneAlgorithm.max_Sum(a, 1)); } @Test void testForThreeElements() { - int[] a = { 5, 3, 12 }; + int[] a = {5, 3, 12}; assertTrue(KadaneAlgorithm.max_Sum(a, 20)); } @Test void testForFourElements() { - int[] a = { -1, -3, -7, -4 }; + int[] a = {-1, -3, -7, -4}; assertTrue(KadaneAlgorithm.max_Sum(a, -1)); } @Test void testForFiveElements() { - int[] a = { 4, 5, 3, 0, 2 }; + int[] a = {4, 5, 3, 0, 2}; assertTrue(KadaneAlgorithm.max_Sum(a, 14)); } @Test void testForSixElements() { - int[] a = { -43, -45, 47, 12, 87, -13 }; + int[] a = {-43, -45, 47, 12, 87, -13}; assertTrue(KadaneAlgorithm.max_Sum(a, 146)); } @Test void testForSevenElements() { - int[] a = { 9, 8, 2, 23, 13, 6, 7 }; + int[] a = {9, 8, 2, 23, 13, 6, 7}; assertTrue(KadaneAlgorithm.max_Sum(a, 68)); } @Test void testForEightElements() { - int[] a = { 9, -5, -5, -2, 4, 5, 0, 1 }; + int[] a = {9, -5, -5, -2, 4, 5, 0, 1}; assertTrue(KadaneAlgorithm.max_Sum(a, 10)); } } diff --git a/src/test/java/com/thealgorithms/others/LineSweepTest.java b/src/test/java/com/thealgorithms/others/LineSweepTest.java index 428556d4..20cf1cd7 100644 --- a/src/test/java/com/thealgorithms/others/LineSweepTest.java +++ b/src/test/java/com/thealgorithms/others/LineSweepTest.java @@ -1,29 +1,28 @@ package com.thealgorithms.others; import static org.junit.jupiter.api.Assertions.*; + import org.junit.jupiter.api.Test; public class LineSweepTest { - @Test - void testForOverlap(){ - int[][]arr = {{0,10},{7,20},{15,24}}; + void testForOverlap() { + int[][] arr = {{0, 10}, {7, 20}, {15, 24}}; assertTrue(LineSweep.isOverlap(arr)); } @Test - void testForNoOverlap(){ - int[][]arr = {{0,10},{11,20},{21,24}}; + void testForNoOverlap() { + int[][] arr = {{0, 10}, {11, 20}, {21, 24}}; assertFalse(LineSweep.isOverlap(arr)); } @Test - void testForOverlapWhenEndAEqualsStartBAndViceVersa(){ - int[][]arr = {{0,10},{10,20},{21,24}}; + void testForOverlapWhenEndAEqualsStartBAndViceVersa() { + int[][] arr = {{0, 10}, {10, 20}, {21, 24}}; assertTrue(LineSweep.isOverlap(arr)); } @Test - void testForMaximumEndPoint(){ - int[][]arr = {{10,20},{1,100},{14,16},{1,8}}; - assertEquals(100,LineSweep.FindMaximumEndPoint(arr)); + void testForMaximumEndPoint() { + int[][] arr = {{10, 20}, {1, 100}, {14, 16}, {1, 8}}; + assertEquals(100, LineSweep.FindMaximumEndPoint(arr)); } - } diff --git a/src/test/java/com/thealgorithms/others/LinkListSortTest.java b/src/test/java/com/thealgorithms/others/LinkListSortTest.java index 7c6da59c..e0e258aa 100644 --- a/src/test/java/com/thealgorithms/others/LinkListSortTest.java +++ b/src/test/java/com/thealgorithms/others/LinkListSortTest.java @@ -9,49 +9,49 @@ public class LinkListSortTest { @Test void testForOneElement() { - int[] a = { 56 }; + int[] a = {56}; assertTrue(LinkListSort.isSorted(a, 2)); } @Test void testForTwoElements() { - int[] a = { 6, 4 }; + int[] a = {6, 4}; assertTrue(LinkListSort.isSorted(a, 1)); } @Test void testForThreeElements() { - int[] a = { 875, 253, 12 }; + int[] a = {875, 253, 12}; assertTrue(LinkListSort.isSorted(a, 3)); } @Test void testForFourElements() { - int[] a = { 86, 32, 87, 13 }; + int[] a = {86, 32, 87, 13}; assertTrue(LinkListSort.isSorted(a, 1)); } @Test void testForFiveElements() { - int[] a = { 6, 5, 3, 0, 9 }; + int[] a = {6, 5, 3, 0, 9}; assertTrue(LinkListSort.isSorted(a, 1)); } @Test void testForSixElements() { - int[] a = { 9, 65, 432, 32, 47, 327 }; + int[] a = {9, 65, 432, 32, 47, 327}; assertTrue(LinkListSort.isSorted(a, 3)); } @Test void testForSevenElements() { - int[] a = { 6, 4, 2, 1, 3, 6, 7 }; + int[] a = {6, 4, 2, 1, 3, 6, 7}; assertTrue(LinkListSort.isSorted(a, 1)); } @Test void testForEightElements() { - int[] a = { 123, 234, 145, 764, 322, 367, 768, 34 }; + int[] a = {123, 234, 145, 764, 322, 367, 768, 34}; assertTrue(LinkListSort.isSorted(a, 2)); } } diff --git a/src/test/java/com/thealgorithms/others/LowestBasePalindromeTest.java b/src/test/java/com/thealgorithms/others/LowestBasePalindromeTest.java index 3124d7b0..1de115bb 100644 --- a/src/test/java/com/thealgorithms/others/LowestBasePalindromeTest.java +++ b/src/test/java/com/thealgorithms/others/LowestBasePalindromeTest.java @@ -1,14 +1,13 @@ package com.thealgorithms.others; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; -import java.util.HashMap; import java.util.ArrayList; import java.util.Arrays; - +import java.util.HashMap; import org.junit.jupiter.api.Test; public class LowestBasePalindromeTest { @@ -17,14 +16,18 @@ public class LowestBasePalindromeTest { assertTrue(LowestBasePalindrome.isPalindromic(new ArrayList())); assertTrue(LowestBasePalindrome.isPalindromic(new ArrayList(Arrays.asList(1)))); assertTrue(LowestBasePalindrome.isPalindromic(new ArrayList(Arrays.asList(1, 1)))); - assertTrue(LowestBasePalindrome.isPalindromic(new ArrayList(Arrays.asList(1, 2, 1)))); - assertTrue(LowestBasePalindrome.isPalindromic(new ArrayList(Arrays.asList(1, 2, 2, 1)))); + assertTrue( + LowestBasePalindrome.isPalindromic(new ArrayList(Arrays.asList(1, 2, 1)))); + assertTrue( + LowestBasePalindrome.isPalindromic(new ArrayList(Arrays.asList(1, 2, 2, 1)))); } @Test public void testIsPalindromicNegative() { - assertFalse(LowestBasePalindrome.isPalindromic(new ArrayList(Arrays.asList(1, 2)))); - assertFalse(LowestBasePalindrome.isPalindromic(new ArrayList(Arrays.asList(1, 2, 1, 1)))); + assertFalse( + LowestBasePalindrome.isPalindromic(new ArrayList(Arrays.asList(1, 2)))); + assertFalse( + LowestBasePalindrome.isPalindromic(new ArrayList(Arrays.asList(1, 2, 1, 1)))); } @Test @@ -45,17 +48,13 @@ public class LowestBasePalindromeTest { @Test public void testIsPalindromicInBaseThrowsExceptionForNegativeNumbers() { assertThrows( - IllegalArgumentException.class, - () -> LowestBasePalindrome.isPalindromicInBase(-1, 5) - ); + IllegalArgumentException.class, () -> LowestBasePalindrome.isPalindromicInBase(-1, 5)); } @Test public void testIsPalindromicInBaseThrowsExceptionForWrongBases() { assertThrows( - IllegalArgumentException.class, - () -> LowestBasePalindrome.isPalindromicInBase(10, 1) - ); + IllegalArgumentException.class, () -> LowestBasePalindrome.isPalindromicInBase(10, 1)); } @Test diff --git a/src/test/java/com/thealgorithms/others/NextFitTest.java b/src/test/java/com/thealgorithms/others/NextFitTest.java index bd1df907..2de6b411 100644 --- a/src/test/java/com/thealgorithms/others/NextFitTest.java +++ b/src/test/java/com/thealgorithms/others/NextFitTest.java @@ -19,9 +19,9 @@ class NextFitCPUTest { @Test void testFitForUseOfOneBlock() { - //test1 - third process does not fit because of algorithms procedure - sizeOfBlocks = new int[] { 5, 12, 17, 10 }; - sizeOfProcesses = new int[] { 10, 5, 15, 2 }; + // test1 - third process does not fit because of algorithms procedure + sizeOfBlocks = new int[] {5, 12, 17, 10}; + sizeOfProcesses = new int[] {10, 5, 15, 2}; memAllocation = nextFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(1, 2, -255, 2)); assertEquals(testMemAllocation, memAllocation); @@ -29,9 +29,9 @@ class NextFitCPUTest { @Test void testFitForEqualProcecesses() { - //test2 - sizeOfBlocks = new int[] { 5, 12, 17, 10 }; - sizeOfProcesses = new int[] { 10, 10, 10, 10 }; + // test2 + sizeOfBlocks = new int[] {5, 12, 17, 10}; + sizeOfProcesses = new int[] {10, 10, 10, 10}; memAllocation = nextFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(1, 2, 3, -255)); assertEquals(testMemAllocation, memAllocation); @@ -39,9 +39,9 @@ class NextFitCPUTest { @Test void testFitForNoEmptyBlockCell() { - //test3 for more processes than blocks - no empty space left to none of the blocks - sizeOfBlocks = new int[] { 5, 12, 17 }; - sizeOfProcesses = new int[] { 5, 12, 10, 7 }; + // test3 for more processes than blocks - no empty space left to none of the blocks + sizeOfBlocks = new int[] {5, 12, 17}; + sizeOfProcesses = new int[] {5, 12, 10, 7}; memAllocation = nextFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(0, 1, 2, 2)); assertEquals(testMemAllocation, memAllocation); @@ -49,9 +49,9 @@ class NextFitCPUTest { @Test void testFitForSameInputDifferentQuery() { - //test4 for more processes than blocks - one element does not fit due to input series - sizeOfBlocks = new int[] { 5, 12, 17 }; - sizeOfProcesses = new int[] { 5, 7, 10, 12 }; + // test4 for more processes than blocks - one element does not fit due to input series + sizeOfBlocks = new int[] {5, 12, 17}; + sizeOfProcesses = new int[] {5, 7, 10, 12}; memAllocation = nextFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(0, 1, 2, -255)); assertEquals(testMemAllocation, memAllocation); @@ -59,9 +59,9 @@ class NextFitCPUTest { @Test void testFitForMoreBlocksNoFit() { - //test5 for more blocks than processes - sizeOfBlocks = new int[] { 5, 4, -1, 3, 6 }; - sizeOfProcesses = new int[] { 10, 11 }; + // test5 for more blocks than processes + sizeOfBlocks = new int[] {5, 4, -1, 3, 6}; + sizeOfProcesses = new int[] {10, 11}; memAllocation = nextFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(-255, -255)); assertEquals(testMemAllocation, memAllocation); diff --git a/src/test/java/com/thealgorithms/others/PasswordGenTest.java b/src/test/java/com/thealgorithms/others/PasswordGenTest.java index 3bdcc955..8bf0d58e 100644 --- a/src/test/java/com/thealgorithms/others/PasswordGenTest.java +++ b/src/test/java/com/thealgorithms/others/PasswordGenTest.java @@ -9,12 +9,8 @@ public class PasswordGenTest { @Test public void failGenerationWithSameMinMaxLengthTest() { int length = 10; - assertThrows( - IllegalArgumentException.class, - () -> { - PasswordGen.generatePassword(length, length); - } - ); + assertThrows(IllegalArgumentException.class, + () -> { PasswordGen.generatePassword(length, length); }); } @Test @@ -27,12 +23,8 @@ public class PasswordGenTest { public void failGenerationWithMinLengthSmallerThanMaxLengthTest() { int minLength = 10; int maxLength = 5; - assertThrows( - IllegalArgumentException.class, - () -> { - PasswordGen.generatePassword(minLength, maxLength); - } - ); + assertThrows(IllegalArgumentException.class, + () -> { PasswordGen.generatePassword(minLength, maxLength); }); } @Test diff --git a/src/test/java/com/thealgorithms/others/TestPrintMatrixInSpiralOrder.java b/src/test/java/com/thealgorithms/others/TestPrintMatrixInSpiralOrder.java index 867311e1..03393651 100644 --- a/src/test/java/com/thealgorithms/others/TestPrintMatrixInSpiralOrder.java +++ b/src/test/java/com/thealgorithms/others/TestPrintMatrixInSpiralOrder.java @@ -1,32 +1,25 @@ package com.thealgorithms.others; -import java.util.List; - -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; +import java.util.List; +import org.junit.jupiter.api.Test; + public class TestPrintMatrixInSpiralOrder { @Test public void testOne() { - int[][] matrix = { - { 3, 4, 5, 6, 7 }, - { 8, 9, 10, 11, 12 }, - { 14, 15, 16, 17, 18 }, - { 23, 24, 25, 26, 27 }, - { 30, 31, 32, 33, 34 } - }; + int[][] matrix = {{3, 4, 5, 6, 7}, {8, 9, 10, 11, 12}, {14, 15, 16, 17, 18}, + {23, 24, 25, 26, 27}, {30, 31, 32, 33, 34}}; var printClass = new PrintAMatrixInSpiralOrder(); List res = printClass.print(matrix, matrix.length, matrix[0].length); - List list = List.of(3, 4, 5, 6, 7, 12, 18, 27, 34, 33, 32, 31, 30, 23, 14, 8, 9, 10, 11, 17, 26, 25, - 24, 15, 16); + List list = List.of(3, 4, 5, 6, 7, 12, 18, 27, 34, 33, 32, 31, 30, 23, 14, 8, 9, + 10, 11, 17, 26, 25, 24, 15, 16); assertIterableEquals(res, list); } @Test public void testTwo() { - int[][] matrix = { - { 2, 2 } - }; + int[][] matrix = {{2, 2}}; var printClass = new PrintAMatrixInSpiralOrder(); List res = printClass.print(matrix, matrix.length, matrix[0].length); List list = List.of(2, 2); diff --git a/src/test/java/com/thealgorithms/others/TwoPointersTest.java b/src/test/java/com/thealgorithms/others/TwoPointersTest.java index 7241140c..8cadb031 100644 --- a/src/test/java/com/thealgorithms/others/TwoPointersTest.java +++ b/src/test/java/com/thealgorithms/others/TwoPointersTest.java @@ -1,44 +1,43 @@ package com.thealgorithms.others; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; public class TwoPointersTest { - @Test - void twoPointersFirstTestCase(){ - int[] arr = {2,6,9,22,121}; + void twoPointersFirstTestCase() { + int[] arr = {2, 6, 9, 22, 121}; int key = 28; - assertEquals(true, TwoPointers.isPairedSum(arr,key)); + assertEquals(true, TwoPointers.isPairedSum(arr, key)); } @Test - void twoPointersSecondTestCase(){ - int[] arr = {-1,-12,12,0,8}; + void twoPointersSecondTestCase() { + int[] arr = {-1, -12, 12, 0, 8}; int key = 0; - assertEquals(true, TwoPointers.isPairedSum(arr,key)); + assertEquals(true, TwoPointers.isPairedSum(arr, key)); } @Test - void twoPointersThirdTestCase(){ - int[] arr = {12,35,12,152,0}; + void twoPointersThirdTestCase() { + int[] arr = {12, 35, 12, 152, 0}; int key = 13; - assertEquals(false, TwoPointers.isPairedSum(arr,key)); + assertEquals(false, TwoPointers.isPairedSum(arr, key)); } @Test - void twoPointersFourthTestCase(){ - int[] arr = {-2,5,-1,52,31}; + void twoPointersFourthTestCase() { + int[] arr = {-2, 5, -1, 52, 31}; int key = -3; - assertEquals(true, TwoPointers.isPairedSum(arr,key)); + assertEquals(true, TwoPointers.isPairedSum(arr, key)); } @Test - void twoPointersFiftiethTestCase(){ - int[] arr = {25,1,0,61,21}; + void twoPointersFiftiethTestCase() { + int[] arr = {25, 1, 0, 61, 21}; int key = 12; - assertEquals(false, TwoPointers.isPairedSum(arr,key)); + assertEquals(false, TwoPointers.isPairedSum(arr, key)); } } diff --git a/src/test/java/com/thealgorithms/others/WorstFitCPUTest.java b/src/test/java/com/thealgorithms/others/WorstFitCPUTest.java index 5d27d0de..6f2a53b3 100644 --- a/src/test/java/com/thealgorithms/others/WorstFitCPUTest.java +++ b/src/test/java/com/thealgorithms/others/WorstFitCPUTest.java @@ -19,9 +19,9 @@ class WorstFitCPUTest { @Test void testFitForUseOfOneBlock() { - //test1 - sizeOfBlocks = new int[] { 5, 12, 17, 10 }; - sizeOfProcesses = new int[] { 10, 5, 15, 2 }; + // test1 + sizeOfBlocks = new int[] {5, 12, 17, 10}; + sizeOfProcesses = new int[] {10, 5, 15, 2}; memAllocation = worstFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(2, 1, -255, 3)); assertEquals(testMemAllocation, memAllocation); @@ -29,9 +29,9 @@ class WorstFitCPUTest { @Test void testFitForEqualProcecesses() { - //test2 - sizeOfBlocks = new int[] { 5, 12, 17, 10 }; - sizeOfProcesses = new int[] { 10, 10, 10, 10 }; + // test2 + sizeOfBlocks = new int[] {5, 12, 17, 10}; + sizeOfProcesses = new int[] {10, 10, 10, 10}; memAllocation = worstFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(2, 1, 3, -255)); assertEquals(testMemAllocation, memAllocation); @@ -39,9 +39,9 @@ class WorstFitCPUTest { @Test void testFitForNoEmptyBlockCell() { - //test3 - could suits best, bad use of memory allocation due to worstFit algorithm - sizeOfBlocks = new int[] { 5, 12, 17 }; - sizeOfProcesses = new int[] { 5, 12, 10, 7 }; + // test3 - could suits best, bad use of memory allocation due to worstFit algorithm + sizeOfBlocks = new int[] {5, 12, 17}; + sizeOfProcesses = new int[] {5, 12, 10, 7}; memAllocation = worstFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(2, 1, 2, -255)); assertEquals(testMemAllocation, memAllocation); @@ -49,9 +49,9 @@ class WorstFitCPUTest { @Test void testFitForSameInputDifferentQuery() { - //test4 same example different series - same results - sizeOfBlocks = new int[] { 5, 12, 17 }; - sizeOfProcesses = new int[] { 5, 7, 10, 12 }; + // test4 same example different series - same results + sizeOfBlocks = new int[] {5, 12, 17}; + sizeOfProcesses = new int[] {5, 7, 10, 12}; memAllocation = worstFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(2, 1, 2, -255)); assertEquals(testMemAllocation, memAllocation); @@ -59,9 +59,9 @@ class WorstFitCPUTest { @Test void testFitForMoreBlocksNoFit() { - //test5 for more blocks than processes - sizeOfBlocks = new int[] { 5, 4, -1, 3, 6 }; - sizeOfProcesses = new int[] { 10, 11 }; + // test5 for more blocks than processes + sizeOfBlocks = new int[] {5, 4, -1, 3, 6}; + sizeOfProcesses = new int[] {10, 11}; memAllocation = worstFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(-255, -255)); assertEquals(testMemAllocation, memAllocation); @@ -69,12 +69,11 @@ class WorstFitCPUTest { @Test void testFitBadCase() { - //test6 for only two process fit - sizeOfBlocks = new int[] { 7, 17, 7, 5, 6 }; - sizeOfProcesses = new int[] { 8, 10, 10, 8, 8, 8 }; + // test6 for only two process fit + sizeOfBlocks = new int[] {7, 17, 7, 5, 6}; + sizeOfProcesses = new int[] {8, 10, 10, 8, 8, 8}; memAllocation = worstFit.fitProcess(sizeOfBlocks, sizeOfProcesses); - testMemAllocation = - new ArrayList<>(Arrays.asList(1, -255, -255, 1, -255, -255)); + testMemAllocation = new ArrayList<>(Arrays.asList(1, -255, -255, 1, -255, -255)); assertEquals(testMemAllocation, memAllocation); } } diff --git a/src/test/java/com/thealgorithms/others/cn/HammingDistanceTest.java b/src/test/java/com/thealgorithms/others/cn/HammingDistanceTest.java index bbefadee..f9b517eb 100644 --- a/src/test/java/com/thealgorithms/others/cn/HammingDistanceTest.java +++ b/src/test/java/com/thealgorithms/others/cn/HammingDistanceTest.java @@ -46,8 +46,8 @@ public class HammingDistanceTest { @Test public void checkForLongDataBits() { - String senderBits = "10010101101010000100110100", receiverBits = - "00110100001011001100110101"; + String senderBits = "10010101101010000100110100", + receiverBits = "00110100001011001100110101"; int answer = hd.getHammingDistanceBetweenBits(senderBits, receiverBits); Assertions.assertThat(answer).isEqualTo(7); } @@ -56,23 +56,16 @@ public class HammingDistanceTest { public void mismatchDataBits() { String senderBits = "100010", receiverBits = "00011"; - Exception ex = org.junit.jupiter.api.Assertions.assertThrows( - IllegalArgumentException.class, - () -> { - int answer = hd.getHammingDistanceBetweenBits( - senderBits, - receiverBits - ); - } - ); + Exception ex = org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class, + () -> { int answer = hd.getHammingDistanceBetweenBits(senderBits, receiverBits); }); Assertions.assertThat(ex.getMessage()).contains("bits should be same"); } @Test public void checkForLongDataBitsSame() { - String senderBits = "10010101101010000100110100", receiverBits = - "10010101101010000100110100"; + String senderBits = "10010101101010000100110100", + receiverBits = "10010101101010000100110100"; int answer = hd.getHammingDistanceBetweenBits(senderBits, receiverBits); Assertions.assertThat(answer).isEqualTo(0); } diff --git a/src/test/java/com/thealgorithms/scheduling/FCFSSchedulingTest.java b/src/test/java/com/thealgorithms/scheduling/FCFSSchedulingTest.java index c25a9c93..87b3d12c 100644 --- a/src/test/java/com/thealgorithms/scheduling/FCFSSchedulingTest.java +++ b/src/test/java/com/thealgorithms/scheduling/FCFSSchedulingTest.java @@ -1,15 +1,13 @@ package com.thealgorithms.scheduling; -import com.thealgorithms.devutils.entities.ProcessDetails; -import org.junit.jupiter.api.Test; - -import java.util.ArrayList; -import java.util.List; - import static org.junit.jupiter.api.Assertions.assertEquals; -public class FCFSSchedulingTest { +import com.thealgorithms.devutils.entities.ProcessDetails; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; +public class FCFSSchedulingTest { @Test public void testingProcesses() { @@ -31,7 +29,6 @@ public class FCFSSchedulingTest { assertEquals("P3", processes.get(2).getProcessId()); assertEquals(15, processes.get(2).getWaitingTime()); assertEquals(23, processes.get(2).getTurnAroundTimeTime()); - } private List addProcessesForFCFS() { @@ -46,5 +43,4 @@ public class FCFSSchedulingTest { return processDetails; } - } diff --git a/src/test/java/com/thealgorithms/scheduling/RRSchedulingTest.java b/src/test/java/com/thealgorithms/scheduling/RRSchedulingTest.java index 935ff733..1d9b7a7f 100644 --- a/src/test/java/com/thealgorithms/scheduling/RRSchedulingTest.java +++ b/src/test/java/com/thealgorithms/scheduling/RRSchedulingTest.java @@ -3,16 +3,16 @@ package com.thealgorithms.scheduling; import static org.junit.jupiter.api.Assertions.*; import com.thealgorithms.devutils.entities.ProcessDetails; -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.List; +import org.junit.jupiter.api.Test; class RRSchedulingTest { @Test public void testingProcesses() { List processes = addProcessesForRR(); - final RRScheduling rrScheduling = new RRScheduling(processes, 4); // for sending to RR with quantum value 4 + final RRScheduling rrScheduling + = new RRScheduling(processes, 4); // for sending to RR with quantum value 4 rrScheduling.scheduleProcesses(); @@ -41,7 +41,6 @@ class RRSchedulingTest { assertEquals("P6", processes.get(5).getProcessId()); assertEquals(11, processes.get(5).getWaitingTime()); assertEquals(15, processes.get(5).getTurnAroundTimeTime()); - } private List addProcessesForRR() { diff --git a/src/test/java/com/thealgorithms/scheduling/SJFSchedulingTest.java b/src/test/java/com/thealgorithms/scheduling/SJFSchedulingTest.java index 8ba3b679..66bfe095 100644 --- a/src/test/java/com/thealgorithms/scheduling/SJFSchedulingTest.java +++ b/src/test/java/com/thealgorithms/scheduling/SJFSchedulingTest.java @@ -1,120 +1,109 @@ package com.thealgorithms.scheduling; -import com.thealgorithms.devutils.entities.ProcessDetails; -import org.junit.jupiter.api.Test; - -import java.util.ArrayList; - import static org.junit.jupiter.api.Assertions.*; +import com.thealgorithms.devutils.entities.ProcessDetails; +import java.util.ArrayList; +import org.junit.jupiter.api.Test; + class SJFSchedulingTest { - private ArrayList process; - void initialisation0() - { + private ArrayList process; + void initialisation0() { - process=new ArrayList<>(); - process.add(new ProcessDetails("1",0 ,6)); - process.add(new ProcessDetails("2",1,2)); + process = new ArrayList<>(); + process.add(new ProcessDetails("1", 0, 6)); + process.add(new ProcessDetails("2", 1, 2)); } - void initialisation1() - { + void initialisation1() { - process=new ArrayList<>(); - process.add(new ProcessDetails("1",0 ,6)); - process.add(new ProcessDetails("2",1,2)); - process.add(new ProcessDetails("3",4 ,3)); - process.add(new ProcessDetails("4",3,1)); - process.add(new ProcessDetails("5",6 ,4)); - process.add(new ProcessDetails("6",5,5)); + process = new ArrayList<>(); + process.add(new ProcessDetails("1", 0, 6)); + process.add(new ProcessDetails("2", 1, 2)); + process.add(new ProcessDetails("3", 4, 3)); + process.add(new ProcessDetails("4", 3, 1)); + process.add(new ProcessDetails("5", 6, 4)); + process.add(new ProcessDetails("6", 5, 5)); } - void initialisation2() - { - - process=new ArrayList<>(); - process.add(new ProcessDetails("1",0 ,3)); - process.add(new ProcessDetails("2",1,2)); - process.add(new ProcessDetails("3",2 ,1)); + void initialisation2() { + process = new ArrayList<>(); + process.add(new ProcessDetails("1", 0, 3)); + process.add(new ProcessDetails("2", 1, 2)); + process.add(new ProcessDetails("3", 2, 1)); } - void initialisation3(){ - process=new ArrayList<>(); - process.add(new ProcessDetails("1",0 ,3)); - process.add(new ProcessDetails("2",5,2)); - process.add(new ProcessDetails("3",9 ,1)); + void initialisation3() { + process = new ArrayList<>(); + process.add(new ProcessDetails("1", 0, 3)); + process.add(new ProcessDetails("2", 5, 2)); + process.add(new ProcessDetails("3", 9, 1)); } @Test - void constructor() - { + void constructor() { initialisation0(); - SJFScheduling a=new SJFScheduling(process); - assertEquals( 6,a.processes.get(0).getBurstTime()); - assertEquals( 2,a.processes.get(1).getBurstTime()); + SJFScheduling a = new SJFScheduling(process); + assertEquals(6, a.processes.get(0).getBurstTime()); + assertEquals(2, a.processes.get(1).getBurstTime()); } - @Test - void sort() - { + @Test + void sort() { initialisation1(); - SJFScheduling a=new SJFScheduling(process); + SJFScheduling a = new SJFScheduling(process); a.sortByArrivalTime(); - assertEquals("1",a.processes.get(0).getProcessId()); - assertEquals("2",a.processes.get(1).getProcessId()); - assertEquals("3",a.processes.get(3).getProcessId()); - assertEquals("4",a.processes.get(2).getProcessId()); - assertEquals("5",a.processes.get(5).getProcessId()); - assertEquals("6",a.processes.get(4).getProcessId()); - + assertEquals("1", a.processes.get(0).getProcessId()); + assertEquals("2", a.processes.get(1).getProcessId()); + assertEquals("3", a.processes.get(3).getProcessId()); + assertEquals("4", a.processes.get(2).getProcessId()); + assertEquals("5", a.processes.get(5).getProcessId()); + assertEquals("6", a.processes.get(4).getProcessId()); } @Test - void scheduling(){ + void scheduling() { initialisation1(); - SJFScheduling a=new SJFScheduling(process); + SJFScheduling a = new SJFScheduling(process); a.scheduleProcesses(); - assertEquals( "1" , a.schedule.get(0)); - assertEquals( "4" , a.schedule.get(1)); - assertEquals( "2" , a.schedule.get(2)); - assertEquals( "3" , a.schedule.get(3)); - assertEquals("5" , a.schedule.get(4)); - assertEquals( "6", a.schedule.get(5)); - - + assertEquals("1", a.schedule.get(0)); + assertEquals("4", a.schedule.get(1)); + assertEquals("2", a.schedule.get(2)); + assertEquals("3", a.schedule.get(3)); + assertEquals("5", a.schedule.get(4)); + assertEquals("6", a.schedule.get(5)); } @Test - void schedulingOf_TwoProcesses(){ + void schedulingOf_TwoProcesses() { initialisation0(); - SJFScheduling a=new SJFScheduling(process); + SJFScheduling a = new SJFScheduling(process); a.scheduleProcesses(); - assertEquals( "1" , a.schedule.get(0)); - assertEquals( "2" , a.schedule.get(1)); + assertEquals("1", a.schedule.get(0)); + assertEquals("2", a.schedule.get(1)); } @Test - void schedulingOfA_ShortestJobArrivingLast(){ + void schedulingOfA_ShortestJobArrivingLast() { initialisation2(); - SJFScheduling a=new SJFScheduling(process); + SJFScheduling a = new SJFScheduling(process); a.scheduleProcesses(); - assertEquals( "1" , a.schedule.get(0)); - assertEquals( "3" , a.schedule.get(1)); - assertEquals( "2" , a.schedule.get(2)); + assertEquals("1", a.schedule.get(0)); + assertEquals("3", a.schedule.get(1)); + assertEquals("2", a.schedule.get(2)); } @Test - void scheduling_WithProcessesNotComingBackToBack(){ + void scheduling_WithProcessesNotComingBackToBack() { initialisation3(); - SJFScheduling a=new SJFScheduling(process); + SJFScheduling a = new SJFScheduling(process); a.scheduleProcesses(); - assertEquals( "1" , a.schedule.get(0)); - assertEquals( "2" , a.schedule.get(1)); - assertEquals( "3" , a.schedule.get(2)); + assertEquals("1", a.schedule.get(0)); + assertEquals("2", a.schedule.get(1)); + assertEquals("3", a.schedule.get(2)); } @Test - void schedulingOf_nothing(){ - process=new ArrayList<>(); - SJFScheduling a=new SJFScheduling(process); + void schedulingOf_nothing() { + process = new ArrayList<>(); + SJFScheduling a = new SJFScheduling(process); a.scheduleProcesses(); - assertTrue( a.schedule.isEmpty()); - + assertTrue(a.schedule.isEmpty()); } } \ No newline at end of file diff --git a/src/test/java/com/thealgorithms/searches/BinarySearch2dArrayTest.java b/src/test/java/com/thealgorithms/searches/BinarySearch2dArrayTest.java index 0db17bdb..4910762c 100644 --- a/src/test/java/com/thealgorithms/searches/BinarySearch2dArrayTest.java +++ b/src/test/java/com/thealgorithms/searches/BinarySearch2dArrayTest.java @@ -4,20 +4,19 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.*; -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.AfterAll; - +import org.junit.jupiter.api.Test; public class BinarySearch2dArrayTest { @Test // valid test case public void BinarySearch2dArrayTestMiddle() { - int[][] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; + int[][] arr = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; int target = 6; int[] ans = BinarySearch2dArray.BinarySearch(arr, target); - int[] expected = { 1, 1 }; + int[] expected = {1, 1}; System.out.println(Arrays.toString(ans)); assertEquals(1, ans[0]); assertEquals(1, ans[1]); @@ -26,11 +25,11 @@ public class BinarySearch2dArrayTest { @Test // valid test case public void BinarySearch2dArrayTestMiddleSide() { - int[][] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; + int[][] arr = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; int target = 8; int[] ans = BinarySearch2dArray.BinarySearch(arr, target); - int[] expected = { 1, 3 }; + int[] expected = {1, 3}; System.out.println(Arrays.toString(ans)); assertEquals(1, ans[0]); assertEquals(3, ans[1]); @@ -39,11 +38,11 @@ public class BinarySearch2dArrayTest { @Test // valid test case public void BinarySearch2dArrayTestUpper() { - int[][] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; + int[][] arr = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; int target = 2; int[] ans = BinarySearch2dArray.BinarySearch(arr, target); - int[] expected = { 0, 1 }; + int[] expected = {0, 1}; System.out.println(Arrays.toString(ans)); assertEquals(0, ans[0]); assertEquals(1, ans[1]); @@ -52,11 +51,11 @@ public class BinarySearch2dArrayTest { @Test // valid test case public void BinarySearch2dArrayTestUpperSide() { - int[][] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; + int[][] arr = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; int target = 1; int[] ans = BinarySearch2dArray.BinarySearch(arr, target); - int[] expected = { 0, 0 }; + int[] expected = {0, 0}; System.out.println(Arrays.toString(ans)); assertEquals(0, ans[0]); assertEquals(0, ans[1]); @@ -65,11 +64,11 @@ public class BinarySearch2dArrayTest { @Test // valid test case public void BinarySearch2dArrayTestLower() { - int[][] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; + int[][] arr = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; int target = 10; int[] ans = BinarySearch2dArray.BinarySearch(arr, target); - int[] expected = { 2, 1 }; + int[] expected = {2, 1}; System.out.println(Arrays.toString(ans)); assertEquals(2, ans[0]); assertEquals(1, ans[1]); @@ -78,11 +77,11 @@ public class BinarySearch2dArrayTest { @Test // valid test case public void BinarySearch2dArrayTestLowerSide() { - int[][] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; + int[][] arr = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; int target = 11; int[] ans = BinarySearch2dArray.BinarySearch(arr, target); - int[] expected = { 2, 2 }; + int[] expected = {2, 2}; System.out.println(Arrays.toString(ans)); assertEquals(2, ans[0]); assertEquals(2, ans[1]); @@ -91,11 +90,11 @@ public class BinarySearch2dArrayTest { @Test // valid test case public void BinarySearch2dArrayTestNotFound() { - int[][] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; + int[][] arr = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; int target = 101; int[] ans = BinarySearch2dArray.BinarySearch(arr, target); - int[] expected = { -1, -1 }; + int[] expected = {-1, -1}; System.out.println(Arrays.toString(ans)); assertEquals(-1, ans[0]); assertEquals(-1, ans[1]); @@ -106,7 +105,7 @@ public class BinarySearch2dArrayTest { */ @Test public void BinarySearch2dArrayTestOneRow() { - int[][] arr = { { 1, 2, 3, 4 }}; + int[][] arr = {{1, 2, 3, 4}}; int target = 2; // Assert that the requirement, that the array only has one row, is fulfilled. @@ -122,10 +121,11 @@ public class BinarySearch2dArrayTest { */ @Test public void BinarySearch2dArrayTestTargetInMiddle() { - int[][] arr = { { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, { 11, 12, 13, 14, 15} }; + int[][] arr = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}}; int target = 8; - // Assert that the requirement, that the target is in the middle row and middle column, is fulfilled. - assertEquals(arr[arr.length/2][arr[0].length/2], target); + // Assert that the requirement, that the target is in the middle row and middle column, is + // fulfilled. + assertEquals(arr[arr.length / 2][arr[0].length / 2], target); int[] ans = BinarySearch2dArray.BinarySearch(arr, target); System.out.println(Arrays.toString(ans)); assertEquals(1, ans[0]); @@ -138,13 +138,13 @@ public class BinarySearch2dArrayTest { */ @Test public void BinarySearch2dArrayTestTargetAboveMiddleRowInMiddleColumn() { - int[][] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; + int[][] arr = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; int target = 3; // Assert that the requirement, that he target is in the middle column, // in an array with an even number of columns, and on the row "above" the middle row. assertEquals(arr[0].length % 2, 0); - assertEquals(arr[arr.length/2-1][arr[0].length/2], target); + assertEquals(arr[arr.length / 2 - 1][arr[0].length / 2], target); int[] ans = BinarySearch2dArray.BinarySearch(arr, target); System.out.println(Arrays.toString(ans)); assertEquals(0, ans[0]); @@ -160,7 +160,7 @@ public class BinarySearch2dArrayTest { int target = 5; // Assert that an empty array is not valid input for the method. - assertThrows(ArrayIndexOutOfBoundsException.class, () -> BinarySearch2dArray.BinarySearch(arr, target)); + assertThrows(ArrayIndexOutOfBoundsException.class, + () -> BinarySearch2dArray.BinarySearch(arr, target)); } - } diff --git a/src/test/java/com/thealgorithms/searches/BreadthFirstSearchTest.java b/src/test/java/com/thealgorithms/searches/BreadthFirstSearchTest.java index d0ddc820..5912458f 100644 --- a/src/test/java/com/thealgorithms/searches/BreadthFirstSearchTest.java +++ b/src/test/java/com/thealgorithms/searches/BreadthFirstSearchTest.java @@ -1,28 +1,21 @@ package com.thealgorithms.searches; -import org.junit.jupiter.api.Test; - -import java.util.List; -import java.util.Optional; - import static org.junit.jupiter.api.Assertions.*; +import java.util.List; +import java.util.Optional; +import org.junit.jupiter.api.Test; + class BreadthFirstSearchTest { - private static final DepthFirstSearch.Node rootNode = new DepthFirstSearch.Node( - "A", - List.of( - new DepthFirstSearch.Node( - "B", - List.of( - new DepthFirstSearch.Node("D"), - new DepthFirstSearch.Node("F", List.of(new DepthFirstSearch.Node("H"), new DepthFirstSearch.Node("I"))) - ) - ), - new DepthFirstSearch.Node("C", List.of(new DepthFirstSearch.Node("G"))), - new DepthFirstSearch.Node("E") - ) - ); + private static final DepthFirstSearch.Node rootNode = new DepthFirstSearch.Node("A", + List.of( + new DepthFirstSearch.Node("B", + List.of(new DepthFirstSearch.Node("D"), + new DepthFirstSearch.Node("F", + List.of(new DepthFirstSearch.Node("H"), new DepthFirstSearch.Node("I"))))), + new DepthFirstSearch.Node("C", List.of(new DepthFirstSearch.Node("G"))), + new DepthFirstSearch.Node("E"))); @Test void searchI() { diff --git a/src/test/java/com/thealgorithms/searches/HowManyTimesRotatedTest.java b/src/test/java/com/thealgorithms/searches/HowManyTimesRotatedTest.java index 320222f5..ac731b0f 100644 --- a/src/test/java/com/thealgorithms/searches/HowManyTimesRotatedTest.java +++ b/src/test/java/com/thealgorithms/searches/HowManyTimesRotatedTest.java @@ -8,10 +8,9 @@ public class HowManyTimesRotatedTest { @Test public void testHowManyTimesRotated() { - int[] arr1 = {5, 1,2,3,4}; + int[] arr1 = {5, 1, 2, 3, 4}; assertEquals(1, HowManyTimesRotated.rotated(arr1)); - int[] arr2 = {15,17,2,3,5}; + int[] arr2 = {15, 17, 2, 3, 5}; assertEquals(2, HowManyTimesRotated.rotated(arr2)); } } - diff --git a/src/test/java/com/thealgorithms/searches/OrderAgnosticBinarySearchTest.java b/src/test/java/com/thealgorithms/searches/OrderAgnosticBinarySearchTest.java index 8194d345..afcbc52f 100644 --- a/src/test/java/com/thealgorithms/searches/OrderAgnosticBinarySearchTest.java +++ b/src/test/java/com/thealgorithms/searches/OrderAgnosticBinarySearchTest.java @@ -1,72 +1,69 @@ package com.thealgorithms.searches; -import com.thealgorithms.searches.OrderAgnosticBinarySearch; - -import org.junit.jupiter.api.Test; - -import java.util.*; - import static org.junit.jupiter.api.Assertions.assertEquals; +import com.thealgorithms.searches.OrderAgnosticBinarySearch; +import java.util.*; +import org.junit.jupiter.api.Test; public class OrderAgnosticBinarySearchTest { - @Test - //valid Test Case - public void ElementInMiddle() { - int[] arr = {10, 20, 30, 40, 50}; - int answer = OrderAgnosticBinarySearch.BinSearchAlgo(arr, 0, arr.length - 1, 30); - System.out.println(answer); - int expected = 2; - assertEquals(expected, answer); - } + @Test + // valid Test Case + public void ElementInMiddle() { + int[] arr = {10, 20, 30, 40, 50}; + int answer = OrderAgnosticBinarySearch.BinSearchAlgo(arr, 0, arr.length - 1, 30); + System.out.println(answer); + int expected = 2; + assertEquals(expected, answer); + } - @Test - //valid Test Case - public void RightHalfDescOrder() { - int[] arr = {50, 40, 30, 20, 10}; - int answer = OrderAgnosticBinarySearch.BinSearchAlgo(arr, 0, arr.length - 1, 10); - System.out.println(answer); - int expected = 4; - assertEquals(expected, answer); - } + @Test + // valid Test Case + public void RightHalfDescOrder() { + int[] arr = {50, 40, 30, 20, 10}; + int answer = OrderAgnosticBinarySearch.BinSearchAlgo(arr, 0, arr.length - 1, 10); + System.out.println(answer); + int expected = 4; + assertEquals(expected, answer); + } - @Test - //valid test case - public void LeftHalfDescOrder() { - int[] arr = {50, 40, 30, 20, 10}; - int answer = OrderAgnosticBinarySearch.BinSearchAlgo(arr, 0, arr.length - 1, 50); - System.out.println(answer); - int expected = 0; - assertEquals(expected, answer); - } + @Test + // valid test case + public void LeftHalfDescOrder() { + int[] arr = {50, 40, 30, 20, 10}; + int answer = OrderAgnosticBinarySearch.BinSearchAlgo(arr, 0, arr.length - 1, 50); + System.out.println(answer); + int expected = 0; + assertEquals(expected, answer); + } - @Test - //valid test case - public void RightHalfAscOrder() { - int[] arr = {10, 20, 30, 40, 50}; - int answer = OrderAgnosticBinarySearch.BinSearchAlgo(arr, 0, arr.length - 1, 50); - System.out.println(answer); - int expected = 4; - assertEquals(expected, answer); - } + @Test + // valid test case + public void RightHalfAscOrder() { + int[] arr = {10, 20, 30, 40, 50}; + int answer = OrderAgnosticBinarySearch.BinSearchAlgo(arr, 0, arr.length - 1, 50); + System.out.println(answer); + int expected = 4; + assertEquals(expected, answer); + } - @Test - //valid test case - public void LeftHalfAscOrder() { - int[] arr = {10, 20, 30, 40, 50}; - int answer = OrderAgnosticBinarySearch.BinSearchAlgo(arr, 0, arr.length - 1, 10); - System.out.println(answer); - int expected = 0; - assertEquals(expected, answer); - } + @Test + // valid test case + public void LeftHalfAscOrder() { + int[] arr = {10, 20, 30, 40, 50}; + int answer = OrderAgnosticBinarySearch.BinSearchAlgo(arr, 0, arr.length - 1, 10); + System.out.println(answer); + int expected = 0; + assertEquals(expected, answer); + } - @Test - //valid test case - public void ElementNotFound() { - int[] arr = {10, 20, 30, 40, 50}; - int answer = OrderAgnosticBinarySearch.BinSearchAlgo(arr, 0, arr.length - 1, 100); - System.out.println(answer); - int expected = -1; - assertEquals(expected, answer); - } - } + @Test + // valid test case + public void ElementNotFound() { + int[] arr = {10, 20, 30, 40, 50}; + int answer = OrderAgnosticBinarySearch.BinSearchAlgo(arr, 0, arr.length - 1, 100); + System.out.println(answer); + int expected = -1; + assertEquals(expected, answer); + } +} diff --git a/src/test/java/com/thealgorithms/searches/QuickSelectTest.java b/src/test/java/com/thealgorithms/searches/QuickSelectTest.java index 720a1250..d788c5d1 100644 --- a/src/test/java/com/thealgorithms/searches/QuickSelectTest.java +++ b/src/test/java/com/thealgorithms/searches/QuickSelectTest.java @@ -180,10 +180,8 @@ class QuickSelectTest { @Test void quickSelectNullList() { - NullPointerException exception = assertThrows( - NullPointerException.class, - () -> QuickSelect.select(null, 0) - ); + NullPointerException exception + = assertThrows(NullPointerException.class, () -> QuickSelect.select(null, 0)); String expectedMsg = "The list of elements must not be null."; assertEquals(expectedMsg, exception.getMessage()); } @@ -191,32 +189,25 @@ class QuickSelectTest { @Test void quickSelectEmptyList() { List objects = Collections.emptyList(); - IllegalArgumentException exception = assertThrows( - IllegalArgumentException.class, - () -> QuickSelect.select(objects, 0) - ); + IllegalArgumentException exception + = assertThrows(IllegalArgumentException.class, () -> QuickSelect.select(objects, 0)); String expectedMsg = "The list of elements must not be empty."; assertEquals(expectedMsg, exception.getMessage()); } @Test void quickSelectIndexOutOfLeftBound() { - IndexOutOfBoundsException exception = assertThrows( - IndexOutOfBoundsException.class, - () -> QuickSelect.select(Collections.singletonList(1), -1) - ); + IndexOutOfBoundsException exception = assertThrows(IndexOutOfBoundsException.class, + () -> QuickSelect.select(Collections.singletonList(1), -1)); String expectedMsg = "The index must not be negative."; assertEquals(expectedMsg, exception.getMessage()); } @Test void quickSelectIndexOutOfRightBound() { - IndexOutOfBoundsException exception = assertThrows( - IndexOutOfBoundsException.class, - () -> QuickSelect.select(Collections.singletonList(1), 1) - ); - String expectedMsg = - "The index must be less than the number of elements."; + IndexOutOfBoundsException exception = assertThrows(IndexOutOfBoundsException.class, + () -> QuickSelect.select(Collections.singletonList(1), 1)); + String expectedMsg = "The index must be less than the number of elements."; assertEquals(expectedMsg, exception.getMessage()); } @@ -230,15 +221,12 @@ class QuickSelectTest { } private static List generateRandomCharacters(int n) { - return RANDOM - .ints(n, ASCII_A, ASCII_Z) + return RANDOM.ints(n, ASCII_A, ASCII_Z) .mapToObj(i -> (char) i) .collect(Collectors.toList()); } - private static > List getSortedCopyOfList( - List list - ) { + private static > List getSortedCopyOfList(List list) { return list.stream().sorted().collect(Collectors.toList()); } } diff --git a/src/test/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearchTest.java b/src/test/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearchTest.java index b15b53c3..e706a58f 100644 --- a/src/test/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearchTest.java +++ b/src/test/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearchTest.java @@ -6,108 +6,108 @@ import org.junit.jupiter.api.Test; public class RowColumnWiseSorted2dArrayBinarySearchTest { - @Test - public void rowColumnSorted2dArrayBinarySearchTestMiddle() { - Integer[][] arr = { - { 10, 20, 30, 40 }, - { 15, 25, 35, 45 }, - { 18, 28, 38, 48 }, - { 21, 31, 41, 51 }, - }; - Integer target = 35; - int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target); - int[] expected = { 1, 2 }; - assertEquals(expected[0], ans[0]); - assertEquals(expected[1], ans[1]); - } + @Test + public void rowColumnSorted2dArrayBinarySearchTestMiddle() { + Integer[][] arr = { + {10, 20, 30, 40}, + {15, 25, 35, 45}, + {18, 28, 38, 48}, + {21, 31, 41, 51}, + }; + Integer target = 35; + int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target); + int[] expected = {1, 2}; + assertEquals(expected[0], ans[0]); + assertEquals(expected[1], ans[1]); + } - @Test - public void rowColumnSorted2dArrayBinarySearchTestSide() { - Integer[][] arr = { - { 10, 20, 30, 40 }, - { 15, 25, 35, 45 }, - { 18, 28, 38, 48 }, - { 21, 31, 41, 51 }, - }; - Integer target = 48; - int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target); - int[] expected = { 2, 3 }; - assertEquals(expected[0], ans[0]); - assertEquals(expected[1], ans[1]); - } + @Test + public void rowColumnSorted2dArrayBinarySearchTestSide() { + Integer[][] arr = { + {10, 20, 30, 40}, + {15, 25, 35, 45}, + {18, 28, 38, 48}, + {21, 31, 41, 51}, + }; + Integer target = 48; + int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target); + int[] expected = {2, 3}; + assertEquals(expected[0], ans[0]); + assertEquals(expected[1], ans[1]); + } - @Test - public void rowColumnSorted2dArray_BinarySearchTestUpper() { - Integer[][] arr = { - { 10, 20, 30, 40 }, - { 15, 25, 35, 45 }, - { 18, 28, 38, 48 }, - { 21, 31, 41, 51 }, - }; - Integer target = 20; - int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target); - int[] expected = { 0, 1 }; - assertEquals(expected[0], ans[0]); - assertEquals(expected[1], ans[1]); - } + @Test + public void rowColumnSorted2dArray_BinarySearchTestUpper() { + Integer[][] arr = { + {10, 20, 30, 40}, + {15, 25, 35, 45}, + {18, 28, 38, 48}, + {21, 31, 41, 51}, + }; + Integer target = 20; + int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target); + int[] expected = {0, 1}; + assertEquals(expected[0], ans[0]); + assertEquals(expected[1], ans[1]); + } - @Test - public void rowColumnSorted2dArray_BinarySearchTestUpperSide() { - Integer[][] arr = { - { 10, 20, 30, 40 }, - { 15, 25, 35, 45 }, - { 18, 28, 38, 48 }, - { 21, 31, 41, 51 }, - }; - Integer target = 40; - int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target); - int[] expected = { 0, 3 }; - assertEquals(expected[0], ans[0]); - assertEquals(expected[1], ans[1]); - } + @Test + public void rowColumnSorted2dArray_BinarySearchTestUpperSide() { + Integer[][] arr = { + {10, 20, 30, 40}, + {15, 25, 35, 45}, + {18, 28, 38, 48}, + {21, 31, 41, 51}, + }; + Integer target = 40; + int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target); + int[] expected = {0, 3}; + assertEquals(expected[0], ans[0]); + assertEquals(expected[1], ans[1]); + } - @Test - public void rowColumnSorted2dArray_BinarySearchTestLower() { - Integer[][] arr = { - { 10, 20, 30, 40 }, - { 15, 25, 35, 45 }, - { 18, 28, 38, 48 }, - { 21, 31, 41, 51 }, - }; - Integer target = 31; - int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target); - int[] expected = { 3, 1 }; - assertEquals(expected[0], ans[0]); - assertEquals(expected[1], ans[1]); - } + @Test + public void rowColumnSorted2dArray_BinarySearchTestLower() { + Integer[][] arr = { + {10, 20, 30, 40}, + {15, 25, 35, 45}, + {18, 28, 38, 48}, + {21, 31, 41, 51}, + }; + Integer target = 31; + int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target); + int[] expected = {3, 1}; + assertEquals(expected[0], ans[0]); + assertEquals(expected[1], ans[1]); + } - @Test - public void rowColumnSorted2dArray_BinarySearchTestLowerSide() { - Integer[][] arr = { - { 10, 20, 30, 40 }, - { 15, 25, 35, 45 }, - { 18, 28, 38, 48 }, - { 21, 31, 41, 51 }, - }; - Integer target = 51; - int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target); - int[] expected = { 3, 3 }; - assertEquals(expected[0], ans[0]); - assertEquals(expected[1], ans[1]); - } + @Test + public void rowColumnSorted2dArray_BinarySearchTestLowerSide() { + Integer[][] arr = { + {10, 20, 30, 40}, + {15, 25, 35, 45}, + {18, 28, 38, 48}, + {21, 31, 41, 51}, + }; + Integer target = 51; + int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target); + int[] expected = {3, 3}; + assertEquals(expected[0], ans[0]); + assertEquals(expected[1], ans[1]); + } - @Test - public void rowColumnSorted2dArray_BinarySearchTestNotFound() { - Integer[][] arr = { - { 10, 20, 30, 40 }, - { 15, 25, 35, 45 }, - { 18, 28, 38, 48 }, - { 21, 31, 41, 51 }, - }; - Integer target = 101; - int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target); - int[] expected = { -1, -1 }; - assertEquals(expected[0], ans[0]); - assertEquals(expected[1], ans[1]); - } + @Test + public void rowColumnSorted2dArray_BinarySearchTestNotFound() { + Integer[][] arr = { + {10, 20, 30, 40}, + {15, 25, 35, 45}, + {18, 28, 38, 48}, + {21, 31, 41, 51}, + }; + Integer target = 101; + int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target); + int[] expected = {-1, -1}; + assertEquals(expected[0], ans[0]); + assertEquals(expected[1], ans[1]); + } } diff --git a/src/test/java/com/thealgorithms/searches/TestSearchInARowAndColWiseSortedMatrix.java b/src/test/java/com/thealgorithms/searches/TestSearchInARowAndColWiseSortedMatrix.java index 0dcc6186..304544d2 100644 --- a/src/test/java/com/thealgorithms/searches/TestSearchInARowAndColWiseSortedMatrix.java +++ b/src/test/java/com/thealgorithms/searches/TestSearchInARowAndColWiseSortedMatrix.java @@ -1,38 +1,29 @@ package com.thealgorithms.searches; import static org.junit.jupiter.api.Assertions.*; + import org.junit.jupiter.api.Test; public class TestSearchInARowAndColWiseSortedMatrix { @Test public void searchItem() { - int[][] matrix = { - { 3, 4, 5, 6, 7 }, - { 8, 9, 10, 11, 12 }, - { 14, 15, 16, 17, 18 }, - { 23, 24, 25, 26, 27 }, - { 30, 31, 32, 33, 34 } - }; + int[][] matrix = {{3, 4, 5, 6, 7}, {8, 9, 10, 11, 12}, {14, 15, 16, 17, 18}, + {23, 24, 25, 26, 27}, {30, 31, 32, 33, 34}}; var test = new SearchInARowAndColWiseSortedMatrix(); int[] res = test.search(matrix, 16); - int[] expectedResult = { 2, 2 }; + int[] expectedResult = {2, 2}; assertArrayEquals(expectedResult, res); } @Test public void notFound() { - int[][] matrix = { - { 3, 4, 5, 6, 7 }, - { 8, 9, 10, 11, 12 }, - { 14, 15, 16, 17, 18 }, - { 23, 24, 25, 26, 27 }, - { 30, 31, 32, 33, 34 } - }; + int[][] matrix = {{3, 4, 5, 6, 7}, {8, 9, 10, 11, 12}, {14, 15, 16, 17, 18}, + {23, 24, 25, 26, 27}, {30, 31, 32, 33, 34}}; var test = new SearchInARowAndColWiseSortedMatrix(); int[] res = test.search(matrix, 96); - int[] expectedResult = { -1, -1 }; + int[] expectedResult = {-1, -1}; assertArrayEquals(expectedResult, res); } } diff --git a/src/test/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearchTest.java b/src/test/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearchTest.java index 804cfc3e..e761eb10 100644 --- a/src/test/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearchTest.java +++ b/src/test/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearchTest.java @@ -4,24 +4,23 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; -public class sortOrderAgnosticBinarySearchTest{ +public class sortOrderAgnosticBinarySearchTest { @Test - public void testAscending(){ - int[] arr = {1,2,3,4,5};// for ascending order. + public void testAscending() { + int[] arr = {1, 2, 3, 4, 5}; // for ascending order. int target = 2; - int ans=sortOrderAgnosticBinarySearch.find(arr, target); + int ans = sortOrderAgnosticBinarySearch.find(arr, target); int excepted = 1; - assertEquals(excepted,ans); + assertEquals(excepted, ans); } @Test - public void testDescending(){ - int[] arr = {5,4,3,2,1};// for descending order. + public void testDescending() { + int[] arr = {5, 4, 3, 2, 1}; // for descending order. int target = 2; - int ans=sortOrderAgnosticBinarySearch.find(arr, target); + int ans = sortOrderAgnosticBinarySearch.find(arr, target); int excepted = 3; - assertEquals(excepted,ans ); + assertEquals(excepted, ans); } - } \ No newline at end of file diff --git a/src/test/java/com/thealgorithms/sorts/BeadSortTest.java b/src/test/java/com/thealgorithms/sorts/BeadSortTest.java index 05f036ed..773eed7a 100644 --- a/src/test/java/com/thealgorithms/sorts/BeadSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/BeadSortTest.java @@ -5,9 +5,9 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import org.junit.jupiter.api.Test; public class BeadSortTest { - //BeadSort can't sort negative number, Character, String. It can sort positive number only + // BeadSort can't sort negative number, Character, String. It can sort positive number only private BeadSort beadSort = new BeadSort(); - + @Test public void beadSortEmptyArray() { int[] inputArray = {}; @@ -18,23 +18,23 @@ public class BeadSortTest { @Test public void beadSortSingleIntegerArray() { - int[] inputArray = { 4 }; + int[] inputArray = {4}; int[] outputArray = beadSort.sort(inputArray); - int[] expectedOutput = { 4 }; + int[] expectedOutput = {4}; assertArrayEquals(outputArray, expectedOutput); } @Test public void bogoSortNonDuplicateIntegerArray() { - int[] inputArray = { 6, 1, 99, 27, 15, 23, 36 }; + int[] inputArray = {6, 1, 99, 27, 15, 23, 36}; int[] outputArray = beadSort.sort(inputArray); int[] expectedOutput = {1, 6, 15, 23, 27, 36, 99}; assertArrayEquals(outputArray, expectedOutput); } - + @Test public void bogoSortDuplicateIntegerArray() { - int[] inputArray = { 6, 1, 27, 15, 23, 27, 36, 23 }; + int[] inputArray = {6, 1, 27, 15, 23, 27, 36, 23}; int[] outputArray = beadSort.sort(inputArray); int[] expectedOutput = {1, 6, 15, 23, 23, 27, 27, 36}; assertArrayEquals(outputArray, expectedOutput); diff --git a/src/test/java/com/thealgorithms/sorts/BinaryInsertionSortTest.java b/src/test/java/com/thealgorithms/sorts/BinaryInsertionSortTest.java index 656b499c..5261d6c6 100644 --- a/src/test/java/com/thealgorithms/sorts/BinaryInsertionSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/BinaryInsertionSortTest.java @@ -11,16 +11,16 @@ class BinaryInsertionSortTest { @Test // valid test case public void BinaryInsertionSortTestNonDuplicate() { - int[] array = { 1, 0, 2, 5, 3, 4, 9, 8, 10, 6, 7 }; - int[] expResult = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + int[] array = {1, 0, 2, 5, 3, 4, 9, 8, 10, 6, 7}; + int[] expResult = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int[] actResult = BIS.binaryInsertSort(array); assertArrayEquals(expResult, actResult); } @Test public void BinaryInsertionSortTestDuplicate() { - int[] array = { 1, 1, 1, 5, 9, 8, 7, 2, 6 }; - int[] expResult = { 1, 1, 1, 2, 5, 6, 7, 8, 9 }; + int[] array = {1, 1, 1, 5, 9, 8, 7, 2, 6}; + int[] expResult = {1, 1, 1, 2, 5, 6, 7, 8, 9}; int[] actResult = BIS.binaryInsertSort(array); assertArrayEquals(expResult, actResult); } diff --git a/src/test/java/com/thealgorithms/sorts/BogoSortTest.java b/src/test/java/com/thealgorithms/sorts/BogoSortTest.java index 24949981..3ebfb7a3 100644 --- a/src/test/java/com/thealgorithms/sorts/BogoSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/BogoSortTest.java @@ -5,9 +5,9 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import org.junit.jupiter.api.Test; public class BogoSortTest { - + private BogoSort bogoSort = new BogoSort(); - + @Test public void bogoSortEmptyArray() { Integer[] inputArray = {}; @@ -18,49 +18,49 @@ public class BogoSortTest { @Test public void bogoSortSingleIntegerArray() { - Integer[] inputArray = { 4 }; + Integer[] inputArray = {4}; Integer[] outputArray = bogoSort.sort(inputArray); - Integer[] expectedOutput = { 4 }; + Integer[] expectedOutput = {4}; assertArrayEquals(outputArray, expectedOutput); } @Test public void bogoSortSingleStringArray() { - String[] inputArray = { "s" }; + String[] inputArray = {"s"}; String[] outputArray = bogoSort.sort(inputArray); - String[] expectedOutput = { "s" }; + String[] expectedOutput = {"s"}; assertArrayEquals(outputArray, expectedOutput); } @Test public void bogoSortNonDuplicateIntegerArray() { - Integer[] inputArray = { 6, -1, 99, 27, -15, 23, -36 }; + Integer[] inputArray = {6, -1, 99, 27, -15, 23, -36}; Integer[] outputArray = bogoSort.sort(inputArray); - Integer[] expectedOutput = { -36, -15, -1, 6, 23, 27, 99}; + Integer[] expectedOutput = {-36, -15, -1, 6, 23, 27, 99}; assertArrayEquals(outputArray, expectedOutput); } - + @Test public void bogoSortDuplicateIntegerArray() { - Integer[] inputArray = { 6, -1, 27, -15, 23, 27, -36, 23 }; + Integer[] inputArray = {6, -1, 27, -15, 23, 27, -36, 23}; Integer[] outputArray = bogoSort.sort(inputArray); - Integer[] expectedOutput = { -36, -15, -1, 6, 23, 23, 27, 27}; + Integer[] expectedOutput = {-36, -15, -1, 6, 23, 23, 27, 27}; assertArrayEquals(outputArray, expectedOutput); } @Test public void bogoSortNonDuplicateStringArray() { - String[] inputArray = { "s", "b", "k", "a", "d", "c", "h" }; + String[] inputArray = {"s", "b", "k", "a", "d", "c", "h"}; String[] outputArray = bogoSort.sort(inputArray); - String[] expectedOutput = {"a", "b", "c", "d", "h", "k", "s" }; + String[] expectedOutput = {"a", "b", "c", "d", "h", "k", "s"}; assertArrayEquals(outputArray, expectedOutput); } @Test public void bogoSortDuplicateStringArray() { - String[] inputArray = { "s", "b", "d", "a", "d", "c", "h", "b" }; + String[] inputArray = {"s", "b", "d", "a", "d", "c", "h", "b"}; String[] outputArray = bogoSort.sort(inputArray); - String[] expectedOutput = {"a", "b", "b", "c", "d", "d", "h", "s" }; + String[] expectedOutput = {"a", "b", "b", "c", "d", "d", "h", "s"}; assertArrayEquals(outputArray, expectedOutput); } } diff --git a/src/test/java/com/thealgorithms/sorts/BubbleSortTest.java b/src/test/java/com/thealgorithms/sorts/BubbleSortTest.java index 1d8cdd31..8690a3f5 100644 --- a/src/test/java/com/thealgorithms/sorts/BubbleSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/BubbleSortTest.java @@ -22,23 +22,23 @@ public class BubbleSortTest { @Test public void bubbleSortSingleIntegerElementArray() { - Integer[] inputArray = { 4 }; + Integer[] inputArray = {4}; Integer[] outputArray = bubbleSort.sort(inputArray); - Integer[] expectedOutput = { 4 }; + Integer[] expectedOutput = {4}; assertArrayEquals(outputArray, expectedOutput); } @Test public void bubbleSortSingleStringElementArray() { - String[] inputArray = { "s" }; + String[] inputArray = {"s"}; String[] outputArray = bubbleSort.sort(inputArray); - String[] expectedOutput = { "s" }; + String[] expectedOutput = {"s"}; assertArrayEquals(outputArray, expectedOutput); } @Test public void bubbleSortIntegerArray() { - Integer[] inputArray = { 4, 23, -6, 78, 1, 54, 23, -6, -231, 9, 12 }; + Integer[] inputArray = {4, 23, -6, 78, 1, 54, 23, -6, -231, 9, 12}; Integer[] outputArray = bubbleSort.sort(inputArray); Integer[] expectedOutput = { -231, diff --git a/src/test/java/com/thealgorithms/sorts/BucketSortTest.java b/src/test/java/com/thealgorithms/sorts/BucketSortTest.java index 1f66be5b..84efde25 100644 --- a/src/test/java/com/thealgorithms/sorts/BucketSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/BucketSortTest.java @@ -8,15 +8,15 @@ public class BucketSortTest { @Test public void bucketSortSingleIntegerArray() { - int[] inputArray = { 4 }; + int[] inputArray = {4}; int[] outputArray = BucketSort.bucketSort(inputArray); - int[] expectedOutput = { 4 }; + int[] expectedOutput = {4}; assertArrayEquals(outputArray, expectedOutput); } @Test public void bucketSortNonDuplicateIntegerArray() { - int[] inputArray = { 6, 1, 99, 27, 15, 23, 36 }; + int[] inputArray = {6, 1, 99, 27, 15, 23, 36}; int[] outputArray = BucketSort.bucketSort(inputArray); int[] expectedOutput = {1, 6, 15, 23, 27, 36, 99}; assertArrayEquals(outputArray, expectedOutput); @@ -24,7 +24,7 @@ public class BucketSortTest { @Test public void bucketSortDuplicateIntegerArray() { - int[] inputArray = { 6, 1, 27, 15, 23, 27, 36, 23 }; + int[] inputArray = {6, 1, 27, 15, 23, 27, 36, 23}; int[] outputArray = BucketSort.bucketSort(inputArray); int[] expectedOutput = {1, 6, 15, 23, 23, 27, 27, 36}; assertArrayEquals(outputArray, expectedOutput); @@ -32,17 +32,17 @@ public class BucketSortTest { @Test public void bucketSortNonDuplicateIntegerArrayWithNegativeNum() { - int[] inputArray = { 6, -1, 99, 27, -15, 23, -36 }; + int[] inputArray = {6, -1, 99, 27, -15, 23, -36}; int[] outputArray = BucketSort.bucketSort(inputArray); - int[] expectedOutput = { -36, -15, -1, 6, 23, 27, 99}; + int[] expectedOutput = {-36, -15, -1, 6, 23, 27, 99}; assertArrayEquals(outputArray, expectedOutput); } @Test public void bucketSortDuplicateIntegerArrayWithNegativeNum() { - int[] inputArray = { 6, -1, 27, -15, 23, 27, -36, 23 }; + int[] inputArray = {6, -1, 27, -15, 23, 27, -36, 23}; int[] outputArray = BucketSort.bucketSort(inputArray); - int[] expectedOutput = { -36, -15, -1, 6, 23, 23, 27, 27}; + int[] expectedOutput = {-36, -15, -1, 6, 23, 23, 27, 27}; assertArrayEquals(outputArray, expectedOutput); } } \ No newline at end of file diff --git a/src/test/java/com/thealgorithms/sorts/CocktailShakerSortTest.java b/src/test/java/com/thealgorithms/sorts/CocktailShakerSortTest.java index 46563d15..56628b78 100644 --- a/src/test/java/com/thealgorithms/sorts/CocktailShakerSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/CocktailShakerSortTest.java @@ -9,11 +9,11 @@ import org.junit.jupiter.api.Test; * @see CocktailShakerSort */ public class CocktailShakerSortTest { - + private CocktailShakerSort cocktailShakerSort = new CocktailShakerSort(); @Test - public void cocktailShakerSortEmptyArray(){ + public void cocktailShakerSortEmptyArray() { Integer[] inputArray = {}; Integer[] outputArray = cocktailShakerSort.sort(inputArray); Integer[] expectedOutput = {}; @@ -21,7 +21,7 @@ public class CocktailShakerSortTest { } @Test - public void cocktailShakerSortSingleStringElementArray(){ + public void cocktailShakerSortSingleStringElementArray() { String[] inputArray = {"Test"}; String[] outputArray = cocktailShakerSort.sort(inputArray); String[] expectedOutput = {"Test"}; @@ -29,15 +29,15 @@ public class CocktailShakerSortTest { } @Test - public void cocktailShakerSortIntegerArray(){ - Integer[] inputArray = { 2, 92, 1, 33, -33, 27, 5, 100, 78, 99, -100}; + public void cocktailShakerSortIntegerArray() { + Integer[] inputArray = {2, 92, 1, 33, -33, 27, 5, 100, 78, 99, -100}; Integer[] outputArray = cocktailShakerSort.sort(inputArray); - Integer[] expectedOutput = { -100, -33, 1, 2, 5, 27, 33, 78, 92, 99, 100}; + Integer[] expectedOutput = {-100, -33, 1, 2, 5, 27, 33, 78, 92, 99, 100}; assertArrayEquals(outputArray, expectedOutput); } @Test - public void cocktailShakerSortStringArray(){ + public void cocktailShakerSortStringArray() { String[] inputArray = { "g3x1", "dN62", diff --git a/src/test/java/com/thealgorithms/sorts/CombSortTest.java b/src/test/java/com/thealgorithms/sorts/CombSortTest.java index a6eb40c6..1b2ca145 100644 --- a/src/test/java/com/thealgorithms/sorts/CombSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/CombSortTest.java @@ -12,7 +12,7 @@ import org.junit.jupiter.api.Test; public class CombSortTest { private CombSort combSort = new CombSort(); - + @Test public void combSortEmptyArray() { Integer[] inputArray = {}; @@ -28,61 +28,41 @@ public class CombSortTest { String[] expectedArray = {"Test"}; assertArrayEquals(outputArray, expectedArray); } - + @Test public void combSortStringArray() { - String[] inputArray = { - "4gp8", - "aBJ2", - "85cW", - "Pmk9", - "ewZO", - "meuU", - "RhNd", - "5TKB", - "eDd5", - "zzyo" - }; + String[] inputArray + = {"4gp8", "aBJ2", "85cW", "Pmk9", "ewZO", "meuU", "RhNd", "5TKB", "eDd5", "zzyo"}; String[] outputArray = combSort.sort(inputArray); - String[] expectedArray = { - "4gp8", - "5TKB", - "85cW", - "Pmk9", - "RhNd", - "aBJ2", - "eDd5", - "ewZO", - "meuU", - "zzyo" - }; + String[] expectedArray + = {"4gp8", "5TKB", "85cW", "Pmk9", "RhNd", "aBJ2", "eDd5", "ewZO", "meuU", "zzyo"}; assertArrayEquals(outputArray, expectedArray); } - @Test + @Test public void combSortIntegerArray() { - Integer[] inputArray = { 36, 98, -51, -23, 66, -58, 31, 25, -30, 40 }; + Integer[] inputArray = {36, 98, -51, -23, 66, -58, 31, 25, -30, 40}; Integer[] outputArray = combSort.sort(inputArray); - Integer[] expectedArray = { -58, -51, -30, -23, 25, 31, 36, 40, 66, 98 }; + Integer[] expectedArray = {-58, -51, -30, -23, 25, 31, 36, 40, 66, 98}; assertArrayEquals(outputArray, expectedArray); } @Test public void combSortDoubleArray() { - Double[] inputArray = { - 0.8335545399, 0.9346214114, - 0.3096396752, 0.6433840668, - 0.3973191975, 0.6118850724, - 0.0553975453, 0.1961108601, - 0.6172800885, 0.1065247772 - }; + Double[] inputArray = {0.8335545399, 0.9346214114, 0.3096396752, 0.6433840668, 0.3973191975, + 0.6118850724, 0.0553975453, 0.1961108601, 0.6172800885, 0.1065247772}; Double[] outputArray = combSort.sort(inputArray); Double[] expectedArray = { - 0.0553975453, 0.1065247772, - 0.1961108601, 0.3096396752, - 0.3973191975, 0.6118850724, - 0.6172800885, 0.6433840668, - 0.8335545399, 0.9346214114, + 0.0553975453, + 0.1065247772, + 0.1961108601, + 0.3096396752, + 0.3973191975, + 0.6118850724, + 0.6172800885, + 0.6433840668, + 0.8335545399, + 0.9346214114, }; assertArrayEquals(outputArray, expectedArray); } diff --git a/src/test/java/com/thealgorithms/sorts/DualPivotQuickSortTest.java b/src/test/java/com/thealgorithms/sorts/DualPivotQuickSortTest.java index 04a612ae..1edfb5fa 100644 --- a/src/test/java/com/thealgorithms/sorts/DualPivotQuickSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/DualPivotQuickSortTest.java @@ -22,42 +22,41 @@ class DualPivotQuickSortTest { @Test void quickSortSingleValueArrayShouldPass() { - Integer[] array = { 7 }; + Integer[] array = {7}; Integer[] sorted = dualPivotquickSort.sort(array); - Integer[] expected = { 7 }; + Integer[] expected = {7}; assertArrayEquals(expected, sorted); } @Test void quickSortWithIntegerArrayShouldPass() { - Integer[] array = { 49, 4, 36, 9, 144, 1 }; + Integer[] array = {49, 4, 36, 9, 144, 1}; Integer[] sorted = dualPivotquickSort.sort(array); - Integer[] expected = { 1, 4, 9, 36, 49, 144 }; + Integer[] expected = {1, 4, 9, 36, 49, 144}; assertArrayEquals(expected, sorted); } @Test void quickSortForArrayWithNegativeValuesShouldPass() { - Integer[] array = { 49, -36, -124, -49, 12, 9 }; + Integer[] array = {49, -36, -124, -49, 12, 9}; Integer[] sorted = dualPivotquickSort.sort(array); - Integer[] expected = { -124, -49, -36, 9, 12, 49 }; + Integer[] expected = {-124, -49, -36, 9, 12, 49}; assertArrayEquals(expected, sorted); } @Test void quickSortForArrayWithDuplicateValuesShouldPass() { - Integer[] array = { 36, 1, 49, 1, 4, 9 }; + Integer[] array = {36, 1, 49, 1, 4, 9}; Integer[] sorted = dualPivotquickSort.sort(array); - Integer[] expected = { 1, 1, 4, 9, 36, 49 }; + Integer[] expected = {1, 1, 4, 9, 36, 49}; assertArrayEquals(expected, sorted); } @Test void quickSortWithStringArrayShouldPass() { - String[] array = { "cat", "ant", "eat", "boss", "dog", "apple" }; + String[] array = {"cat", "ant", "eat", "boss", "dog", "apple"}; String[] sorted = dualPivotquickSort.sort(array); - String[] expected = { "ant", "apple", "boss", "cat", "dog", "eat" }; + String[] expected = {"ant", "apple", "boss", "cat", "dog", "eat"}; assertArrayEquals(expected, sorted); } - } \ No newline at end of file diff --git a/src/test/java/com/thealgorithms/sorts/DutchNationalFlagSortTest.java b/src/test/java/com/thealgorithms/sorts/DutchNationalFlagSortTest.java index 0048c843..7c81aefc 100644 --- a/src/test/java/com/thealgorithms/sorts/DutchNationalFlagSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/DutchNationalFlagSortTest.java @@ -12,8 +12,8 @@ public class DutchNationalFlagSortTest { Partitions on the result array: [ smaller than 1 , equal 1, greater than 1] */ void DNFSTestOdd() { - Integer[] integers = { 1, 3, 1, 4, 0 }; - Integer[] integersResult = { 0, 1, 1, 4, 3 }; + Integer[] integers = {1, 3, 1, 4, 0}; + Integer[] integersResult = {0, 1, 1, 4, 3}; DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort(); dutchNationalFlagSort.sort(integers); assertArrayEquals(integers, integersResult); @@ -25,8 +25,8 @@ public class DutchNationalFlagSortTest { Partitions on the result array: [ smaller than 3 , equal 3, greater than 3] */ void DNFSTestEven() { - Integer[] integers = { 8, 1, 3, 1, 4, 0 }; - Integer[] integersResult = { 0, 1, 1, 3, 4, 8 }; + Integer[] integers = {8, 1, 3, 1, 4, 0}; + Integer[] integersResult = {0, 1, 1, 3, 4, 8}; DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort(); dutchNationalFlagSort.sort(integers); assertArrayEquals(integers, integersResult); @@ -38,8 +38,8 @@ public class DutchNationalFlagSortTest { Partitions on the result array: [ smaller than b , equal b, greater than b] */ void DNFSTestEvenStrings() { - String[] strings = { "a", "d", "b", "s", "e", "e" }; - String[] stringsResult = { "a", "b", "s", "e", "e", "d" }; + String[] strings = {"a", "d", "b", "s", "e", "e"}; + String[] stringsResult = {"a", "b", "s", "e", "e", "d"}; DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort(); dutchNationalFlagSort.sort(strings); assertArrayEquals(strings, stringsResult); @@ -51,8 +51,8 @@ public class DutchNationalFlagSortTest { Partitions on the result array: [ smaller than b , equal b, greater than b] */ void DNFSTestOddStrings() { - String[] strings = { "a", "d", "b", "s", "e" }; - String[] stringsResult = { "a", "b", "s", "e", "d" }; + String[] strings = {"a", "d", "b", "s", "e"}; + String[] stringsResult = {"a", "b", "s", "e", "d"}; DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort(); dutchNationalFlagSort.sort(strings); assertArrayEquals(strings, stringsResult); @@ -64,8 +64,8 @@ public class DutchNationalFlagSortTest { Partitions on the result array: [ smaller than 0 , equal 0, greater than 0] */ void DNFSTestOddMidGiven() { - Integer[] integers = { 1, 3, 1, 4, 0 }; - Integer[] integersResult = { 0, 1, 4, 3, 1 }; + Integer[] integers = {1, 3, 1, 4, 0}; + Integer[] integersResult = {0, 1, 4, 3, 1}; DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort(); dutchNationalFlagSort.sort(integers, 0); assertArrayEquals(integers, integersResult); @@ -77,8 +77,8 @@ public class DutchNationalFlagSortTest { Partitions on the result array: [ smaller than 4 , equal 4, greater than 4] */ void DNFSTestEvenMidGiven() { - Integer[] integers = { 8, 1, 3, 1, 4, 0 }; - Integer[] integersResult = { 0, 1, 3, 1, 4, 8 }; + Integer[] integers = {8, 1, 3, 1, 4, 0}; + Integer[] integersResult = {0, 1, 3, 1, 4, 8}; DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort(); dutchNationalFlagSort.sort(integers, 4); assertArrayEquals(integers, integersResult); @@ -90,8 +90,8 @@ public class DutchNationalFlagSortTest { Partitions on the result array: [ smaller than s , equal s, greater than s] */ void DNFSTestEvenStringsMidGiven() { - String[] strings = { "a", "d", "b", "s", "e", "e" }; - String[] stringsResult = { "a", "d", "b", "e", "e", "s" }; + String[] strings = {"a", "d", "b", "s", "e", "e"}; + String[] stringsResult = {"a", "d", "b", "e", "e", "s"}; DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort(); dutchNationalFlagSort.sort(strings, "s"); assertArrayEquals(strings, stringsResult); @@ -103,8 +103,8 @@ public class DutchNationalFlagSortTest { Partitions on the result array: [ smaller than e , equal e, greater than e] */ void DNFSTestOddStringsMidGiven() { - String[] strings = { "a", "d", "b", "s", "e" }; - String[] stringsResult = { "a", "d", "b", "e", "s" }; + String[] strings = {"a", "d", "b", "s", "e"}; + String[] stringsResult = {"a", "d", "b", "e", "s"}; DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort(); dutchNationalFlagSort.sort(strings, "e"); assertArrayEquals(strings, stringsResult); diff --git a/src/test/java/com/thealgorithms/sorts/InsertionSortTest.java b/src/test/java/com/thealgorithms/sorts/InsertionSortTest.java index 2202872f..87a2c733 100644 --- a/src/test/java/com/thealgorithms/sorts/InsertionSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/InsertionSortTest.java @@ -1,11 +1,10 @@ package com.thealgorithms.sorts; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; import java.util.function.Function; - -import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; class InsertionSortTest { private InsertionSort insertionSort; diff --git a/src/test/java/com/thealgorithms/sorts/IntrospectiveSortTest.java b/src/test/java/com/thealgorithms/sorts/IntrospectiveSortTest.java index caaf3f4b..91f9aeb4 100644 --- a/src/test/java/com/thealgorithms/sorts/IntrospectiveSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/IntrospectiveSortTest.java @@ -1,10 +1,10 @@ package com.thealgorithms.sorts; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import org.junit.jupiter.api.Test; + public class IntrospectiveSortTest { @Test // valid test case @@ -34,9 +34,8 @@ public class IntrospectiveSortTest { // valid test case public void StrandSortNullTest() { Integer[] expectedArray = null; - assertThrows(NullPointerException.class, () -> { - new IntrospectiveSort().sort(expectedArray); - }); + assertThrows( + NullPointerException.class, () -> { new IntrospectiveSort().sort(expectedArray); }); } @Test diff --git a/src/test/java/com/thealgorithms/sorts/MergeSortRecursiveTest.java b/src/test/java/com/thealgorithms/sorts/MergeSortRecursiveTest.java index 8bc7c0b2..745e1139 100644 --- a/src/test/java/com/thealgorithms/sorts/MergeSortRecursiveTest.java +++ b/src/test/java/com/thealgorithms/sorts/MergeSortRecursiveTest.java @@ -5,31 +5,31 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import java.util.Arrays; import java.util.List; - import org.junit.jupiter.api.Test; public class MergeSortRecursiveTest { - -// private MergeSortRecursive mergeSortRecursive = new MergeSortRecursive(); - - @Test - void testMergeSortRecursiveCase1 () { - MergeSortRecursive mergeSortRecursive = new MergeSortRecursive(Arrays.asList(5, 12, 9, 3, 15, 88)); - - List expected = Arrays.asList(3, 5, 9, 12, 15, 88); - List sorted = mergeSortRecursive.mergeSort(); - - assertEquals(expected, sorted); - } - - @Test - void testMergeSortRecursiveCase2 () { - MergeSortRecursive mergeSortRecursive = new MergeSortRecursive(Arrays.asList(-3, 5, 3, 4, 3, 7, 40, -20, 30, 0)); - - List expected = Arrays.asList(-20, -3, 0, 3, 3, 4, 5, 7, 30, 40); - List sorted = mergeSortRecursive.mergeSort(); - - assertEquals(expected, sorted); - } + // private MergeSortRecursive mergeSortRecursive = new MergeSortRecursive(); + + @Test + void testMergeSortRecursiveCase1() { + MergeSortRecursive mergeSortRecursive + = new MergeSortRecursive(Arrays.asList(5, 12, 9, 3, 15, 88)); + + List expected = Arrays.asList(3, 5, 9, 12, 15, 88); + List sorted = mergeSortRecursive.mergeSort(); + + assertEquals(expected, sorted); + } + + @Test + void testMergeSortRecursiveCase2() { + MergeSortRecursive mergeSortRecursive + = new MergeSortRecursive(Arrays.asList(-3, 5, 3, 4, 3, 7, 40, -20, 30, 0)); + + List expected = Arrays.asList(-20, -3, 0, 3, 3, 4, 5, 7, 30, 40); + List sorted = mergeSortRecursive.mergeSort(); + + assertEquals(expected, sorted); + } } diff --git a/src/test/java/com/thealgorithms/sorts/OddEvenSortTest.java b/src/test/java/com/thealgorithms/sorts/OddEvenSortTest.java index 8c031871..e6d86325 100644 --- a/src/test/java/com/thealgorithms/sorts/OddEvenSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/OddEvenSortTest.java @@ -13,7 +13,7 @@ public class OddEvenSortTest { private OddEvenSort oddEvenSort = new OddEvenSort(); @Test - public void oddEvenSortEmptyArray(){ + public void oddEvenSortEmptyArray() { int[] inputArray = {}; oddEvenSort.oddEvenSort(inputArray); int[] expectedOutput = {}; @@ -21,7 +21,7 @@ public class OddEvenSortTest { } @Test - public void oddEvenSortNaturalNumberArray(){ + public void oddEvenSortNaturalNumberArray() { int[] inputArray = {18, 91, 86, 60, 21, 44, 37, 78, 98, 67}; oddEvenSort.oddEvenSort(inputArray); int[] expectedOutput = {18, 21, 37, 44, 60, 67, 78, 86, 91, 98}; @@ -29,11 +29,10 @@ public class OddEvenSortTest { } @Test - public void oddEvenSortIntegerArray(){ + public void oddEvenSortIntegerArray() { int[] inputArray = {57, 69, -45, 12, -85, 3, -76, 36, 67, -14}; oddEvenSort.oddEvenSort(inputArray); int[] expectedOutput = {-85, -76, -45, -14, 3, 12, 36, 57, 67, 69}; assertArrayEquals(inputArray, expectedOutput); } - } diff --git a/src/test/java/com/thealgorithms/sorts/SelectionSortTest.java b/src/test/java/com/thealgorithms/sorts/SelectionSortTest.java index ebe153e6..36470f86 100644 --- a/src/test/java/com/thealgorithms/sorts/SelectionSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/SelectionSortTest.java @@ -9,25 +9,19 @@ class SelectionSortTest { @Test // valid test case void IntegerArrTest() { - Integer[] arr = { 4, 23, 6, 78, 1, 54, 231, 9, 12 }; + Integer[] arr = {4, 23, 6, 78, 1, 54, 231, 9, 12}; SelectionSort selectionSort = new SelectionSort(); - assertArrayEquals( - new Integer[] { 1, 4, 6, 9, 12, 23, 54, 78, 231 }, - selectionSort.sort(arr) - ); + assertArrayEquals(new Integer[] {1, 4, 6, 9, 12, 23, 54, 78, 231}, selectionSort.sort(arr)); } @Test // valid test case void StringArrTest() { - String[] arr = { "c", "a", "e", "b", "d" }; + String[] arr = {"c", "a", "e", "b", "d"}; SelectionSort selectionSort = new SelectionSort(); - assertArrayEquals( - new String[] { "a", "b", "c", "d", "e" }, - selectionSort.sort(arr) - ); + assertArrayEquals(new String[] {"a", "b", "c", "d", "e"}, selectionSort.sort(arr)); } @Test diff --git a/src/test/java/com/thealgorithms/sorts/ShellSortTest.java b/src/test/java/com/thealgorithms/sorts/ShellSortTest.java index 60c6292f..cecc8d8b 100644 --- a/src/test/java/com/thealgorithms/sorts/ShellSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/ShellSortTest.java @@ -5,9 +5,9 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import org.junit.jupiter.api.Test; public class ShellSortTest { - + private ShellSort shellSort = new ShellSort(); - + @Test public void ShellSortEmptyArray() { Integer[] inputArray = {}; @@ -18,50 +18,49 @@ public class ShellSortTest { @Test public void ShellSortSingleIntegerArray() { - Integer[] inputArray = { 4 }; + Integer[] inputArray = {4}; Integer[] outputArray = shellSort.sort(inputArray); - Integer[] expectedOutput = { 4 }; + Integer[] expectedOutput = {4}; assertArrayEquals(outputArray, expectedOutput); } @Test public void ShellSortSingleStringArray() { - String[] inputArray = { "s" }; + String[] inputArray = {"s"}; String[] outputArray = shellSort.sort(inputArray); - String[] expectedOutput = { "s" }; + String[] expectedOutput = {"s"}; assertArrayEquals(outputArray, expectedOutput); } @Test public void ShellSortNonDuplicateIntegerArray() { - Integer[] inputArray = { 6, -1, 99, 27, -15, 23, -36 }; + Integer[] inputArray = {6, -1, 99, 27, -15, 23, -36}; Integer[] outputArray = shellSort.sort(inputArray); - Integer[] expectedOutput = { -36, -15, -1, 6, 23, 27, 99}; + Integer[] expectedOutput = {-36, -15, -1, 6, 23, 27, 99}; assertArrayEquals(outputArray, expectedOutput); } - + @Test public void ShellSortDuplicateIntegerArray() { - Integer[] inputArray = { 6, -1, 27, -15, 23, 27, -36, 23 }; + Integer[] inputArray = {6, -1, 27, -15, 23, 27, -36, 23}; Integer[] outputArray = shellSort.sort(inputArray); - Integer[] expectedOutput = { -36, -15, -1, 6, 23, 23, 27, 27}; + Integer[] expectedOutput = {-36, -15, -1, 6, 23, 23, 27, 27}; assertArrayEquals(outputArray, expectedOutput); } @Test public void ShellSortNonDuplicateStringArray() { - String[] inputArray = { "s", "b", "k", "a", "d", "c", "h" }; + String[] inputArray = {"s", "b", "k", "a", "d", "c", "h"}; String[] outputArray = shellSort.sort(inputArray); - String[] expectedOutput = {"a", "b", "c", "d", "h", "k", "s" }; + String[] expectedOutput = {"a", "b", "c", "d", "h", "k", "s"}; assertArrayEquals(outputArray, expectedOutput); } @Test public void ShellSortDuplicateStringArray() { - String[] inputArray = { "s", "b", "d", "a", "d", "c", "h", "b" }; + String[] inputArray = {"s", "b", "d", "a", "d", "c", "h", "b"}; String[] outputArray = shellSort.sort(inputArray); - String[] expectedOutput = {"a", "b", "b", "c", "d", "d", "h", "s" }; + String[] expectedOutput = {"a", "b", "b", "c", "d", "d", "h", "s"}; assertArrayEquals(outputArray, expectedOutput); } - } diff --git a/src/test/java/com/thealgorithms/sorts/SimpleSortTest.java b/src/test/java/com/thealgorithms/sorts/SimpleSortTest.java index a4654247..e476b97b 100644 --- a/src/test/java/com/thealgorithms/sorts/SimpleSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/SimpleSortTest.java @@ -5,9 +5,9 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import org.junit.jupiter.api.Test; public class SimpleSortTest { - + private SimpleSort simpleSort = new SimpleSort(); - + @Test public void simpleSortEmptyArray() { Integer[] inputArray = {}; @@ -18,49 +18,49 @@ public class SimpleSortTest { @Test public void simpleSortSingleIntegerArray() { - Integer[] inputArray = { 4 }; + Integer[] inputArray = {4}; Integer[] outputArray = simpleSort.sort(inputArray); - Integer[] expectedOutput = { 4 }; + Integer[] expectedOutput = {4}; assertArrayEquals(outputArray, expectedOutput); } @Test public void simpleSortSingleStringArray() { - String[] inputArray = { "s" }; + String[] inputArray = {"s"}; String[] outputArray = simpleSort.sort(inputArray); - String[] expectedOutput = { "s" }; + String[] expectedOutput = {"s"}; assertArrayEquals(outputArray, expectedOutput); } @Test public void simpleSortNonDuplicateIntegerArray() { - Integer[] inputArray = { 6, -1, 99, 27, -15, 23, -36 }; + Integer[] inputArray = {6, -1, 99, 27, -15, 23, -36}; Integer[] outputArray = simpleSort.sort(inputArray); - Integer[] expectedOutput = { -36, -15, -1, 6, 23, 27, 99}; + Integer[] expectedOutput = {-36, -15, -1, 6, 23, 27, 99}; assertArrayEquals(outputArray, expectedOutput); } - + @Test public void simpleSortDuplicateIntegerArray() { - Integer[] inputArray = { 6, -1, 27, -15, 23, 27, -36, 23 }; + Integer[] inputArray = {6, -1, 27, -15, 23, 27, -36, 23}; Integer[] outputArray = simpleSort.sort(inputArray); - Integer[] expectedOutput = { -36, -15, -1, 6, 23, 23, 27, 27}; + Integer[] expectedOutput = {-36, -15, -1, 6, 23, 23, 27, 27}; assertArrayEquals(outputArray, expectedOutput); } @Test public void simpleSortNonDuplicateStringArray() { - String[] inputArray = { "s", "b", "k", "a", "d", "c", "h" }; + String[] inputArray = {"s", "b", "k", "a", "d", "c", "h"}; String[] outputArray = simpleSort.sort(inputArray); - String[] expectedOutput = {"a", "b", "c", "d", "h", "k", "s" }; + String[] expectedOutput = {"a", "b", "c", "d", "h", "k", "s"}; assertArrayEquals(outputArray, expectedOutput); } @Test public void simpleSortDuplicateStringArray() { - String[] inputArray = { "s", "b", "d", "a", "d", "c", "h", "b" }; + String[] inputArray = {"s", "b", "d", "a", "d", "c", "h", "b"}; String[] outputArray = simpleSort.sort(inputArray); - String[] expectedOutput = {"a", "b", "b", "c", "d", "d", "h", "s" }; + String[] expectedOutput = {"a", "b", "b", "c", "d", "d", "h", "s"}; assertArrayEquals(outputArray, expectedOutput); } } diff --git a/src/test/java/com/thealgorithms/sorts/SlowSortTest.java b/src/test/java/com/thealgorithms/sorts/SlowSortTest.java index d4d9eaa1..5d5d1556 100644 --- a/src/test/java/com/thealgorithms/sorts/SlowSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/SlowSortTest.java @@ -71,9 +71,11 @@ public class SlowSortTest { @Test public void slowSortStringSymbolArray() { - String[] inputArray = {"cbf", "auk", "ó", "(b", "a", ")", "au", "á", "cba", "auk", "(a", "bhy", "cba"}; + String[] inputArray + = {"cbf", "auk", "ó", "(b", "a", ")", "au", "á", "cba", "auk", "(a", "bhy", "cba"}; String[] outputArray = slowSort.sort(inputArray); - String[] expectedOutput = {"(a", "(b", ")", "a", "au", "auk", "auk", "bhy", "cba", "cba", "cbf", "á", "ó"}; + String[] expectedOutput + = {"(a", "(b", ")", "a", "au", "auk", "auk", "bhy", "cba", "cba", "cbf", "á", "ó"}; assertArrayEquals(outputArray, expectedOutput); } } diff --git a/src/test/java/com/thealgorithms/sorts/SortUtilsRandomGeneratorTest.java b/src/test/java/com/thealgorithms/sorts/SortUtilsRandomGeneratorTest.java index 30fd22c2..16571b3b 100644 --- a/src/test/java/com/thealgorithms/sorts/SortUtilsRandomGeneratorTest.java +++ b/src/test/java/com/thealgorithms/sorts/SortUtilsRandomGeneratorTest.java @@ -1,10 +1,10 @@ package com.thealgorithms.sorts; +import static org.assertj.core.api.Assertions.assertThat; + import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.Test; -import static org.assertj.core.api.Assertions.assertThat; - class SortUtilsRandomGeneratorTest { @RepeatedTest(1000) diff --git a/src/test/java/com/thealgorithms/sorts/SortUtilsTest.java b/src/test/java/com/thealgorithms/sorts/SortUtilsTest.java index 249c251d..34a6b00d 100644 --- a/src/test/java/com/thealgorithms/sorts/SortUtilsTest.java +++ b/src/test/java/com/thealgorithms/sorts/SortUtilsTest.java @@ -1,10 +1,9 @@ package com.thealgorithms.sorts; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; import java.util.List; - -import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; class SortUtilsTest { diff --git a/src/test/java/com/thealgorithms/sorts/SortingAlgorithmTest.java b/src/test/java/com/thealgorithms/sorts/SortingAlgorithmTest.java index d7230f6d..ac11b8ad 100644 --- a/src/test/java/com/thealgorithms/sorts/SortingAlgorithmTest.java +++ b/src/test/java/com/thealgorithms/sorts/SortingAlgorithmTest.java @@ -1,21 +1,20 @@ package com.thealgorithms.sorts; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; - -import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public abstract class SortingAlgorithmTest { abstract SortAlgorithm getSortAlgorithm(); @Test void shouldAcceptWhenEmptyArrayIsPassed() { - Integer[] array = new Integer[]{}; - Integer[] expected = new Integer[]{}; + Integer[] array = new Integer[] {}; + Integer[] expected = new Integer[] {}; Integer[] sorted = getSortAlgorithm().sort(array); @@ -34,8 +33,8 @@ public abstract class SortingAlgorithmTest { @Test void shouldAcceptWhenSingleValuedArrayIsPassed() { - Integer[] array = new Integer[]{2}; - Integer[] expected = new Integer[]{2}; + Integer[] array = new Integer[] {2}; + Integer[] expected = new Integer[] {2}; Integer[] sorted = getSortAlgorithm().sort(array); @@ -54,8 +53,8 @@ public abstract class SortingAlgorithmTest { @Test void shouldAcceptWhenListWithAllPositiveValuesIsPassed() { - Integer[] array = new Integer[]{60, 7, 55, 9, 999, 3}; - Integer[] expected = new Integer[]{3, 7, 9, 55, 60, 999}; + Integer[] array = new Integer[] {60, 7, 55, 9, 999, 3}; + Integer[] expected = new Integer[] {3, 7, 9, 55, 60, 999}; Integer[] sorted = getSortAlgorithm().sort(array); @@ -74,8 +73,8 @@ public abstract class SortingAlgorithmTest { @Test void shouldAcceptWhenArrayWithAllNegativeValuesIsPassed() { - Integer[] array = new Integer[]{-60, -7, -55, -9, -999, -3}; - Integer[] expected = new Integer[]{-999, -60, -55, -9, -7, -3}; + Integer[] array = new Integer[] {-60, -7, -55, -9, -999, -3}; + Integer[] expected = new Integer[] {-999, -60, -55, -9, -7, -3}; Integer[] sorted = getSortAlgorithm().sort(array); @@ -94,8 +93,8 @@ public abstract class SortingAlgorithmTest { @Test void shouldAcceptWhenArrayWithRealNumberValuesIsPassed() { - Integer[] array = new Integer[]{60, -7, 55, 9, -999, -3}; - Integer[] expected = new Integer[]{-999, -7, -3, 9, 55, 60}; + Integer[] array = new Integer[] {60, -7, 55, 9, -999, -3}; + Integer[] expected = new Integer[] {-999, -7, -3, 9, 55, 60}; Integer[] sorted = getSortAlgorithm().sort(array); @@ -114,8 +113,8 @@ public abstract class SortingAlgorithmTest { @Test void shouldAcceptWhenArrayWithDuplicateValueIsPassed() { - Integer[] array = new Integer[]{60, 7, 55, 55, 999, 3}; - Integer[] expected = new Integer[]{3, 7, 55, 55, 60, 999}; + Integer[] array = new Integer[] {60, 7, 55, 55, 999, 3}; + Integer[] expected = new Integer[] {3, 7, 55, 55, 60, 999}; Integer[] sorted = getSortAlgorithm().sort(array); diff --git a/src/test/java/com/thealgorithms/sorts/StrandSortTest.java b/src/test/java/com/thealgorithms/sorts/StrandSortTest.java index 9e46c9cc..aa9e203c 100644 --- a/src/test/java/com/thealgorithms/sorts/StrandSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/StrandSortTest.java @@ -11,10 +11,9 @@ class StrandSortTest { @Test // valid test case public void StrandSortNonDuplicateTest() { - int[] expectedArray = { 1, 2, 3, 4, 5 }; - LinkedList actualList = StrandSort.strandSort( - new LinkedList(Arrays.asList(3, 1, 2, 4, 5)) - ); + int[] expectedArray = {1, 2, 3, 4, 5}; + LinkedList actualList + = StrandSort.strandSort(new LinkedList(Arrays.asList(3, 1, 2, 4, 5))); int[] actualArray = new int[actualList.size()]; for (int i = 0; i < actualList.size(); i++) { actualArray[i] = actualList.get(i); @@ -25,10 +24,9 @@ class StrandSortTest { @Test // valid test case public void StrandSortDuplicateTest() { - int[] expectedArray = { 2, 2, 2, 5, 7 }; - LinkedList actualList = StrandSort.strandSort( - new LinkedList(Arrays.asList(7, 2, 2, 2, 5)) - ); + int[] expectedArray = {2, 2, 2, 5, 7}; + LinkedList actualList + = StrandSort.strandSort(new LinkedList(Arrays.asList(7, 2, 2, 2, 5))); int[] actualArray = new int[actualList.size()]; for (int i = 0; i < actualList.size(); i++) { actualArray[i] = actualList.get(i); diff --git a/src/test/java/com/thealgorithms/sorts/TimSortTest.java b/src/test/java/com/thealgorithms/sorts/TimSortTest.java index 85df96f5..564afe37 100644 --- a/src/test/java/com/thealgorithms/sorts/TimSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/TimSortTest.java @@ -1,10 +1,10 @@ package com.thealgorithms.sorts; +import static org.junit.jupiter.api.Assertions.*; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; - class TimSortTest extends SortingAlgorithmTest { @Override SortAlgorithm getSortAlgorithm() { diff --git a/src/test/java/com/thealgorithms/sorts/TopologicalSortTest.java b/src/test/java/com/thealgorithms/sorts/TopologicalSortTest.java index fe678c00..6ee84b7b 100644 --- a/src/test/java/com/thealgorithms/sorts/TopologicalSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/TopologicalSortTest.java @@ -53,13 +53,10 @@ class TopologicalSortTest { graph.addEdge("6", "2"); graph.addEdge("7", ""); graph.addEdge("8", ""); - Exception exception = assertThrows( - BackEdgeException.class, - () -> TopologicalSort.sort(graph) - ); - String expected = - "This graph contains a cycle. No linear ordering is possible. " + - "Back edge: 6 -> 2"; + Exception exception + = assertThrows(BackEdgeException.class, () -> TopologicalSort.sort(graph)); + String expected = "This graph contains a cycle. No linear ordering is possible. " + + "Back edge: 6 -> 2"; assertEquals(exception.getMessage(), expected); } } diff --git a/src/test/java/com/thealgorithms/sorts/TreeSortTest.java b/src/test/java/com/thealgorithms/sorts/TreeSortTest.java index 5c99c2d6..39ec5aad 100644 --- a/src/test/java/com/thealgorithms/sorts/TreeSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/TreeSortTest.java @@ -12,8 +12,8 @@ import org.junit.jupiter.api.Test; public class TreeSortTest { private TreeSort treeSort = new TreeSort(); - @Test - public void treeSortEmptyArray(){ + @Test + public void treeSortEmptyArray() { Integer[] inputArray = {}; Integer[] outputArray = treeSort.sort(inputArray); Integer[] expectedOutput = {}; @@ -30,59 +30,29 @@ public class TreeSortTest { @Test public void treeSortStringArray() { - String[] inputArray = { - "F6w9", - "l1qz", - "dIxH", - "larj", - "kRzy", - "vnNH", - "3ftM", - "hc4n", - "C5Qi", - "btGF" - }; + String[] inputArray + = {"F6w9", "l1qz", "dIxH", "larj", "kRzy", "vnNH", "3ftM", "hc4n", "C5Qi", "btGF"}; String[] outputArray = treeSort.sort(inputArray); - String[] expectedArray = { - "3ftM", - "C5Qi", - "F6w9", - "btGF", - "dIxH", - "hc4n", - "kRzy", - "l1qz", - "larj", - "vnNH" - }; + String[] expectedArray + = {"3ftM", "C5Qi", "F6w9", "btGF", "dIxH", "hc4n", "kRzy", "l1qz", "larj", "vnNH"}; assertArrayEquals(outputArray, expectedArray); } - @Test + @Test public void treeSortIntegerArray() { - Integer[] inputArray = { -97, -44, -4, -85, -92, 74, 79, -26, 76, -5 }; + Integer[] inputArray = {-97, -44, -4, -85, -92, 74, 79, -26, 76, -5}; Integer[] outputArray = treeSort.sort(inputArray); - Integer[] expectedArray = { -97, -92, -85, -44, -26, -5, -4, 74, 76, 79 }; + Integer[] expectedArray = {-97, -92, -85, -44, -26, -5, -4, 74, 76, 79}; assertArrayEquals(outputArray, expectedArray); } @Test public void treeSortDoubleArray() { - Double[] inputArray = { - 0.8047485045, 0.4493112337, - 0.8298433723, 0.2691406748, - 0.2482782839, 0.5976243420, - 0.6746235284, 0.0552623569, - 0.3515624123, 0.0536747336 - }; + Double[] inputArray = {0.8047485045, 0.4493112337, 0.8298433723, 0.2691406748, 0.2482782839, + 0.5976243420, 0.6746235284, 0.0552623569, 0.3515624123, 0.0536747336}; Double[] outputArray = treeSort.sort(inputArray); - Double[] expectedArray = { - 0.0536747336, 0.0552623569, - 0.2482782839, 0.2691406748, - 0.3515624123, 0.4493112337, - 0.5976243420, 0.6746235284, - 0.8047485045, 0.8298433723 - }; + Double[] expectedArray = {0.0536747336, 0.0552623569, 0.2482782839, 0.2691406748, + 0.3515624123, 0.4493112337, 0.5976243420, 0.6746235284, 0.8047485045, 0.8298433723}; assertArrayEquals(outputArray, expectedArray); } } diff --git a/src/test/java/com/thealgorithms/sorts/WiggleSortTest.java b/src/test/java/com/thealgorithms/sorts/WiggleSortTest.java index cddbb432..449c8c11 100644 --- a/src/test/java/com/thealgorithms/sorts/WiggleSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/WiggleSortTest.java @@ -10,8 +10,8 @@ public class WiggleSortTest { @Test void WiggleTestNumbersEven() { WiggleSort wiggleSort = new WiggleSort(); - Integer[] values = { 1, 2, 3, 4 }; - Integer[] result = { 1, 4, 2, 3 }; + Integer[] values = {1, 2, 3, 4}; + Integer[] result = {1, 4, 2, 3}; wiggleSort.sort(values); assertArrayEquals(values, result); } @@ -19,8 +19,8 @@ public class WiggleSortTest { @Test void WiggleTestNumbersOdd() { WiggleSort wiggleSort = new WiggleSort(); - Integer[] values = { 1, 2, 3, 4, 5 }; - Integer[] result = { 3, 5, 1, 4, 2 }; + Integer[] values = {1, 2, 3, 4, 5}; + Integer[] result = {3, 5, 1, 4, 2}; wiggleSort.sort(values); assertArrayEquals(values, result); } @@ -28,8 +28,8 @@ public class WiggleSortTest { @Test void WiggleTestNumbersOddDuplicates() { WiggleSort wiggleSort = new WiggleSort(); - Integer[] values = { 7, 2, 2, 2, 5 }; - Integer[] result = { 2, 7, 2, 5, 2 }; + Integer[] values = {7, 2, 2, 2, 5}; + Integer[] result = {2, 7, 2, 5, 2}; wiggleSort.sort(values); assertArrayEquals(values, result); } @@ -37,8 +37,8 @@ public class WiggleSortTest { @Test void WiggleTestNumbersOddMultipleDuplicates() { WiggleSort wiggleSort = new WiggleSort(); - Integer[] values = { 1, 1, 2, 2, 5 }; - Integer[] result = { 2, 5, 1, 2, 1 }; + Integer[] values = {1, 1, 2, 2, 5}; + Integer[] result = {2, 5, 1, 2, 1}; wiggleSort.sort(values); assertArrayEquals(values, result); } @@ -46,8 +46,8 @@ public class WiggleSortTest { @Test void WiggleTestNumbersEvenMultipleDuplicates() { WiggleSort wiggleSort = new WiggleSort(); - Integer[] values = { 1, 1, 2, 2, 2, 5 }; - Integer[] result = { 2, 5, 1, 2, 1, 2 }; + Integer[] values = {1, 1, 2, 2, 2, 5}; + Integer[] result = {2, 5, 1, 2, 1, 2}; wiggleSort.sort(values); System.out.println(Arrays.toString(values)); assertArrayEquals(values, result); @@ -56,8 +56,8 @@ public class WiggleSortTest { @Test void WiggleTestNumbersEvenDuplicates() { WiggleSort wiggleSort = new WiggleSort(); - Integer[] values = { 1, 2, 4, 4 }; - Integer[] result = { 1, 4, 2, 4 }; + Integer[] values = {1, 2, 4, 4}; + Integer[] result = {1, 4, 2, 4}; wiggleSort.sort(values); assertArrayEquals(values, result); } @@ -65,8 +65,8 @@ public class WiggleSortTest { @Test void WiggleTestStrings() { WiggleSort wiggleSort = new WiggleSort(); - String[] values = { "a", "b", "d", "c" }; - String[] result = { "a", "d", "b", "c" }; + String[] values = {"a", "b", "d", "c"}; + String[] result = {"a", "d", "b", "c"}; wiggleSort.sort(values); assertArrayEquals(values, result); } diff --git a/src/test/java/com/thealgorithms/strings/HammingDistanceTest.java b/src/test/java/com/thealgorithms/strings/HammingDistanceTest.java index 386ad125..1fac37a6 100644 --- a/src/test/java/com/thealgorithms/strings/HammingDistanceTest.java +++ b/src/test/java/com/thealgorithms/strings/HammingDistanceTest.java @@ -10,30 +10,16 @@ public class HammingDistanceTest { @Test void testHammingDistance() throws Exception { assertEquals(HammingDistance.calculateHammingDistance("", ""), 0); - assertEquals( - HammingDistance.calculateHammingDistance("java", "java"), - 0 - ); - assertEquals( - HammingDistance.calculateHammingDistance("karolin", "kathrin"), - 3 - ); - assertEquals( - HammingDistance.calculateHammingDistance("kathrin", "kerstin"), - 4 - ); - assertEquals( - HammingDistance.calculateHammingDistance("00000", "11111"), - 5 - ); + assertEquals(HammingDistance.calculateHammingDistance("java", "java"), 0); + assertEquals(HammingDistance.calculateHammingDistance("karolin", "kathrin"), 3); + assertEquals(HammingDistance.calculateHammingDistance("kathrin", "kerstin"), 4); + assertEquals(HammingDistance.calculateHammingDistance("00000", "11111"), 5); } @Test void testNotEqualStringLengths() { Exception exception = assertThrows( - Exception.class, - () -> HammingDistance.calculateHammingDistance("ab", "abc") - ); + Exception.class, () -> HammingDistance.calculateHammingDistance("ab", "abc")); assertEquals("String lengths must be equal", exception.getMessage()); } } diff --git a/src/test/java/com/thealgorithms/strings/HorspoolSearchTest.java b/src/test/java/com/thealgorithms/strings/HorspoolSearchTest.java index 9240ac8a..243edf4f 100644 --- a/src/test/java/com/thealgorithms/strings/HorspoolSearchTest.java +++ b/src/test/java/com/thealgorithms/strings/HorspoolSearchTest.java @@ -1,9 +1,9 @@ package com.thealgorithms.strings; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + class HorspoolSearchTest { @Test @@ -76,13 +76,12 @@ class HorspoolSearchTest { @Test void testFindFirstPatternNull() { - assertThrows(NullPointerException.class, - () -> HorspoolSearch.findFirst(null, "Hello World")); + assertThrows( + NullPointerException.class, () -> HorspoolSearch.findFirst(null, "Hello World")); } @Test void testFindFirstTextNull() { - assertThrows(NullPointerException.class, - () -> HorspoolSearch.findFirst("Hello", null)); + assertThrows(NullPointerException.class, () -> HorspoolSearch.findFirst("Hello", null)); } } \ No newline at end of file diff --git a/src/test/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumberTest.java b/src/test/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumberTest.java index 08d94250..7392ce2d 100644 --- a/src/test/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumberTest.java +++ b/src/test/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumberTest.java @@ -1,7 +1,8 @@ package com.thealgorithms.strings; -import java.util.*; import static org.junit.jupiter.api.Assertions.*; + +import java.util.*; import org.junit.jupiter.api.Test; public class LetterCombinationsOfPhoneNumberTest { @@ -21,14 +22,14 @@ public class LetterCombinationsOfPhoneNumberTest { // ** Test 2 ** // Input: digits = "2" // Output: ["a","b","c"] - int[] numbers2 = { 2 }; + int[] numbers2 = {2}; List output2 = Arrays.asList("a", "b", "c"); assertTrue(ob.printWords(numbers2, numbers2.length, 0, "").equals(output2)); // ** Test 3 ** // Input: digits = "23" // Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"] - int[] numbers3 = { 2, 3 }; + int[] numbers3 = {2, 3}; List output3 = Arrays.asList("ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"); assertTrue(ob.printWords(numbers3, numbers3.length, 0, "").equals(output3)); @@ -37,10 +38,10 @@ public class LetterCombinationsOfPhoneNumberTest { // Output: ["adg", "adh", "adi", "aeg", "aeh", "aei", "afg", "afh", "afi", // "bdg", "bdh", "bdi", "beg", "beh", "bei", "bfg", "bfh", "bfi", "cdg", "cdh", // "cdi", "ceg", "ceh", "cei", "cfg", "cfh", "cfi"] - int[] numbers4 = { 2, 3, 4 }; - List output4 = Arrays.asList("adg", "adh", "adi", "aeg", "aeh", "aei", "afg", "afh", "afi", "bdg", - "bdh", "bdi", "beg", "beh", "bei", "bfg", "bfh", "bfi", "cdg", "cdh", "cdi", "ceg", "ceh", "cei", "cfg", - "cfh", "cfi"); + int[] numbers4 = {2, 3, 4}; + List output4 = Arrays.asList("adg", "adh", "adi", "aeg", "aeh", "aei", "afg", "afh", + "afi", "bdg", "bdh", "bdi", "beg", "beh", "bei", "bfg", "bfh", "bfi", "cdg", "cdh", + "cdi", "ceg", "ceh", "cei", "cfg", "cfh", "cfi"); assertTrue(ob.printWords(numbers4, numbers4.length, 0, "").equals(output4)); } } diff --git a/src/test/java/com/thealgorithms/strings/LowerTest.java b/src/test/java/com/thealgorithms/strings/LowerTest.java index 7e3ab762..ebc72f3c 100644 --- a/src/test/java/com/thealgorithms/strings/LowerTest.java +++ b/src/test/java/com/thealgorithms/strings/LowerTest.java @@ -1,16 +1,16 @@ package com.thealgorithms.strings; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + public class LowerTest { @Test public void toLowerCase() { String input1 = "hello world"; String input2 = "HelLO WoRld"; String input3 = "HELLO WORLD"; - + assertEquals("hello world", Lower.toLowerCase(input1)); assertEquals("hello world", Lower.toLowerCase(input2)); assertEquals("hello world", Lower.toLowerCase(input3)); diff --git a/src/test/java/com/thealgorithms/strings/MyAtoiTest.java b/src/test/java/com/thealgorithms/strings/MyAtoiTest.java index 29dda8c0..6d27a8ac 100644 --- a/src/test/java/com/thealgorithms/strings/MyAtoiTest.java +++ b/src/test/java/com/thealgorithms/strings/MyAtoiTest.java @@ -1,26 +1,26 @@ package com.thealgorithms.strings; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + public class MyAtoiTest { - + @Test void testOne() { assertEquals(42, MyAtoi.myAtoi("42")); } - + @Test void testTwo() { assertEquals(-42, MyAtoi.myAtoi(" -42")); } - + @Test void testThree() { assertEquals(4193, MyAtoi.myAtoi("4193 with words")); } - + @Test void testFour() { assertEquals(0, MyAtoi.myAtoi("0")); diff --git a/src/test/java/com/thealgorithms/strings/PalindromeTest.java b/src/test/java/com/thealgorithms/strings/PalindromeTest.java index 0545cdb9..a3390ff1 100644 --- a/src/test/java/com/thealgorithms/strings/PalindromeTest.java +++ b/src/test/java/com/thealgorithms/strings/PalindromeTest.java @@ -8,19 +8,16 @@ public class PalindromeTest { @Test public void palindrome() { - String[] palindromes = { null, "", "aba", "123321", "kayak" }; + String[] palindromes = {null, "", "aba", "123321", "kayak"}; for (String s : palindromes) { - Assertions.assertTrue(Palindrome.isPalindrome(s) && - Palindrome.isPalindromeRecursion(s) && - Palindrome.isPalindromeTwoPointer(s)); + Assertions.assertTrue(Palindrome.isPalindrome(s) && Palindrome.isPalindromeRecursion(s) + && Palindrome.isPalindromeTwoPointer(s)); } - String[] notPalindromes = { "abb", "abc", "abc123", "kayaks" }; + String[] notPalindromes = {"abb", "abc", "abc123", "kayaks"}; for (String s : notPalindromes) { - Assertions.assertFalse(Palindrome.isPalindrome(s) || - Palindrome.isPalindromeRecursion(s) || - Palindrome.isPalindromeTwoPointer(s)); + Assertions.assertFalse(Palindrome.isPalindrome(s) || Palindrome.isPalindromeRecursion(s) + || Palindrome.isPalindromeTwoPointer(s)); } - } } diff --git a/src/test/java/com/thealgorithms/strings/PangramTest.java b/src/test/java/com/thealgorithms/strings/PangramTest.java index d3789d49..970e7280 100644 --- a/src/test/java/com/thealgorithms/strings/PangramTest.java +++ b/src/test/java/com/thealgorithms/strings/PangramTest.java @@ -1,6 +1,7 @@ package com.thealgorithms.strings; import static org.junit.jupiter.api.Assertions.*; + import org.junit.jupiter.api.Test; public class PangramTest { @@ -8,12 +9,14 @@ public class PangramTest { @Test public void testPangram() { assertTrue(Pangram.isPangram("The quick brown fox jumps over the lazy dog")); - assertFalse(Pangram.isPangram("The quick brown fox jumps over the azy dog")); // L is missing + assertFalse( + Pangram.isPangram("The quick brown fox jumps over the azy dog")); // L is missing assertFalse(Pangram.isPangram("+-1234 This string is not alphabetical")); assertFalse(Pangram.isPangram("\u0000/\\ Invalid characters are alright too")); - + assertTrue(Pangram.isPangram2("The quick brown fox jumps over the lazy dog")); - assertFalse(Pangram.isPangram2("The quick brown fox jumps over the azy dog")); // L is missing + assertFalse( + Pangram.isPangram2("The quick brown fox jumps over the azy dog")); // L is missing assertFalse(Pangram.isPangram2("+-1234 This string is not alphabetical")); assertFalse(Pangram.isPangram2("\u0000/\\ Invalid characters are alright too")); } diff --git a/src/test/java/com/thealgorithms/strings/ReverseStringRecursiveTest.java b/src/test/java/com/thealgorithms/strings/ReverseStringRecursiveTest.java index ccf68e1c..f36994be 100644 --- a/src/test/java/com/thealgorithms/strings/ReverseStringRecursiveTest.java +++ b/src/test/java/com/thealgorithms/strings/ReverseStringRecursiveTest.java @@ -1,33 +1,33 @@ package com.thealgorithms.strings; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + public class ReverseStringRecursiveTest { ReverseStringRecursive stringRecursive = new ReverseStringRecursive(); @Test void shouldAcceptWhenEmptyStringIsPassed() { String expected = ""; - String reversed = stringRecursive.reverse(""); + String reversed = stringRecursive.reverse(""); - assertEquals(expected,reversed); + assertEquals(expected, reversed); } @Test void shouldAcceptNotWhenWhenSingleCharacterIsPassed() { String expected = "a"; - String reversed = stringRecursive.reverse("a"); + String reversed = stringRecursive.reverse("a"); - assertEquals(expected,reversed); + assertEquals(expected, reversed); } @Test void shouldAcceptWhenStringIsPassed() { String expected = "dlroWolleH"; - String reversed = stringRecursive.reverse("HelloWorld"); + String reversed = stringRecursive.reverse("HelloWorld"); - assertEquals(expected,reversed); + assertEquals(expected, reversed); } } diff --git a/src/test/java/com/thealgorithms/strings/ReverseStringTest.java b/src/test/java/com/thealgorithms/strings/ReverseStringTest.java index b190a437..137ec7a9 100644 --- a/src/test/java/com/thealgorithms/strings/ReverseStringTest.java +++ b/src/test/java/com/thealgorithms/strings/ReverseStringTest.java @@ -1,9 +1,9 @@ package com.thealgorithms.strings; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + public class ReverseStringTest { @Test diff --git a/src/test/java/com/thealgorithms/strings/RotationTest.java b/src/test/java/com/thealgorithms/strings/RotationTest.java index 781a68d8..239366df 100644 --- a/src/test/java/com/thealgorithms/strings/RotationTest.java +++ b/src/test/java/com/thealgorithms/strings/RotationTest.java @@ -11,5 +11,5 @@ public class RotationTest { assertEquals("eksge", Rotation.rotation("geeks", 2)); assertEquals("anasban", Rotation.rotation("bananas", 3)); assertEquals("abracadabra", Rotation.rotation("abracadabra", 0)); - } + } } diff --git a/src/test/java/com/thealgorithms/strings/StringCompressionTest.java b/src/test/java/com/thealgorithms/strings/StringCompressionTest.java index d02e83ce..4194cad0 100644 --- a/src/test/java/com/thealgorithms/strings/StringCompressionTest.java +++ b/src/test/java/com/thealgorithms/strings/StringCompressionTest.java @@ -1,13 +1,14 @@ package com.thealgorithms.strings; import static org.junit.jupiter.api.Assertions.*; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; public class StringCompressionTest { @ParameterizedTest - @CsvSource({"a,a","aabbb,a2b3","abbbc,ab3c","aabccd,a2bc2d"}) - void stringCompressionTest(String input,String expectedOutput){ - String output=StringCompression.compress(input); + @CsvSource({"a,a", "aabbb,a2b3", "abbbc,ab3c", "aabccd,a2bc2d"}) + void stringCompressionTest(String input, String expectedOutput) { + String output = StringCompression.compress(input); assertEquals(expectedOutput, output); } } diff --git a/src/test/java/com/thealgorithms/strings/ValidParenthesesTest.java b/src/test/java/com/thealgorithms/strings/ValidParenthesesTest.java index ab215f22..13909e63 100644 --- a/src/test/java/com/thealgorithms/strings/ValidParenthesesTest.java +++ b/src/test/java/com/thealgorithms/strings/ValidParenthesesTest.java @@ -1,24 +1,23 @@ package com.thealgorithms.strings; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + public class ValidParenthesesTest { - + @Test void testOne() { assertEquals(true, ValidParentheses.isValid("()")); } - + @Test void testTwo() { assertEquals(true, ValidParentheses.isValid("()[]{}")); } - - + @Test void testThree() { assertEquals(false, ValidParentheses.isValid("(]")); } - } diff --git a/src/test/java/com/thealgorithms/strings/WordLadderTest.java b/src/test/java/com/thealgorithms/strings/WordLadderTest.java index ad572a13..5b40df8b 100644 --- a/src/test/java/com/thealgorithms/strings/WordLadderTest.java +++ b/src/test/java/com/thealgorithms/strings/WordLadderTest.java @@ -1,14 +1,15 @@ package com.thealgorithms.strings; import static org.junit.jupiter.api.Assertions.*; -import org.junit.jupiter.api.Test; + import java.util.*; +import org.junit.jupiter.api.Test; public class WordLadderTest { @Test public void testWordLadder() { - + /** * Test 1: * Input: beginWord = "hit", endWord = "cog", wordList = @@ -33,6 +34,5 @@ public class WordLadderTest { List wordList2 = Arrays.asList("hot", "dot", "dog", "lot", "log"); assertEquals(WordLadder.ladderLength("hit", "cog", wordList2), 0); - - } + } } diff --git a/src/test/java/com/thealgorithms/strings/longestNonRepeativeSubstringTest.java b/src/test/java/com/thealgorithms/strings/longestNonRepeativeSubstringTest.java index dac3cc85..2dce8cf3 100644 --- a/src/test/java/com/thealgorithms/strings/longestNonRepeativeSubstringTest.java +++ b/src/test/java/com/thealgorithms/strings/longestNonRepeativeSubstringTest.java @@ -9,13 +9,7 @@ public class longestNonRepeativeSubstringTest { public void palindrome() { String input1 = "HelloWorld"; String input2 = "javaIsAProgrammingLanguage"; - Assertions.assertEquals( - longestNonRepeativeSubstring.lengthOfLongestSubstring(input1), - 5 - ); - Assertions.assertEquals( - longestNonRepeativeSubstring.lengthOfLongestSubstring(input2), - 9 - ); + Assertions.assertEquals(longestNonRepeativeSubstring.lengthOfLongestSubstring(input1), 5); + Assertions.assertEquals(longestNonRepeativeSubstring.lengthOfLongestSubstring(input2), 9); } } diff --git a/src/test/java/com/thealgorithms/strings/zigZagPattern/zigZagPatternTest.java b/src/test/java/com/thealgorithms/strings/zigZagPattern/zigZagPatternTest.java index 81d42af9..02904ddc 100644 --- a/src/test/java/com/thealgorithms/strings/zigZagPattern/zigZagPatternTest.java +++ b/src/test/java/com/thealgorithms/strings/zigZagPattern/zigZagPatternTest.java @@ -9,13 +9,7 @@ public class zigZagPatternTest { public void palindrome() { String input1 = "HelloWorldFromJava"; String input2 = "javaIsAProgrammingLanguage"; - Assertions.assertEquals( - zigZagPattern.encode(input1, 4), - "HooeWrrmalolFJvlda" - ); - Assertions.assertEquals( - zigZagPattern.encode(input2, 4), - "jAaLgasPrmgaaevIrgmnnuaoig" - ); + Assertions.assertEquals(zigZagPattern.encode(input1, 4), "HooeWrrmalolFJvlda"); + Assertions.assertEquals(zigZagPattern.encode(input2, 4), "jAaLgasPrmgaaevIrgmnnuaoig"); } }